Files
MikrotikManager/backend/src/services/server-partition-maintenance-lease.test.ts
T

37 lines
10 KiB
TypeScript

import assert from "node:assert/strict"
import { PARTITION_SPECS } from "../db/partitions.js"
import { createServerPartitionMaintenanceLease, SERVER_PARTITION_WRITER_DDL, SERVER_PARTITION_WRITER_LOCK, ServerPartitionLeaseError, type ServerPartitionLeaseOptions, type ServerPartitionQuery } from "./server-partition-maintenance-lease.js"
import type { ServerPollSqlConnection } from "./server-poll-production.js"
const options=():ServerPartitionLeaseOptions=>({deadlineAt:11000,serverIds:[1,2]})
const inventory=()=>PARTITION_SPECS.map((p,i)=>({parent:p.parent,oid:String(i+1),relname:p.parent,nspname:"public",trigger_type:31,trigger_enabled:"A",trigger_name:"server_partition_writer_guard",trigger_args:0,unconditional:true,constraint_oid:"0",function_schema:"public",function_name:"server_partition_writer_guard",function_language:"plpgsql",security_definer:false,function_source:"BEGIN PERFORM pg_advisory_xact_lock_shared(8723110::bigint); IF TG_OP='DELETE' THEN RETURN OLD; END IF; RETURN NEW; END;"}))
function fixture(){
let authority=true,time=1000,fail:string|undefined,unlock=true,count=0,rows:Record<string,unknown>[]=inventory()
const log:{connection:number;sql:string;values:unknown[];timeout:number}[]=[],releases:{connection:number;destroy:boolean}[]=[],authorizations:number[][]=[]
const factory=createServerPartitionMaintenanceLease({now:()=>time,assertAuthority:async opts=>{authorizations.push([...opts.serverIds]);if(!authority)throw Error("revoked")},connect:async()=>{const connection=++count;const client:ServerPollSqlConnection={release:destroy=>{releases.push({connection,destroy:!!destroy})},query:async(sql,values,opts)=>{log.push({connection,sql,values,timeout:opts.timeoutMs});if(fail&&sql.includes(fail)){fail=undefined;throw Error("SQL ACK lost")};if(sql.includes("partition-lease:inventory"))return {rows};if(sql.includes("partition-lease:unlock"))return {rows:[{unlocked:unlock}]};return {rows:[{value:1}]}}};return client}})
return {factory,log,releases,authorizations,revoke:()=>{authority=false},clock:(v:number)=>{time=v},fail:(v:string)=>{fail=v},badUnlock:()=>{unlock=false},inventory:(v:Record<string,unknown>[])=>{rows=v},count:()=>count}
}
let checks=0
async function test(name:string,work:()=>Promise<void>|void){await work();checks++;console.log("ok",name)}
await test("schema proposes always-enabled row trigger for every parent",()=>{assert.equal(PARTITION_SPECS.length,12);assert.equal((SERVER_PARTITION_WRITER_DDL.match(/CREATE TRIGGER/g)??[]).length,12);assert.equal((SERVER_PARTITION_WRITER_DDL.match(/ENABLE ALWAYS TRIGGER/g)??[]).length,12);assert.match(SERVER_PARTITION_WRITER_DDL,/pg_advisory_xact_lock_shared\(8723110::bigint\)/);assert.equal(SERVER_PARTITION_WRITER_LOCK,8723110)})
await test("session lock, mutations and unlock use exactly one SQL backend",async()=>{const f=fixture();await f.factory.withLease(async()=>{await f.factory.transaction(false,async()=>{},options(),async query=>{await query("INSERT INTO server_snapshots VALUES (1)")});await f.factory.transaction(true,async()=>{},options(),async query=>{await query("SELECT 1")})},options());assert.equal(f.count(),1);assert.equal(new Set(f.log.map(c=>c.connection)).size,1);assert(f.log[0].sql.includes("partition-lease:acquire"));assert(f.log.at(-1)?.sql.includes("partition-lease:unlock"));assert.deepEqual(f.releases,[{connection:1,destroy:false}]);assert(f.authorizations.length>f.log.length)})
await test("preparation uses owned read-only transaction without session lock",async()=>{const f=fixture();await f.factory.transaction(true,async()=>{},options(),async query=>{await query("SELECT 1")});assert.equal(f.log[0].sql,"BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY");assert(!f.log.some(r=>r.sql.includes("advisory_lock")));assert.deepEqual(f.releases,[{connection:1,destroy:false}])})
await test("nested read uses a savepoint and no second pool backend",async()=>{const f=fixture();await f.factory.withLease(()=>f.factory.transaction(false,async()=>{},options(),async query=>{await query("SELECT 'before'");await f.factory.transaction(true,async()=>{},options(),async read=>{await read("SELECT 'nested'")});await query("INSERT INTO server_snapshots VALUES (1)")}),options());assert.equal(f.count(),1);assert.equal(f.log.filter(r=>r.sql==="BEGIN").length,1);assert(f.log.some(r=>r.sql==="SAVEPOINT poll_nested_1"));assert(f.log.some(r=>r.sql==="RELEASE SAVEPOINT poll_nested_1"));assert.equal(f.log.filter(r=>r.sql==="COMMIT").length,1)})
await test("nested write is rejected before dispatch",async()=>{const f=fixture();await assert.rejects(f.factory.withLease(()=>f.factory.transaction(false,async()=>{},options(),async()=>f.factory.transaction(false,async()=>{},options(),async()=>{})),options()),ServerPartitionLeaseError);assert(!f.log.some(r=>r.sql.startsWith("SAVEPOINT")));assert.equal(f.releases.at(-1)?.destroy,true)})
await test("outer transactions are FIFO and never overlap",async()=>{const f=fixture(),seen:string[]=[];let release!:()=>void,started!:()=>void;const began=new Promise<void>(resolve=>{started=resolve}),gate=new Promise<void>(resolve=>{release=resolve});await f.factory.withLease(async()=>{const first=f.factory.transaction(false,async()=>{},options(),async()=>{seen.push("first-enter");started();await gate;seen.push("first-exit")});await began;const second=f.factory.transaction(true,async()=>{},options(),async()=>{seen.push("second-enter")});assert.deepEqual(seen,["first-enter"]);release();await Promise.all([first,second])},options());assert.deepEqual(seen,["first-enter","first-exit","second-enter"])})
await test("closed captured query cannot dispatch after commit",async()=>{const f=fixture();let captured:ServerPartitionQuery|undefined;await f.factory.withLease(async()=>{await f.factory.transaction(false,async()=>{},options(),async query=>{captured=query});const count=f.log.length;await assert.rejects(captured!("SELECT 1"),ServerPartitionLeaseError);assert.equal(f.log.length,count)},options())})
await test("detached work inherits a closed lease and cannot reacquire",async()=>{const f=fixture();let invoke!:()=>void,detached!:Promise<void>;const gate=new Promise<void>(resolve=>{invoke=resolve});await f.factory.withLease(async()=>{detached=gate.then(()=>f.factory.transaction(true,async()=>{},options(),async()=>{}))},options());const count=f.log.length;invoke();await assert.rejects(detached,ServerPartitionLeaseError);assert.equal(f.log.length,count)})
await test("nested lease rejected",async()=>{const f=fixture();await assert.rejects(f.factory.withLease(()=>f.factory.withLease(async()=>{},options()),options()),ServerPartitionLeaseError);assert.equal(f.count(),1)})
await test("missing parent trigger refuses maintenance",async()=>{const f=fixture();f.inventory(inventory().slice(1));let called=false;await assert.rejects(f.factory.withLease(async()=>{called=true},options()),ServerPartitionLeaseError);assert.equal(called,false);assert.equal(f.releases[0].destroy,true)})
await test("unprotected leaf refuses maintenance",async()=>{const f=fixture();f.inventory([...inventory(),{...inventory()[0],oid:"99",relname:"flow_buckets_d_20260101",trigger_enabled:"D"}]);await assert.rejects(f.factory.withLease(async()=>{},options()),ServerPartitionLeaseError)})
await test("wrong lock trigger body refuses maintenance",async()=>{const f=fixture();const rows=inventory();rows[0].function_source="BEGIN RETURN NEW; END;";f.inventory(rows);await assert.rejects(f.factory.withLease(async()=>{},options()),ServerPartitionLeaseError)})
await test("lost BEGIN ACK destroys holder with no rollback",async()=>{const f=fixture();f.fail("BEGIN");await assert.rejects(f.factory.withLease(()=>f.factory.transaction(false,async()=>{},options(),async()=>{}),options()),(e:unknown)=>e instanceof ServerPartitionLeaseError&&e.outcomeUnknown);assert(!f.log.some(r=>r.sql.includes("ROLLBACK")||r.sql.includes("partition-lease:unlock")));assert.equal(f.releases[0].destroy,true)})
await test("lost COMMIT ACK destroys holder with no rollback or retry",async()=>{const f=fixture();f.fail("COMMIT");await assert.rejects(f.factory.withLease(()=>f.factory.transaction(false,async()=>{},options(),async query=>{await query("INSERT INTO server_snapshots VALUES (1)")}),options()),(e:unknown)=>e instanceof ServerPartitionLeaseError&&e.outcomeUnknown);assert.equal(f.log.filter(r=>r.sql==="COMMIT").length,1);assert(!f.log.some(r=>r.sql.includes("ROLLBACK")||r.sql.includes("partition-lease:unlock")));assert.equal(f.releases[0].destroy,true)})
await test("unknown unlock destroys instead of pooling session owner",async()=>{const f=fixture();f.badUnlock();await assert.rejects(f.factory.withLease(async()=>{},options()),(e:unknown)=>e instanceof ServerPartitionLeaseError&&e.outcomeUnknown);assert.deepEqual(f.releases,[{connection:1,destroy:true}])})
await test("authority revocation between SQL boundaries blocks next dispatch",async()=>{const f=fixture();await assert.rejects(f.factory.withLease(()=>f.factory.transaction(false,async()=>{},options(),async query=>{f.revoke();await query("INSERT INTO server_snapshots VALUES (1)")}),options()),ServerPartitionLeaseError);assert(!f.log.some(r=>r.sql.startsWith("INSERT")));assert.equal(f.releases[0].destroy,true)})
await test("abort destroys SQL holder and rejects later work",async()=>{const f=fixture(),controller=new AbortController(),opts={...options(),signal:controller.signal};await assert.rejects(f.factory.withLease(()=>f.factory.transaction(false,async()=>{},opts,async query=>{controller.abort();await query("SELECT 1")}),opts),ServerPartitionLeaseError);assert.equal(f.releases[0].destroy,true)})
await test("expired deadline prevents next SQL",async()=>{const f=fixture();await assert.rejects(f.factory.withLease(()=>f.factory.transaction(false,async()=>{},options(),async query=>{f.clock(11000);await query("SELECT 1")}),options()),ServerPartitionLeaseError);assert(!f.log.some(r=>r.sql==="SELECT 1"))})
await test("deadline above180 seconds refused before connect",async()=>{const f=fixture();await assert.rejects(f.factory.withLease(async()=>{},{...options(),deadlineAt:182000}),ServerPartitionLeaseError);assert.equal(f.count(),0)})
await test("work cannot override factory transaction boundary",async()=>{const f=fixture();await assert.rejects(f.factory.withLease(()=>f.factory.transaction(false,async()=>{},options(),async query=>{await query("COMMIT")}),options()),ServerPartitionLeaseError);assert(!f.log.some(r=>r.sql==="COMMIT"))})
console.log(`server-partition-maintenance-lease: ${checks} inert SQL scenarios passed`)