Files
MikrotikManager/backend/src/services/bandwidth-speed-run-identity.test.ts
T

85 lines
7.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** Pure identity + actual journal plumbing with a synthetic unique-index driver.
* No PostgreSQL is used here; real cross-process/restore acceptance is separate. */
import assert from "node:assert/strict"
import { test } from "node:test"
import { promisify } from "node:util"
import { execFile } from "node:child_process"
import { readFile } from "node:fs/promises"
import { z } from "zod"
import { createBandwidthSpeedRunIdentity, assertBandwidthSpeedRunHistoryAbsent, BandwidthSpeedRunIdUnavailable } from "./bandwidth-speed-run-identity.js"
import { SpeedRunPersistenceUnknown } from "./speed-run-persistence.js"
import { createBandwidthAdmissionSqlJournal } from "./bandwidth-admission-storage.js"
import type { BandwidthBinding } from "./bandwidth-admission.js"
import type { ProbeStorageConnection } from "./server-probe-journal-maintenance.js"
test("one normalized run ID has global stable custom UUIDv8/fullhash identity; actor/caller/generation cannot salt it", () => {
const first = createBandwidthSpeedRunIdentity(" owned-speed-α/原 "), second = createBandwidthSpeedRunIdentity("owned-speed-α/原")
assert.deepEqual(first, second); assert(Object.isFrozen(first)); assert.equal(first.runId, "owned-speed-α/原")
assert.match(first.attemptId, /^[a-f0-9]{8}-[a-f0-9]{4}-8[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/)
assert(z.string().uuid().safeParse(first.attemptId).success); assert.match(first.operationId, /^speed-run-v1:[a-f0-9]{64}$/)
assert.notEqual(createBandwidthSpeedRunIdentity("other").attemptId, first.attemptId)
assert.equal(createBandwidthSpeedRunIdentity("x".repeat(10000)).operationId.length, first.operationId.length)
const fresh = Array.from({ length: 30 }, () => createBandwidthSpeedRunIdentity())
assert.equal(new Set(fresh.map(value => value.runId)).size, 30)
for (const value of fresh) assert.deepEqual(createBandwidthSpeedRunIdentity(value.runId), value)
})
test("independent Node process derives identical identity without keys, caller state or application-history access", async () => {
const url = new URL("./bandwidth-speed-run-identity.ts", import.meta.url).href
const code = `import {createBandwidthSpeedRunIdentity} from ${JSON.stringify(url)}; process.stdout.write(JSON.stringify(createBandwidthSpeedRunIdentity("owned-cross-process-run")))`
const child = await promisify(execFile)(process.execPath, ["--import", "tsx", "--input-type=module", "-e", code])
assert.deepEqual(JSON.parse(child.stdout), createBandwidthSpeedRunIdentity("owned-cross-process-run"))
})
test("legacy lookup is fail closed and suppresses second failure publication, without pretending to reserve a run", () => {
assert.doesNotThrow(() => assertBandwidthSpeedRunHistoryAbsent({ command: "SELECT", rowCount: 0, rows: [] }, "owned-run"))
for (const result of [null, {}, { command: "UPDATE", rowCount: 0, rows: [] }, { command: "SELECT", rowCount: null, rows: [] },
{ command: "SELECT", rowCount: 1, rows: [{ id: "owned-run" }] }, { command: "SELECT", rowCount: 0, rows: [{}] }]) {
assert.throws(() => assertBandwidthSpeedRunHistoryAbsent(result, "owned-run"), error => {
assert(error instanceof BandwidthSpeedRunIdUnavailable); assert(error instanceof SpeedRunPersistenceUnknown)
assert.equal(error.automaticReplay, false); return true
})
}
assert.throws(() => createBandwidthSpeedRunIdentity("bad\0run")); assert.throws(() => createBandwidthSpeedRunIdentity({ toString() { assert.fail("coercion executed") } } as never))
})
test("existing plain INSERT journal refuses another caller/new host for the same global attempt before arm/native; history erasure cannot clear this driver ledger", async () => {
// Explicit synthetic database uniqueness boundary: this exercises the ACTUAL
// SQL journal reserve/error path. It is not a real durability/restore proof.
let committedAttempt: string | undefined
const statements: string[] = []
const connect = async (): Promise<ProbeStorageConnection> => {
let inserted: string | undefined
return { release() {}, async query(text, values = []) {
statements.push(text)
if (text === "BEGIN" || text === "ROLLBACK") return { command: text, rows: [] }
if (text === "COMMIT") { if (inserted) committedAttempt = inserted; return { command: "COMMIT", rows: [] } }
if (text.includes("pg_try_advisory_xact_lock")) return { command: "SELECT", rows: [{ locked: true }] }
if (text.includes("pg_catalog.set_config")) return { command: "SELECT", rows: [{}] }
if (text.startsWith("INSERT INTO mmapp_control.bandwidth_attempts(")) {
assert(!/ON CONFLICT/i.test(text)); if (committedAttempt === values[0]) throw Object.assign(Error("synthetic unique violation"), { code: "23505" })
inserted = String(values[0]); return { command: "INSERT", rows: [{ attempt_id: values[0] }] }
}
if (text.startsWith("INSERT INTO mmapp_control.bandwidth_node_occupancy")) return { command: "INSERT", rows: [{ node_id: values[0] }, { node_id: values[1] }] }
if (text.startsWith("INSERT INTO mmapp_control.bandwidth_attempt_events")) return { command: "INSERT", rows: [{ ack_id: values[0] }] }
assert.fail("Unexpected journal statement")
} }
}
const identity = createBandwidthSpeedRunIdentity("owned-caller-independent-run"), now = Date.now()
const binding = (callerKind: "rest-speed" | "scheduled-speed", suffix: string): BandwidthBinding => ({ attemptId: identity.attemptId,
operationId: identity.operationId, callerKind, source: { canonicalNodeId: "source-" + suffix, endpointProof: "a".repeat(64) },
destination: { canonicalNodeId: "dest-" + suffix, endpointProof: "b".repeat(64) }, authorityProof: "c".repeat(64), authorityGeneration: "different-actor-" + suffix,
controlGeneration: "owned-control", expiresAt: now + 60000, durationSec: 3, requestProof: "d".repeat(64), commandProof: "e".repeat(64), bindingProof: "f".repeat(64) })
const journal = () => createBandwidthAdmissionSqlJournal({ now: Date.now, connect, authorize: async () => {}, verifyEvidence: async () => {}, eventProof: async () => "a".repeat(64) })
const first = await journal().reserve(binding("rest-speed", "first"), { deadlineAt: now + 5000 })
assert.equal(first.outcome, "new"); assert.equal(committedAttempt, identity.attemptId)
// Simulate application history absence/restore independently from control.
assertBandwidthSpeedRunHistoryAbsent({ command: "SELECT", rowCount: 0, rows: [] }, identity.runId)
await assert.rejects(journal().reserve(binding("scheduled-speed", "foreign"), { deadlineAt: now + 5000 }))
assert.equal(statements.filter(sql => sql.startsWith("INSERT INTO mmapp_control.bandwidth_attempts(")).length, 2)
assert.equal(statements.filter(sql => sql.startsWith("INSERT INTO mmapp_control.bandwidth_attempt_events")).length, 1)
assert.equal(statements.filter(sql => sql.startsWith("INSERT INTO mmapp_control.bandwidth_node_occupancy")).length, 1)
})
test("required durable global key and permanent-attempt guards are existing control DDL, not an application-history uniqueness claim", async () => {
const source = await readFile(new URL("./bandwidth-admission-schema.ts", import.meta.url), "utf8")
assert(source.includes("attempt_id uuid PRIMARY KEY")); assert(source.includes("UNIQUE (caller_kind, operation_id)"))
assert(source.includes("bandwidth attempts cannot be deleted")); assert(source.includes("bandwidth_attempts_no_truncate"))
})