import assert from "node:assert/strict" import { test } from "node:test" import { invalidateSystemDatabaseCaches } from "./system-database-cache.js" import { applyRingSnapshot, snapshotRings } from "./traffic-flow-engine.js" import { rememberServerIfaces, ifaceCacheHas } from "./traffic-flow-ifindex.js" import { DatabaseBackgroundWork } from "./database-background-work.js" import { executeDatabaseOperation } from "./system-database-operation.js" import { executeSystemDatabaseRestore } from "./system-database-restore-execution.js" import { disableRipePersistForTests, seedRipeCacheForTests, lookupRipeCached, pauseRipeBackgroundWork, resumeRipeBackgroundWork, enqueueRipeMisses, ripeFetchCountForTests, } from "./traffic-flow-ripe.js" test("restore discards old RIPE, interface and live data without reopening RIPE admission", async () => { disableRipePersistForTests() seedRipeCacheForTests({ prefix: "8.8.8.0/24", asn: 15169, country: "US", lat: null, lng: null, holder: "old database", ok: true, fetchedAt: Date.now() }) rememberServerIfaces(1, [{ ".id": "*1", name: "ether1" }]) applyRingSnapshot([{ key: "old database", inBps: [1_000_000], outBps: [1_000_000] }]) assert.equal(lookupRipeCached("8.8.8.8")?.holder, "old database") assert.equal(ifaceCacheHas(1), true) assert.equal(snapshotRings().length, 1) await pauseRipeBackgroundWork() try { const count = ripeFetchCountForTests() invalidateSystemDatabaseCaches() assert.equal(lookupRipeCached("8.8.8.8"), null) assert.equal(ifaceCacheHas(1), false) assert.equal(snapshotRings().length, 0) enqueueRipeMisses(["8.8.8.8"]) assert.equal(ripeFetchCountForTests(), count) } finally { resumeRipeBackgroundWork() } }) test("background drain precedes restore and consumers restart with invalidated caches", async () => { const work = new DatabaseBackgroundWork(), calls: string[] = [] let release!: () => void work.track(new Promise(r => { release = r })) rememberServerIfaces(1, [{ ".id": "*1", name: "old-interface" }]) const operation = executeDatabaseOperation(() => executeSystemDatabaseRestore(Buffer.from("PGDMPfixture"), "fixture", { allocate: async () => "fixture.dump", write: async () => {}, remove: async () => {}, run: async () => { calls.push("restore") }, invalidate: () => { calls.push("invalidate"); invalidateSystemDatabaseCaches() }, }), { stopListener: () => { calls.push("stop listener") }, stopScheduler: async () => { await work.drain(); calls.push("drained") }, startListener: () => { assert.equal(ifaceCacheHas(1), false); calls.push("restart listener") }, startScheduler: () => { calls.push("restart scheduler") }, }) await Promise.resolve(); await Promise.resolve() assert.equal(calls.includes("restore"), false) assert.equal(ifaceCacheHas(1), true) release(); await operation assert.deepEqual(calls, ["stop listener", "drained", "restore", "invalidate", "restart listener", "restart scheduler"]) })