diff --git a/backend/src/services/config-mutation-lock.ts b/backend/src/services/config-mutation-lock.ts index 39c3d217..bc59bb60 100644 --- a/backend/src/services/config-mutation-lock.ts +++ b/backend/src/services/config-mutation-lock.ts @@ -80,10 +80,29 @@ export async function withApplicationMutationLock(work: () => Promise, opt /** Collectors coexist with each other but exclude configuration mutation for * the complete native/sample/status operation. This lock grants no authority. * Verified operations retain their original exact exclusive client protocol. */ -export async function withApplicationCollectorLock(work: () => Promise): Promise { +export async function withApplicationCollectorLock(work: () => Promise, { waitMs = 5000 }: { waitMs?: number } = {}): Promise { assertOperationConfigurationLockScope() if (applicationLease.getStore()?.active || captureOperationConfigurationLockHandoff()) return withApplicationMutationLock(work) if (collectorLease.getStore()?.active) return work() + const deadline = performance.now() + waitMs + for (;;) { + let admitted = false + try { + return await tryApplicationCollectorLock(() => { + admitted = true + return work() + }) + } catch (error) { + const remaining = deadline - performance.now() + if (admitted || !(error instanceof ConfigurationBusyError) || remaining <= 0) throw error + // Release the failed attempt's connection before waiting for the writer. + await delay(Math.min(250, remaining)) + if (performance.now() >= deadline) throw error + } + } +} + +async function tryApplicationCollectorLock(work: () => Promise): Promise { let complete!: () => void const completed = new Promise(resolve => { complete = resolve }) const client = await pool.connect(), context = { active: true, completed } diff --git a/backend/src/services/routing-catalog-observation.sql-helper.ts b/backend/src/services/routing-catalog-observation.sql-helper.ts index ed3cb184..2d1c28e2 100644 --- a/backend/src/services/routing-catalog-observation.sql-helper.ts +++ b/backend/src/services/routing-catalog-observation.sql-helper.ts @@ -100,6 +100,27 @@ export async function checkCatalogReadContention(serverId: number) { const load = () => Promise.all([readFilterRulesCatalog([server], { source: "live", persistObserved: true }), readRecursiveCatalogForServer(server), readRecursiveRoutesForServer(server)]) try { + const jobs = ["uptime_resources", "uptime_ping"] + const startedAt = new Date().toISOString() + const pending = await withApplicationMutationLock(async () => { + const runs = independent.runInAsyncScope(() => Promise.all(jobs.map(runSchedulerJobNow))) + const state = await Promise.race([runs.then(() => "finished", () => "failed"), delay(600, "waiting")]) + assert.equal(state, "waiting", "Scheduler must wait for a transient exclusive lock") + await independent.runInAsyncScope(() => assert.rejects( + withApplicationCollectorLock(async () => assert.fail("Collector entered during a write"), { waitMs: 50 }), + ConfigurationBusyError, + )) + return { runs } + }) + assert.deepEqual((await pending.runs).map(run => run.status), ["ok", "ok"]) + const { rows } = await pool.query("SELECT job_key,status FROM scheduler_runs WHERE started_at >= $1 AND job_key=ANY($2::text[]) ORDER BY job_key", [startedAt, jobs]) + assert.deepEqual(rows, [{ job_key: "uptime_ping", status: "ok" }, { job_key: "uptime_resources", status: "ok" }]) + let executions = 0 + await assert.rejects(withApplicationCollectorLock(async () => { + executions++ + throw new ConfigurationBusyError("server") + }), ConfigurationBusyError) + assert.equal(executions, 1, "An admitted collector must never be replayed") const cold = await Promise.all(Array.from({ length: 24 }, load)) assert(cold.every(([filters, catalog, routes]) => filters[0].live && catalog.live && routes.live)) const revisions = () => pool.query("SELECT section,source FROM config_revisions WHERE server_id=$1 ORDER BY section,created_at", [server.id]) diff --git a/backend/src/services/routing-catalog-observation.ts b/backend/src/services/routing-catalog-observation.ts index 8a436e14..48ca00ef 100644 --- a/backend/src/services/routing-catalog-observation.ts +++ b/backend/src/services/routing-catalog-observation.ts @@ -78,7 +78,7 @@ export async function readCatalogWithObservedCache void catalogRefreshes.set(serverId, new Promise(resolve => { done = resolve })) try { - return await enterCatalogLock(work => withApplicationCollectorLock(() => withConfigMutationLock([serverId], work)), async () => { + return await enterCatalogLock(work => withApplicationCollectorLock(() => withConfigMutationLock([serverId], work), { waitMs: 0 }), async () => { await assertCatalogSource(server) const latest = await read(true) return latest.current ? latest : save(latest)