Files
MikrotikManager/backend/src/services/traffic-flow-write-transaction.test.ts
T

98 lines
6.3 KiB
TypeScript

import assert from "node:assert/strict"
import type { PoolClient } from "pg"
import { commitFlowWrite, reconcileFlowWrite, flowWriteQuery, FlowCommitUnknown, FLOW_WRITE_LOCK_KEY } from "./traffic-flow-write-transaction.js"
const id="11111111-1111-4111-8111-111111111111",sourceProof="a".repeat(64),input={id,sourceProof,kind:"ingest" as const}
const calls:string[]=[],released:boolean[]=[]
let stored:{kind:string;source_proof:string;result:unknown}|null=null,staged:typeof stored=null,mode="normal",exclusive=true
let finishOldTransaction:(()=>void)|undefined,oldTransaction:Promise<void>|undefined
let revokeAt:string|undefined,revoked=false
const connect=async()=>({
query:async(sql:string|{text:string;values?:unknown[]},parameters?:unknown[])=>{
const text=typeof sql==="string"?sql:sql.text,params=typeof sql==="string"?parameters:sql.values;calls.push(text)
if(revokeAt&&text.startsWith(revokeAt))revoked=true
if(text.startsWith("SELECT pg_try_advisory_xact_lock"))return {rows:[{acquired:exclusive}]}
if(text.startsWith("SELECT pg_advisory_lock("))await oldTransaction
if(text.startsWith("SELECT pg_advisory_unlock("))return {rows:[{released:true}]}
if(text.startsWith("SELECT kind,source_proof,result"))return {rows:stored?[stored]:[]}
if(text.startsWith("INSERT INTO flow_write_receipts"))staged={kind:String(params?.[1]),source_proof:String(params?.[2]),result:JSON.parse(String(params?.[3]))}
if(text==="ROLLBACK")staged=null
if(text==="COMMIT"){
if(mode==="rollback-command"||mode==="missing-command"||mode==="wrong-command"){
staged=null
return {rows:[],...(mode==="rollback-command"?{command:"ROLLBACK"}:mode==="wrong-command"?{command:"SELECT"}:{})}
}
if(mode==="delayed-lost"){
const pending=staged;staged=null
oldTransaction=new Promise<void>(resolve=>{finishOldTransaction=()=>{stored=pending;resolve()}})
throw Error("lost response while COMMIT still running")
}
stored=staged;staged=null
return {rows:[],command:"COMMIT"}
}
return {rows:[]}
},
release:(destroy=false)=>{released.push(destroy)},
}) as unknown as PoolClient
let checks=0
const result=await commitFlowWrite(input,async()=>{await flowWriteQuery("UPDATE fixture SET n=?",[1]);return {buckets:1}},async()=>{checks++},connect)
assert.deepEqual(result,{buckets:1});assert.equal(checks,6)
assert.ok(calls.indexOf("SELECT pg_advisory_xact_lock_shared($1)")<calls.indexOf("UPDATE fixture SET n=$1"))
assert.ok(calls.indexOf("SELECT pg_advisory_xact_lock_shared($1::bigint)")<calls.indexOf("SELECT pg_advisory_xact_lock_shared($1)"),"Partition admission precedes the flow writer key and table SQL on the same owned client")
assert.ok(calls.findIndex(sql=>sql.startsWith("INSERT INTO flow_write_receipts"))<calls.indexOf("COMMIT"))
assert.equal(FLOW_WRITE_LOCK_KEY,8723105);assert.equal(released.at(-1),false)
let executed=0
assert.deepEqual(await commitFlowWrite(input,async()=>{executed++;return {buckets:99}},async()=>{},connect),{buckets:1});assert.equal(executed,0)
// Lock waits and even a receipt SELECT may outlive the caller's authority.
for(const boundary of ["SELECT pg_advisory_xact_lock(hashtextextended", "SELECT kind,source_proof,result"]){
revokeAt=boundary;revoked=false;calls.length=0
await assert.rejects(commitFlowWrite(input,async()=>{executed++;return {}},async()=>{if(revoked)throw Error("cached receipt authority revoked")},connect),/cached receipt authority revoked/)
assert.equal(executed,0)
assert.ok(!calls.some(sql=>sql.startsWith("INSERT")||sql==="COMMIT"))
}
revokeAt=undefined;revoked=false
stored=null;calls.length=0
await assert.rejects(commitFlowWrite(input,async()=>{throw Error("known body failure")},async()=>{},connect),/known body failure/)
assert.ok(calls.includes("ROLLBACK"));assert.ok(!calls.includes("COMMIT"));assert.equal(stored,null)
exclusive=false;calls.length=0
await assert.rejects(commitFlowWrite({...input,exclusive:true},async()=>{executed++;return {}},async()=>{},connect),/busy/)
assert.equal(executed,0);assert.ok(!calls.some(sql=>sql.startsWith("INSERT")));exclusive=true
calls.length=0
await assert.rejects(commitFlowWrite(input,async()=>({}),async()=>{throw Error("revoked")},connect),/revoked/)
assert.ok(!calls.includes("BEGIN"))
for(const commandMode of ["rollback-command","missing-command","wrong-command"]){
mode=commandMode;stored=null;calls.length=0
await assert.rejects(commitFlowWrite(input,async()=>({buckets:7}),async()=>{},connect),FlowCommitUnknown)
assert.equal(released.at(-1),true);assert.equal(stored,null)
assert.equal(calls.filter(sql=>sql==="COMMIT").length,1)
assert.ok(!calls.includes("ROLLBACK"),"An unconfirmed COMMIT quarantines the backend instead of attempting a second transition")
}
mode="normal"
// Unknown COMMIT must destroy the connection. Even receipt absence remains
// inconclusive while the previous backend transaction still owns its batch lock.
mode="delayed-lost";calls.length=0
await assert.rejects(commitFlowWrite(input,async()=>({buckets:7}),async()=>{},connect),FlowCommitUnknown)
assert.equal(released.at(-1),true);assert.equal(stored,null)
let reconciled=false
const waiting=reconcileFlowWrite(input,async()=>{},connect).then(value=>{reconciled=true;return value})
await new Promise<void>(resolve=>setImmediate(resolve));assert.equal(reconciled,false)
finishOldTransaction!()
assert.deepEqual(await waiting,{committed:true,result:{buckets:7}})
assert.ok(calls.some(sql=>sql.startsWith("SELECT pg_advisory_lock(hashtextextended")))
mode="normal";stored=null;oldTransaction=undefined
assert.deepEqual(await reconcileFlowWrite(input,async()=>{},connect),{committed:false,result:null})
// An asynchronous child must not use its former transaction after commit.
let wake:()=>void=()=>{},detached:Promise<unknown>|undefined
await commitFlowWrite({...input,id:"22222222-2222-4222-8222-222222222222"},async()=>{
const later=new Promise<void>(resolve=>{wake=resolve})
detached=later.then(()=>flowWriteQuery("UPDATE forbidden_after_commit SET n=1"))
return {buckets:0}
},async()=>{},connect)
wake();await assert.rejects(detached!,/context is closed/)
assert.ok(!calls.includes("UPDATE forbidden_after_commit SET n=1"))
console.log("traffic-flow-write-transaction.test.ts: fake-client lease ordering, receipts, rollback, revoke, connection quarantine, in-flight COMMIT reconciliation barrier and closed-context fencing verified; no SQL/network executed")