25 lines
1.5 KiB
TypeScript
25 lines
1.5 KiB
TypeScript
import { asc, eq, sql } from "drizzle-orm"
|
|
import { emptySpeedProbeObservations, type SpeedProbeWrite } from "@mmapp/contracts"
|
|
import { db } from "../db/index.js"
|
|
import { uptimeSpeedProbes } from "../db/schema.js"
|
|
import { replaceSpeedProbes } from "./speed-probe-replacement.js"
|
|
import { executeGuardedApplicationWrite } from "./config-mutation-policy.js"
|
|
|
|
export async function readSpeedProbeCatalog() {
|
|
return db.select().from(uptimeSpeedProbes).orderBy(asc(uptimeSpeedProbes.sortOrder))
|
|
}
|
|
export function replaceSpeedProbeCatalog(probes: SpeedProbeWrite[]) {
|
|
return executeGuardedApplicationWrite({ kind: "speed-probe-catalog", id: "all" }, "all", () => replaceSpeedProbes({ transaction: run => db.transaction(async tx => {
|
|
await tx.execute(sql`select pg_advisory_xact_lock(hashtext('uptime-speed-probes'))`)
|
|
await run({
|
|
listProbes: async () => tx.select().from(uptimeSpeedProbes).for("update"),
|
|
remove: async id => { await tx.delete(uptimeSpeedProbes).where(eq(uptimeSpeedProbes.id, id)) },
|
|
upsert: async (row, createdAt, resetObservations) => {
|
|
const { id, ...patch } = row
|
|
await tx.insert(uptimeSpeedProbes).values({ id, ...patch, createdAt })
|
|
.onConflictDoUpdate({ target: uptimeSpeedProbes.id, set: { ...patch, ...(resetObservations ? emptySpeedProbeObservations : {}) } })
|
|
},
|
|
})
|
|
}) }, probes), async () => [...new Set([...(await readSpeedProbeCatalog()).map(row => row.id), ...probes.map(row => row.id)])].map(id => ({ kind: "speed-probe", id })))
|
|
}
|