85 lines
5.7 KiB
TypeScript
85 lines
5.7 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { createServer, request } from "node:http"
|
|
import { pool } from "../../db/index.js"
|
|
import { configurationRows, resourceById, type RosSnapshot, type RosStep } from "./resources.js"
|
|
import { fingerprint } from "./security.js"
|
|
import { verifyRosStepSnapshots } from "./ros-step-verification.js"
|
|
|
|
// Real loopback framing/response-loss test of the pure projected verifier. This
|
|
// deliberately does not invoke admission, SQL checkpoints or real RouterOS.
|
|
const originalQuery = pool.query, originalConnect = pool.connect
|
|
let sql = 0
|
|
const forbidden = () => { sql++; throw Error("HTTP model must not access PostgreSQL") }
|
|
pool.query = forbidden as typeof pool.query; pool.connect = forbidden as typeof pool.connect
|
|
type Row = Record<string, string>
|
|
let rows: Row[] = [], mode = "normal", writes = 0, next = 0
|
|
const serverId = 198
|
|
const base = (resource: string): Row[] => ["a", "b", "c"].map(id => ({ ".id": `*${id}`, ...(resource === "ip_filter" ? { chain: "fixture", action: "accept" } : { action: "lookup", table: "main" }), comment: id, disabled: "true" }))
|
|
const router = createServer(async (req, res) => {
|
|
res.setHeader("content-type", "application/json")
|
|
if (req.method === "GET") { res.end(JSON.stringify(rows)); return }
|
|
let body = ""; for await (const chunk of req) body += chunk
|
|
const fields = body ? JSON.parse(body) as Row : {}, id = req.method === "PUT" ? `*new${++next}` : decodeURIComponent((req.url ?? "").split("/").at(-1)!)
|
|
writes++
|
|
if (mode !== "ignored") {
|
|
if (req.method === "PUT") rows.push({ ".id": id, ...fields })
|
|
if (req.method === "PATCH") Object.assign(rows.find(row => row[".id"] === id)!, fields)
|
|
if (req.method === "DELETE") rows = rows.filter(row => row[".id"] !== id)
|
|
}
|
|
if (mode === "two-new") rows.push({ ".id": `*extra${next}`, ...fields })
|
|
if (mode === "collateral") rows.find(row => row[".id"] === "*b")!.comment = "external"
|
|
if (mode === "unsupplied") rows.find(row => row[".id"] === id)!.disabled = "false"
|
|
if (mode === "removed-neighbor") rows = rows.filter(row => row[".id"] !== "*b")
|
|
if (mode === "duplicate") rows.push(structuredClone(rows[0]))
|
|
if (mode === "missing") delete (rows[0] as Record<string, string | undefined>)[".id"]
|
|
if (mode === "reorder") rows.reverse()
|
|
if (mode === "lost") { req.socket.destroy(); return }
|
|
res.end(JSON.stringify(req.method === "PUT" ? { ".id": mode === "existing" ? "*a" : id } : {}))
|
|
})
|
|
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
|
|
const port = (router.address() as { port: number }).port
|
|
const http = (method: string, path: string, body?: unknown) => new Promise<unknown>((resolve, reject) => {
|
|
const payload = body === undefined ? undefined : JSON.stringify(body)
|
|
const req = request({ hostname: "127.0.0.1", port, method, path, agent: false, ...(payload === undefined ? {} : { headers: { "content-type": "application/json", "content-length": Buffer.byteLength(payload) } }) }, res => {
|
|
let text = ""; res.on("data", chunk => { text += chunk }); res.once("error", reject)
|
|
res.once("end", () => { try { resolve(JSON.parse(text)) } catch (error) { reject(error) } })
|
|
})
|
|
req.once("error", reject); req.setTimeout(3000, () => req.destroy(Error("Loopback timeout")))
|
|
req.end(payload)
|
|
})
|
|
const snapshot = async (resource: string): Promise<RosSnapshot> => {
|
|
const projected = configurationRows(resourceById(resource), await http("GET", resourceById(resource).path))
|
|
return { serverId, resource, rows: projected, fingerprint: fingerprint(projected) }
|
|
}
|
|
try {
|
|
let cases = 0
|
|
for (const resource of ["ip_filter", "routing_rule"]) {
|
|
for (const action of ["create", "update", "delete"] as const) {
|
|
const faults = ["normal", "ignored", "lost", "collateral", "removed-neighbor", "duplicate", "missing", "reorder", ...(action === "create" ? ["existing", "two-new"] : action === "update" ? ["unsupplied"] : [])]
|
|
for (const fault of faults) {
|
|
rows = base(resource); mode = fault
|
|
const fields: Record<string, string> = action === "create" ? { ...(resource === "ip_filter" ? { chain: "fixture", action: "accept" } : { action: "lookup", table: "main" }), comment: "new", disabled: "true" } : action === "update" ? { comment: "changed" } : {}
|
|
const step: RosStep = { serverId, resource, action, fields, ...(action === "create" ? {} : { id: "*a" }) }
|
|
const before = await snapshot(resource), count = writes
|
|
let acknowledged = false, result: unknown
|
|
try { result = await http(action === "create" ? "PUT" : action === "update" ? "PATCH" : "DELETE", `${resourceById(resource).path}${action === "create" ? "" : "/*a"}`, fields); acknowledged = true }
|
|
catch (error) { assert.equal(fault, "lost", `${resource}/${action}/${fault}: ${error instanceof Error ? error.message : "transport error"}`) }
|
|
const after = await snapshot(resource)
|
|
// Snapshot equality cannot manufacture an acknowledgement after loss.
|
|
const verified = acknowledged && verifyRosStepSnapshots(step, result, before, after)
|
|
assert.equal(verified, fault === "normal", `${resource}/${action}/${fault}`)
|
|
assert.equal(writes, count + 1)
|
|
// Diagnostic reads and repeated verification never dispatch a retry.
|
|
verifyRosStepSnapshots(step, result, before, await snapshot(resource))
|
|
assert.equal(writes, count + 1); cases++
|
|
}
|
|
}
|
|
}
|
|
assert.equal(sql, 0)
|
|
console.log(`Native conservation HTTP: ${cases} C/U/D cases, assigned IDs, exact membership/fields/order, lost ACK remains unconfirmed, no diagnostic replay; zero PostgreSQL access`)
|
|
} finally {
|
|
await new Promise<void>((resolve, reject) => router.close(error => error ? reject(error) : resolve()))
|
|
pool.query = originalQuery; pool.connect = originalConnect
|
|
await pool.end()
|
|
}
|