28 lines
1.5 KiB
TypeScript
28 lines
1.5 KiB
TypeScript
import { and, eq, inArray, lte } from "drizzle-orm"
|
|
import { db } from "../db/index.js"
|
|
import { trafficCollectionState, trafficSettings, type Server } from "../db/schema.js"
|
|
|
|
export async function recordTrafficCollectionAttempt(server: Pick<Server, "id" | "updatedAt">,
|
|
status: "pending" | "ok" | "error", sampledAt: string, error?: string) {
|
|
if (status === "pending") {
|
|
const next = { serverId: server.id, serverUpdatedAt: server.updatedAt,
|
|
lastAttemptAt: sampledAt, status, error: null }
|
|
await db.insert(trafficCollectionState).values(next).onConflictDoUpdate({
|
|
target: trafficCollectionState.serverId, set: next,
|
|
setWhere: lte(trafficCollectionState.lastAttemptAt, sampledAt),
|
|
})
|
|
} else {
|
|
await db.update(trafficCollectionState).set({ status, error: error?.slice(0, 1024) ?? null,
|
|
...(status === "ok" ? { lastSucceededAt: sampledAt } : {}) }).where(and(
|
|
eq(trafficCollectionState.serverId, server.id), eq(trafficCollectionState.lastAttemptAt, sampledAt),
|
|
))
|
|
}
|
|
}
|
|
|
|
/** Read-only: does not create default settings or contact a device. */
|
|
export async function readTrafficCollectionContext(serverIds?: readonly number[]) {
|
|
const [states, settings] = await Promise.all([db.select().from(trafficCollectionState).where(serverIds === undefined ? undefined : inArray(trafficCollectionState.serverId, [...serverIds])),
|
|
db.select().from(trafficSettings).where(eq(trafficSettings.id, 1)).limit(1)])
|
|
return { states: new Map(states.map(s => [s.serverId, s])), settings: settings[0] }
|
|
}
|