perf: optimize machine token lookup
This commit is contained in:
parent
38b46f32ce
commit
4c848486a6
2 changed files with 17 additions and 14 deletions
|
|
@ -5,7 +5,7 @@ import { ConvexError, v } from "convex/values"
|
|||
import { sha256 } from "@noble/hashes/sha256"
|
||||
import { randomBytes } from "@noble/hashes/utils"
|
||||
import type { Doc, Id } from "./_generated/dataModel"
|
||||
import type { MutationCtx } from "./_generated/server"
|
||||
import type { MutationCtx, QueryCtx } from "./_generated/server"
|
||||
import { normalizeStatus } from "./tickets"
|
||||
|
||||
const DEFAULT_TENANT_ID = "tenant-atlas"
|
||||
|
|
@ -62,6 +62,17 @@ function normalizeIdentifiers(macAddresses: string[], serialNumbers: string[]):
|
|||
return { macs, serials }
|
||||
}
|
||||
|
||||
async function findActiveMachineToken(ctx: QueryCtx, machineId: Id<"machines">, now: number) {
|
||||
const tokens = await ctx.db
|
||||
.query("machineTokens")
|
||||
.withIndex("by_machine_revoked_expires", (q) =>
|
||||
q.eq("machineId", machineId).eq("revoked", false).gt("expiresAt", now),
|
||||
)
|
||||
.collect()
|
||||
|
||||
return tokens.length > 0 ? tokens[0]! : null
|
||||
}
|
||||
|
||||
function toHex(input: Uint8Array) {
|
||||
return Array.from(input)
|
||||
.map((byte) => byte.toString(16).padStart(2, "0"))
|
||||
|
|
@ -762,12 +773,7 @@ export const listByTenant = query({
|
|||
|
||||
return Promise.all(
|
||||
machines.map(async (machine) => {
|
||||
const tokens = await ctx.db
|
||||
.query("machineTokens")
|
||||
.withIndex("by_machine", (q) => q.eq("machineId", machine._id))
|
||||
.collect()
|
||||
|
||||
const activeToken = tokens.find((token) => !token.revoked && token.expiresAt > now) ?? null
|
||||
const activeToken = await findActiveMachineToken(ctx, machine._id, now)
|
||||
const offlineThresholdMs = getOfflineThresholdMs()
|
||||
const staleThresholdMs = getStaleThresholdMs(offlineThresholdMs)
|
||||
const manualStatus = (machine.status ?? "").toLowerCase()
|
||||
|
|
@ -893,12 +899,7 @@ export const getById = query({
|
|||
}
|
||||
const resolvedCompany = companyFromId ?? companyFromSlug
|
||||
|
||||
const tokens = await ctx.db
|
||||
.query("machineTokens")
|
||||
.withIndex("by_machine", (q) => q.eq("machineId", machine._id))
|
||||
.collect()
|
||||
|
||||
const activeToken = tokens.find((token) => !token.revoked && token.expiresAt > now) ?? null
|
||||
const activeToken = await findActiveMachineToken(ctx, machine._id, now)
|
||||
|
||||
const offlineThresholdMs = getOfflineThresholdMs()
|
||||
const staleThresholdMs = getStaleThresholdMs(offlineThresholdMs)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue