Files
MikrotikManager/backend/src/services/bandwidth-native-dispatch-source.sql-helper.ts
T

60 lines
4.8 KiB
TypeScript

/** Owned PostgreSQL acceptance for the production-source producer, separate
* from transport fixtures. Only the outer runner provisions a disposable DB. */
import assert from "node:assert/strict"
import { randomUUID } from "node:crypto"
import type { Pool } from "pg"
import type { createConfiguredBandwidthControlSource } from "./bandwidth-control-source.js"
import { createBandwidthAdmissionSqlJournal } from "./bandwidth-admission-storage.js"
import { createBandwidthNativeDispatchSqlGate } from "./bandwidth-native-dispatch-source.js"
import { assertOwnedBandwidthSql, fixtureBinding } from "./bandwidth-admission-process.sql-helper.js"
import type { BandwidthScope } from "./bandwidth-admission.js"
import type { ProbeStorageConnection } from "./server-probe-journal-maintenance.js"
export async function acceptOwnedBandwidthNativeDispatchSqlSource(core: ReturnType<typeof createConfiguredBandwidthControlSource>, controlGeneration: string, owner: Pool) {
assertOwnedBandwidthSql()
const scope = (): BandwidthScope => ({ deadlineAt: Date.now() + 10000 })
const binding = fixtureBinding("native-sql-" + randomUUID(), "native-sql-" + randomUUID(), { controlGeneration })
let journalConnection: ProbeStorageConnection | undefined, journalScope: BandwidthScope | undefined
const journal = createBandwidthAdmissionSqlJournal({ now: Date.now,
connect: async current => { journalScope = current; journalConnection = await core.connect(current); return journalConnection },
authorize: async expected => { assert.deepEqual(expected, binding) }, verifyEvidence: async () => {},
eventProof: async event => { assert(journalConnection && journalScope); return core.eventProofOnConnection(event, journalConnection, journalScope) },
})
await journal.reserve(binding, scope()); await journal.arm(binding, scope())
const before = await owner.query("SELECT binding,state FROM mmapp_control.bandwidth_attempts WHERE attempt_id=$1", [binding.attemptId])
const make = () => createBandwidthNativeDispatchSqlGate(core, binding, async fence => {
assert.equal((await fence.sourceIdentity()).controlGeneration, controlGeneration)
})
const ownedScope = { deadlineAt: Date.now() + 5000 }
const gate = make(), lease = await gate.acquire(ownedScope)
try {
await lease.verify(ownedScope)
assert.equal((await owner.query("SELECT pg_catalog.pg_try_advisory_xact_lock(8723116) AS locked")).rows[0].locked, false)
for (const node of [binding.source.canonicalNodeId, binding.destination.canonicalNodeId]) {
assert.equal((await owner.query("SELECT pg_catalog.pg_try_advisory_xact_lock(pg_catalog.hashtextextended($1,764301)) AS locked", ["bandwidth-node:" + node])).rows[0].locked, false)
}
await assert.rejects(owner.query("SELECT attempt_id FROM mmapp_control.bandwidth_attempts WHERE attempt_id=$1 FOR UPDATE NOWAIT", [binding.attemptId]), error => (error as { code?: string }).code === "55P03")
const second = make()
await assert.rejects(second.acquire(scope()))
await lease.verify(ownedScope)
assert.deepEqual((await owner.query("SELECT binding,state FROM mmapp_control.bandwidth_attempts WHERE attempt_id=$1", [binding.attemptId])).rows, before.rows)
} finally { lease.close() }
await assert.rejects(lease.verify(scope())); await assert.rejects(gate.acquire(scope()))
// Destruction retires all locks physically without COMMIT or ledger writes.
const rival=await owner.connect()
try{
await rival.query("BEGIN")
await rival.query("SET LOCAL lock_timeout='2000ms'")
// Destroying the client closes the socket; PostgreSQL observes that close
// asynchronously. Wait on the real lock, rather than assume immediate EOF.
await rival.query("SELECT pg_catalog.pg_advisory_xact_lock(8723116)")
await rival.query("SELECT attempt_id FROM mmapp_control.bandwidth_attempts WHERE attempt_id=$1 FOR UPDATE NOWAIT", [binding.attemptId])
}finally{try{await rival.query("ROLLBACK")}finally{rival.release(true)}}
await journal.quarantine(binding, scope())
const deniedScope = { deadlineAt: Date.now() + 5000 }, quarantined = make(), denied = await quarantined.acquire(deniedScope)
try { await assert.rejects(denied.verify(deniedScope)) } finally { denied.close() }
assert.equal((await owner.query("SELECT state FROM mmapp_control.bandwidth_attempts WHERE attempt_id=$1", [binding.attemptId])).rows[0].state, "unknown_busy")
assert.equal(Number((await owner.query("SELECT count(*) AS n FROM mmapp_control.bandwidth_node_occupancy WHERE attempt_id=$1", [binding.attemptId])).rows[0].n), 2)
return { checks: ["actual authenticated same-lease armed row, two owners and reserve/arm event MACs; registry/canonical/owner locks exclude a rival, physical close releases locks without ledger mutation; unknown occupancy cannot send or clear"], actualNativePosts: 0, peerGuardSynthetic: true }
}