diff --git a/convex/machines.ts b/convex/machines.ts index 9f95303..ac8c5a7 100644 --- a/convex/machines.ts +++ b/convex/machines.ts @@ -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) diff --git a/convex/schema.ts b/convex/schema.ts index 7488363..d11344a 100644 --- a/convex/schema.ts +++ b/convex/schema.ts @@ -379,5 +379,7 @@ export default defineSchema({ }) .index("by_token_hash", ["tokenHash"]) .index("by_machine", ["machineId"]) - .index("by_tenant_machine", ["tenantId", "machineId"]), + .index("by_tenant_machine", ["tenantId", "machineId"]) + .index("by_machine_created", ["machineId", "createdAt"]) + .index("by_machine_revoked_expires", ["machineId", "revoked", "expiresAt"]), });