Files
MikrotikManager/backend/src/services/server-poll-storage.test.ts
T

265 lines
21 KiB
TypeScript

import assert from "node:assert/strict"
import { randomUUID } from "node:crypto"
import { test } from "node:test"
import type { ProbeStorageConnection, ProbeStorageOptions, ProbeStorageSql } from "./server-probe-journal-maintenance.js"
import { createServerPollStorageForTests, runPollStorageTransaction, PollStorageRefused, PollStorageUnknown,
type PollStorageBinding, type PollStorageDependencies } from "./server-poll-storage.js"
type State = { admission?: Record<string, unknown>; anchors: string[]; quarantines: Record<string, unknown>[] }
const gate = () => { let resolve!: () => void; const promise = new Promise<void>(done => { resolve = done }); return { promise, resolve } }
const safe = (error: unknown) => (error instanceof PollStorageRefused || error instanceof PollStorageUnknown) && !error.message.includes("PRIVATE_PROVIDER")
function fixture() {
let now = Date.now(), state: State = { anchors: [], quarantines: [] }, lostCommit = 0, commits = 0, revoked = false, authorizations = 0
let phaseAfterReservation: string | undefined
const leases: { commands: string[]; releases: boolean[]; options: ProbeStorageOptions; timeouts: number[] }[] = [], events: string[] = []
const binding: PollStorageBinding = { scope: { receiptId: randomUUID(), kind: "mcp", executionId: randomUUID(), ownerId: "owned-operator", bindingProof: "a".repeat(64), contextProof: "b".repeat(64), issuedAt: now - 1000, expiresAt: now + 60000 },
connectionId: randomUUID(), maxStages: 11, authorize: async () => { authorizations++; if (revoked) throw Error("PRIVATE_PROVIDER revoked") } }
const dependencies: PollStorageDependencies = { now: () => now, connect: async options => {
const number = leases.length + 1, lease = { commands: [] as string[], releases: [] as boolean[], options: { ...options }, timeouts: [] as number[] }
leases.push(lease); events.push("connect:" + number)
let transaction: State | undefined, closed = false
const connection: ProbeStorageConnection = { async query(text, values = [], queryOptions) {
assert(!closed, "A released physical backend must not receive SQL")
lease.commands.push(text); lease.timeouts.push(queryOptions!.timeoutMs); events.push(number + ":" + text)
if (text === "BEGIN") { transaction = structuredClone(state); return { rows: [] } }
if (text === "ROLLBACK") { transaction = undefined; return { rows: [] } }
if (text === "COMMIT") {
assert(transaction); state = transaction; transaction = undefined; commits++
if (commits === 1 && phaseAfterReservation && state.admission) state.admission.storage_state = phaseAfterReservation
if (commits === lostCommit) throw Error("PRIVATE_PROVIDER lost actual COMMIT acknowledgement")
return { rows: [] }
}
assert(transaction)
if (text === "SELECT set_config('TimeZone','UTC',true),set_config('statement_timeout','5000ms',true)" || text.includes("pg_advisory_xact_lock")) return { rows: [] }
if (text.startsWith("SELECT a.receipt_id AS admission_receipt_id")) {
assert.equal(transaction.admission, undefined, "First reservation scans the actual empty fixture ledger")
return { rows: [] }
}
if (text.startsWith("SELECT r.receipt_id FROM server_poll_archives")) return { rows: [] }
if (text.startsWith("SELECT scope,admissions,compacted_admissions,archive_bytes,reserved_rows,reserved_bytes"))
return { rows: [{ scope: "global", admissions: 0, compacted_admissions: 0, archive_bytes: 0, reserved_rows: 0, reserved_bytes: 0 }] }
if (text.startsWith("SELECT * FROM server_poll_storage_admissions")) {
const row = transaction.admission
return { rows: row && (row.receipt_id === values[0] || row.identity_kind === values[1] && row.execution_id === values[2]) ? [structuredClone(row)] : [] }
}
if (text.startsWith("INSERT INTO server_poll_storage_admissions")) {
assert.equal(transaction.admission, undefined)
transaction.admission = { receipt_id: values[0], identity_kind: values[1], execution_id: values[2], connection_id: values[3], owner_id: values[4],
binding_proof: values[5], context_proof: values[6], authority_issued_at: new Date(String(values[7])), authority_expires_at: new Date(String(values[8])),
max_stages: values[9], claim_token: values[10], claim_attempted_at: null, storage_state: "full" }
return { rows: [{ receipt_id: values[0] }] }
}
if (text.startsWith("UPDATE server_poll_storage_admissions SET claim_token=NULL")) {
const row = transaction.admission
if (!row || row.receipt_id !== values[0] || row.claim_token !== values[1] || new Date(row.authority_expires_at as Date).getTime() <= now) return { rows: [] }
row.claim_token = null; row.claim_attempted_at = new Date(now)
return { rows: [{ receipt_id: values[0] }] }
}
if (text.startsWith("SELECT receipt_id,identity_kind,execution_id,context_proof FROM server_poll_quarantines")) return { rows: structuredClone(transaction.quarantines.filter(row => row.receipt_id === values[0])) }
if (text.startsWith("INSERT INTO server_poll_quarantines")) {
assert(transaction.admission); assert(!transaction.quarantines.some(row => row.receipt_id === values[0]))
transaction.quarantines.push({ receipt_id: values[0], identity_kind: values[1], execution_id: values[2], context_proof: values[3] }); return { rows: [] }
}
if (text.startsWith("INSERT INTO server_poll_executions")) { transaction.anchors.push(String(values[0])); return { rows: [] } }
if (text === "SELECT bounded_callback") return { rows: [] }
throw Error("Unapproved fake SQL; PRIVATE_PROVIDER")
}, release(unsafe = false) { assert(!closed, "Release exactly once"); closed = true; transaction = undefined; lease.releases.push(unsafe); events.push("release:" + number + ":" + unsafe) } }
return connection
} }
const options = () => ({ deadlineAt: now + 2000 })
const anchor = (sql: ProbeStorageSql) => sql.query("INSERT INTO server_poll_executions(receipt_id) VALUES($1)", [binding.scope.receiptId])
return { binding, dependencies, options, anchor, leases, events, state: () => structuredClone(state), now: () => now,
phaseAfterReserve: (phase: string) => { phaseAfterReservation = phase },
phase: (phase: string) => { assert(state.admission); state.admission.storage_state = phase },
advance: (ms: number) => { now += ms }, lose: (which: number) => { lostCommit = which }, revoke: () => { revoked = true }, authorizations: () => authorizations }
}
test("two-phase reservation COMMIT precedes consume/anchor; every transaction owns storage lock first", async () => {
const f = fixture(), storage = createServerPollStorageForTests(f.binding, f.dependencies)
await storage.claim(f.options(), f.anchor)
assert.equal(f.leases.length, 2); assert.deepEqual(f.leases.map(lease => lease.releases), [[false], [false]])
assert(f.events.indexOf("1:COMMIT") < f.events.findIndex(event => event.startsWith("2:UPDATE server_poll_storage_admissions")))
assert(f.events.indexOf("1:COMMIT") < f.events.findIndex(event => event.startsWith("2:INSERT INTO server_poll_executions")))
for (const lease of f.leases) {
assert(lease.commands.findIndex(sql => sql.includes("pg_advisory_xact_lock")) < lease.commands.findIndex(sql => sql.startsWith("SELECT * FROM server_poll_storage_admissions")))
assert(lease.timeouts.every(value => value >= 1 && value <= 5000))
}
const first = f.leases[0].commands
assert(first.findIndex(sql => sql.startsWith("SELECT a.receipt_id AS admission_receipt_id")) < first.findIndex(sql => sql.startsWith("INSERT INTO server_poll_storage_admissions")))
assert(first.findIndex(sql => sql.startsWith("SELECT scope,admissions,compacted_admissions")) < first.findIndex(sql => sql.startsWith("INSERT INTO server_poll_storage_admissions")))
assert.equal(f.state().admission!.claim_token, null); assert.equal(f.state().anchors.length, 1); assert(f.authorizations() > 2)
})
test("phase drift after reservation refuses consume/anchor and later writes require full phase", async () => {
const drift = fixture(); drift.phaseAfterReserve("compacted")
await assert.rejects(createServerPollStorageForTests(drift.binding, drift.dependencies).claim(drift.options(), drift.anchor), PollStorageRefused)
assert.equal(drift.state().anchors.length, 0)
assert.equal(drift.leases.flatMap(lease => lease.commands).some(sql => sql.startsWith("UPDATE server_poll_storage_admissions SET claim_token=NULL")), false)
const f = fixture(), storage = createServerPollStorageForTests(f.binding, f.dependencies)
await storage.claim(f.options(), f.anchor); f.phase("compacted")
let writes = 0
await assert.rejects(storage.write(f.options(), async () => { writes++ }), PollStorageRefused)
assert.equal(writes, 0); assert.equal(f.state().anchors.length, 1)
})
test("lost reservation COMMIT never enters anchor; fresh instance sees spent reservation without renewal", async () => {
const f = fixture(); f.lose(1)
const storage = createServerPollStorageForTests(f.binding, f.dependencies); let callbacks = 0
await assert.rejects(storage.claim(f.options(), async () => { callbacks++ }), PollStorageUnknown)
assert.equal(callbacks, 0); assert(f.state().admission!.claim_token); assert.equal(f.state().anchors.length, 0)
assert.deepEqual(f.leases[0].releases, [true]); assert(!f.leases[0].commands.includes("ROLLBACK"))
await assert.rejects(storage.claim(f.options(), async () => { callbacks++ }), PollStorageRefused)
const restarted = createServerPollStorageForTests(f.binding, f.dependencies)
await assert.rejects(restarted.claim(f.options(), async () => { callbacks++ }), PollStorageRefused)
assert.equal(callbacks, 0); assert.equal(f.leases.flatMap(lease => lease.commands).filter(sql => sql.startsWith("INSERT INTO server_poll_storage_admissions")).length, 1)
})
test("lost consume COMMIT destroys original backend before independent quarantine; no rollback/replay", async () => {
const f = fixture(); f.lose(2)
const storage = createServerPollStorageForTests(f.binding, f.dependencies)
await assert.rejects(storage.claim(f.options(), f.anchor), PollStorageUnknown)
assert.equal(f.state().anchors.length, 1); assert.equal(f.state().admission!.claim_token, null)
assert.deepEqual(f.leases[1].releases, [true]); assert(!f.leases[1].commands.includes("ROLLBACK"))
await storage.quarantine()
assert(f.events.indexOf("release:2:true") < f.events.indexOf("connect:3")); assert.equal(f.state().quarantines.length, 1)
const previous = f.leases.length
await assert.rejects(storage.write(f.options(), async () => {}), PollStorageRefused)
await assert.rejects(storage.claim(f.options(), f.anchor), PollStorageRefused); assert.equal(f.leases.length, previous)
})
test("unknown write COMMIT poisons future work, including fresh instance claim", async () => {
const f = fixture(), storage = createServerPollStorageForTests(f.binding, f.dependencies)
await storage.claim(f.options(), f.anchor); f.lose(3)
await assert.rejects(storage.write(f.options(), sql => sql.query("SELECT bounded_callback")), PollStorageUnknown)
assert(!f.leases[2].commands.includes("ROLLBACK")); assert.deepEqual(f.leases[2].releases, [true])
await assert.rejects(storage.write(f.options(), async () => {}), PollStorageRefused)
await assert.rejects(createServerPollStorageForTests(f.binding, f.dependencies).claim(f.options(), f.anchor), PollStorageRefused)
})
test("callback crypto-gap timeout destroys once and refuses late SQL without fresh checkout", async () => {
const f = fixture(), storage = createServerPollStorageForTests(f.binding, f.dependencies), entered = gate(), resume = gate(), late = gate()
const pending = storage.claim({ deadlineAt: f.now() + 40 }, async sql => {
entered.resolve(); await resume.promise; await assert.rejects(sql.query("SELECT late_source"), safe); late.resolve()
})
await entered.promise; await assert.rejects(pending, PollStorageRefused)
assert.deepEqual(f.leases[1].releases, [true]); assert(!f.leases[1].commands.includes("ROLLBACK"))
const commands = f.leases[1].commands.length; resume.resolve(); await late.promise
assert.equal(f.leases[1].commands.length, commands); assert.deepEqual(f.leases[1].releases, [true]); assert.equal(f.leases.length, 2)
assert.equal(f.state().anchors.length, 0); assert(f.state().admission!.claim_token)
})
test("escaped successful callback facade is inactive after its owner commits", async () => {
const f = fixture(), storage = createServerPollStorageForTests(f.binding, f.dependencies); let escaped!: ProbeStorageSql
await storage.claim(f.options(), async sql => { escaped = sql; await f.anchor(sql) })
const commands = f.leases[1].commands.length
await assert.rejects(escaped.query("SELECT late_source"), PollStorageRefused)
assert.equal(f.leases[1].commands.length, commands); assert.deepEqual(f.leases[1].releases, [false])
})
test("callback cannot dispatch transaction boundaries or multiple statements owned by the host", async () => {
for (const command of ["COMMIT", "/* callback */ ROLLBACK", "-- callback\nBEGIN", "END", "SAVEPOINT nested", "RELEASE nested", "START TRANSACTION", "PREPARE TRANSACTION 'nested'", "SET TRANSACTION READ ONLY", "SELECT bounded_callback; COMMIT"]) {
const f = fixture()
await assert.rejects(runPollStorageTransaction(f.dependencies, f.options(), async () => {}, sql => sql.query(command)), PollStorageRefused)
assert.equal(f.leases.length, 1)
const lease = f.leases[0]
assert.deepEqual(lease.commands.filter(sql => !sql.startsWith("SELECT set_config(") && !sql.includes("pg_advisory_xact_lock")), ["BEGIN", "ROLLBACK"])
assert.deepEqual(lease.releases, [true]); assert.equal(f.state().anchors.length, 0)
}
})
test("ordinary callback SELECT still commits exactly once through its transaction owner", async () => {
const f = fixture()
const result = await runPollStorageTransaction(f.dependencies, f.options(), async () => {}, async sql => {
await sql.query("SELECT bounded_callback"); return "confirmed"
})
assert.equal(result, "confirmed"); assert.equal(f.leases.length, 1)
const lease = f.leases[0]
assert.deepEqual(lease.commands.filter(sql => !sql.startsWith("SELECT set_config(") && !sql.includes("pg_advisory_xact_lock")), ["BEGIN", "SELECT bounded_callback", "COMMIT"])
assert.deepEqual(lease.releases, [false])
})
test("scope, authority provider, connector and clock are captured before any asynchronous work", async () => {
const f = fixture(), original = structuredClone(f.binding.scope), storage = createServerPollStorageForTests(f.binding, f.dependencies)
f.binding.scope.ownerId = "foreign"; f.binding.scope.receiptId = randomUUID(); f.binding.maxStages = 2008; f.binding.connectionId = randomUUID()
f.binding.authorize = async () => { throw Error("Replacement authority must never run") }
f.dependencies.connect = async () => { throw Error("Replacement connector must never run") }; f.dependencies.now = () => 0
await storage.claim(f.options(), sql => sql.query("INSERT INTO server_poll_executions(receipt_id) VALUES($1)", [original.receiptId]))
assert.equal(f.state().admission!.owner_id, original.ownerId); assert.equal(f.state().admission!.receipt_id, original.receiptId)
assert.equal(f.state().admission!.max_stages, 11); assert.equal(f.state().anchors[0], original.receiptId)
})
test("both claim phases retain the accepted signal/deadline even when caller options change", async () => {
const f = fixture(), controller = new AbortController(), replacement = new AbortController()
const options = { deadlineAt: f.now() + 2000, signal: controller.signal }, acceptedDeadline = options.deadlineAt
const originalAuthorize = f.binding.authorize; let changed = false
f.binding.authorize = async value => {
await originalAuthorize(value); assert(Object.isFrozen(value))
if (!changed) { changed = true; options.deadlineAt += 90000; options.signal = replacement.signal }
}
await createServerPollStorageForTests(f.binding, f.dependencies).claim(options, f.anchor)
assert.equal(f.leases.length, 2)
for (const lease of f.leases) { assert.equal(lease.options.deadlineAt, acceptedDeadline); assert.equal(lease.options.signal, controller.signal) }
})
test("transaction entry captures connector, clock and options before an authorization await", async () => {
const f = fixture(), entered = gate(), resume = gate(), controller = new AbortController()
const options = { deadlineAt: f.now() + 2000, signal: controller.signal }, acceptedDeadline = options.deadlineAt
const pending = runPollStorageTransaction(f.dependencies, options, async () => { entered.resolve(); await resume.promise }, async sql => {
await sql.query("SELECT bounded_callback"); return "confirmed"
})
await entered.promise
f.dependencies.connect = async () => { throw Error("Replacement connector must not run") }; f.dependencies.now = () => 0
options.deadlineAt = 0; options.signal = AbortSignal.abort()
resume.resolve(); assert.equal(await pending, "confirmed")
assert.equal(f.leases.length, 1); assert.equal(f.leases[0].options.deadlineAt, acceptedDeadline); assert.equal(f.leases[0].options.signal, controller.signal)
assert.deepEqual(f.leases[0].releases, [false])
})
test("duplicate/fresh claim and foreign owner/receipt/context/connection cannot adopt a reservation", async () => {
const f = fixture(), storage = createServerPollStorageForTests(f.binding, f.dependencies)
await storage.claim(f.options(), f.anchor)
await assert.rejects(storage.claim(f.options(), f.anchor), PollStorageRefused)
for (const changed of [{ scope: { ...f.binding.scope, ownerId: "foreign" } }, { scope: { ...f.binding.scope, receiptId: randomUUID() } },
{ scope: { ...f.binding.scope, contextProof: "c".repeat(64) } }, { connectionId: randomUUID() }]) {
const foreign = createServerPollStorageForTests({ ...f.binding, ...changed }, f.dependencies)
await assert.rejects(foreign.claim(f.options(), async () => assert.fail("Must not write foreign anchor")), PollStorageRefused)
await assert.rejects(foreign.quarantine(), PollStorageRefused)
}
assert.equal(f.state().anchors.length, 1); assert.equal(f.state().quarantines.length, 0)
})
test("quarantine survives original expiry/revocation/abort with independent 10s budget and exact idempotence", async () => {
const f = fixture(), storage = createServerPollStorageForTests(f.binding, f.dependencies), controller = new AbortController()
await storage.claim({ ...f.options(), signal: controller.signal }, f.anchor)
controller.abort(); f.revoke(); f.advance(120000)
const authorizations = f.authorizations(), before = f.now()
await storage.quarantine(); await storage.quarantine()
assert.equal(f.authorizations(), authorizations); assert.equal(f.state().quarantines.length, 1)
for (const lease of f.leases.slice(2)) { assert.equal(lease.options.deadlineAt, before + 10000); assert.equal(lease.options.signal, undefined); assert.deepEqual(lease.releases, [false]) }
await assert.rejects(storage.write(f.options(), async () => {}), PollStorageRefused)
})
test("quarantine cannot create quota-free orphan metadata", async () => {
const f = fixture(), storage = createServerPollStorageForTests(f.binding, f.dependencies)
await assert.rejects(storage.quarantine(), PollStorageRefused)
assert.equal(f.state().admission, undefined); assert.equal(f.state().quarantines.length, 0)
})
test("whole authorization gap and abandoned checkout settle promptly and dispose late backend once", async () => {
const resume = gate(), entered = gate(); let checkouts = 0
const pending = runPollStorageTransaction({ now: Date.now, connect: async () => { checkouts++; throw Error("No checkout expected") } }, { deadlineAt: Date.now() + 30 }, async () => { entered.resolve(); await resume.promise }, async () => {})
await entered.promise; await assert.rejects(pending, PollStorageRefused); resume.resolve(); await new Promise(done => setImmediate(done)); assert.equal(checkouts, 0)
const checkout = gate(), started = gate(), releases: boolean[] = [], controller = new AbortController()
const late = runPollStorageTransaction({ now: Date.now, connect: async () => { started.resolve(); await checkout.promise; return { query: async () => assert.fail("Late backend cannot receive BEGIN"), release: unsafe => { releases.push(unsafe ?? false) } } } },
{ deadlineAt: Date.now() + 2000, signal: controller.signal }, async () => {}, async () => {})
await started.promise; controller.abort(); await assert.rejects(late, PollStorageRefused); checkout.resolve(); await new Promise(done => setImmediate(done)); assert.deepEqual(releases, [true])
})
test("provider errors never escape and invalid/expired scope refuses without any connection", async () => {
const f = fixture()
assert.throws(() => createServerPollStorageForTests({ ...f.binding, scope: { ...f.binding.scope, expiresAt: f.now() } }, f.dependencies), PollStorageRefused)
assert.equal(f.leases.length, 0)
f.dependencies.connect = async () => { throw Error("PRIVATE_PROVIDER database URL") }
await assert.rejects(createServerPollStorageForTests(f.binding, f.dependencies).claim(f.options(), f.anchor), safe)
})