Docker images / prepare-release (push) Successful in 9s
Docker images / updater-image (push) Successful in 3m22s
Docker images / frontend-image (push) Successful in 3m26s
Docker images / netflow-agent-image (push) Successful in 3m21s
Docker images / backend-test (push) Successful in 25m38s
Docker images / backend-image (push) Successful in 20m27s
Docker images / notify-webhook (push) Successful in 1s
Docker images / publish-release (push) Successful in 9s
168 lines
9.9 KiB
TypeScript
168 lines
9.9 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { AsyncResource } from "node:async_hooks"
|
|
import { mock } from "node:test"
|
|
import { setTimeout as delay } from "node:timers/promises"
|
|
|
|
import { assertOwnedBandwidthSql } from "./bandwidth-admission-process.sql-helper.js"
|
|
|
|
export async function checkCatalogReadContention(serverId: number) {
|
|
assertOwnedBandwidthSql()
|
|
const { db, pool } = await import("../db/index.js")
|
|
const { default: Fastify } = await import("fastify")
|
|
const { installDatabaseRequestGate } = await import("../plugins/database-request-gate.js")
|
|
const app = Fastify()
|
|
installDatabaseRequestGate(app)
|
|
let releaseHttp!: () => void
|
|
const httpGate = new Promise<void>(resolve => { releaseHttp = resolve })
|
|
let activeReads = 0
|
|
app.get("/api/test/catalog", async () => { activeReads++; await httpGate; return { ok: true } })
|
|
app.put("/api/test/catalog", async () => ({ ok: true }))
|
|
await app.ready()
|
|
const requests = Promise.all(Array.from({ length: 12 }, () => app.inject({ method: "GET", url: "/api/test/catalog" })))
|
|
try {
|
|
const until = Date.now() + 5000
|
|
while (activeReads < 8) { assert(Date.now() < until, "REST read pool did not fill"); await delay(10) }
|
|
assert.equal((await app.inject({ method: "PUT", url: "/api/test/catalog" })).statusCode, 200)
|
|
assert.equal(activeReads, 8, "Write admitted while every ordinary REST lease was held by a GET")
|
|
} finally {
|
|
releaseHttp()
|
|
try { assert((await requests).every(response => response.statusCode === 200)) }
|
|
finally { await app.close() }
|
|
}
|
|
const { ensurePartitionFor } = await import("../db/partitions.js")
|
|
await ensurePartitionFor(pool, "internet_path_snapshots", "week", new Date())
|
|
const { getSettings } = await import("./uptime-collector.js")
|
|
const { getTrafficSettings } = await import("./traffic-collector.js")
|
|
const { getInternetPathSettings } = await import("./internet-path-collector.js")
|
|
const { getServersApiPingSettings } = await import("./servers-rest-ping-collector.js")
|
|
for (const [table, get] of [["uptime_settings", getSettings], ["traffic_settings", getTrafficSettings],
|
|
["internet_path_settings", getInternetPathSettings], ["servers_api_ping_settings", getServersApiPingSettings]] as const) {
|
|
// Two readers see the missing row before either INSERT can commit.
|
|
await pool.query(`DELETE FROM ${table} WHERE id=1`)
|
|
const gate = await pool.connect()
|
|
let results
|
|
try {
|
|
await gate.query("BEGIN")
|
|
await gate.query(`LOCK TABLE ${table} IN SHARE MODE`)
|
|
results = Promise.allSettled([get(), get()])
|
|
const until = Date.now() + 5000
|
|
while ((await gate.query("SELECT count(*)::int AS n FROM pg_locks WHERE relation=$1::regclass AND NOT granted", [table])).rows[0].n < 2) {
|
|
assert(Date.now() < until, "Concurrent initializers did not reach INSERT: " + table)
|
|
await delay(10)
|
|
}
|
|
} finally { await gate.query("ROLLBACK"); gate.release() }
|
|
const [first, second] = await results
|
|
assert(first.status === "fulfilled" && second.status === "fulfilled", table)
|
|
assert.deepEqual(first.value, second.value)
|
|
}
|
|
const { readFilterRulesCatalog } = await import("../routes/filters.js")
|
|
const { readRecursiveRoutesForServer, readRecursiveCatalogForServer, applyRecursiveToServer } = await import("../routes/recursive-routes.js")
|
|
const { servers } = await import("../db/schema.js")
|
|
const { eq } = await import("drizzle-orm")
|
|
const { runSchedulerJobNow } = await import("./scheduler.js")
|
|
const { MikrotikClient } = await import("./mikrotik.js")
|
|
const { coalesceCatalogReads, readCatalogWithObservedCache } = await import("./routing-catalog-observation.js")
|
|
const { ConfigurationBusyError, withApplicationCollectorLock, withApplicationMutationLock } = await import("./config-mutation-lock.js")
|
|
const [fixture] = await db.select().from(servers).where(eq(servers.id, serverId))
|
|
const server = { ...fixture, enabled: true }
|
|
let attempts = 0
|
|
const poll = coalesceCatalogReads(async () => {
|
|
attempts++
|
|
if (attempts === 1) throw new Error("RouterOS unavailable")
|
|
return attempts
|
|
})
|
|
const first = poll(server)
|
|
assert.equal(first, poll(server))
|
|
assert.equal(await poll({ ...server, routingEndpointEpoch: "new-source" }), 2)
|
|
await assert.rejects(first, /RouterOS unavailable/)
|
|
assert.equal(await poll(server), 3, "Errors must not be cached")
|
|
assert.equal(await poll(server), 4, "A later refresh must start a new poll")
|
|
const independent = new AsyncResource("other-catalog-request")
|
|
const route = { id: "", dstAddress: "192.0.2.1/32", gateway: "192.0.2.2", distance: 1, scope: 30, targetScope: 10,
|
|
routingTable: "main", checkGateway: "ping", disabled: false, country: "", comment: "test" }
|
|
let native: Record<string, string>[] = [], blocked = 0, hold = false
|
|
let resume!: () => void
|
|
const gate = new Promise<void>(resolve => { resume = resolve })
|
|
const readRouter = async (path: string) => {
|
|
if (path === "/interface/gre") return []
|
|
assert(["/routing/filter/rule", "/ip/route/print"].includes(path))
|
|
const snapshot = path === "/ip/route/print" ? [...native] : []
|
|
if (hold) { blocked++; await gate }
|
|
return snapshot
|
|
}
|
|
const get = mock.method(MikrotikClient.prototype, "get", readRouter)
|
|
const post = mock.method(MikrotikClient.prototype, "post", readRouter)
|
|
const put = mock.method(MikrotikClient.prototype, "put", async (path: string, body: Record<string, string>) => {
|
|
assert.equal(path, "/ip/route")
|
|
native = [{ ...body, ".id": "*A", static: "true" }]
|
|
return { ".id": "*A" }
|
|
})
|
|
const load = () => Promise.all([readFilterRulesCatalog([server], { source: "live", persistObserved: true }),
|
|
readRecursiveCatalogForServer(server), readRecursiveRoutesForServer(server)])
|
|
try {
|
|
const jobs = ["uptime_resources", "uptime_ping"]
|
|
const startedAt = new Date().toISOString()
|
|
const pending = await withApplicationMutationLock(async () => {
|
|
const runs = independent.runInAsyncScope(() => Promise.all(jobs.map(runSchedulerJobNow)))
|
|
const state = await Promise.race([runs.then(() => "finished", () => "failed"), delay(600, "waiting")])
|
|
assert.equal(state, "waiting", "Scheduler must wait for a transient exclusive lock")
|
|
await independent.runInAsyncScope(() => assert.rejects(
|
|
withApplicationCollectorLock(async () => assert.fail("Collector entered during a write"), { waitMs: 50 }),
|
|
ConfigurationBusyError,
|
|
))
|
|
return { runs }
|
|
})
|
|
assert.deepEqual((await pending.runs).map(run => run.status), ["ok", "ok"])
|
|
const { rows } = await pool.query("SELECT job_key,status FROM scheduler_runs WHERE started_at >= $1 AND job_key=ANY($2::text[]) ORDER BY job_key", [startedAt, jobs])
|
|
assert.deepEqual(rows, [{ job_key: "uptime_ping", status: "ok" }, { job_key: "uptime_resources", status: "ok" }])
|
|
let executions = 0
|
|
await assert.rejects(withApplicationCollectorLock(async () => {
|
|
executions++
|
|
throw new ConfigurationBusyError("server")
|
|
}), ConfigurationBusyError)
|
|
assert.equal(executions, 1, "An admitted collector must never be replayed")
|
|
const cold = await Promise.all(Array.from({ length: 24 }, load))
|
|
assert(cold.every(([filters, catalog, routes]) => filters[0].live && catalog.live && routes.live))
|
|
const revisions = () => pool.query("SELECT section,source FROM config_revisions WHERE server_id=$1 ORDER BY section,created_at", [server.id])
|
|
assert.equal((await revisions()).rowCount, 2)
|
|
hold = true
|
|
const reading = Promise.all(Array.from({ length: 24 }, load))
|
|
try {
|
|
const until = Date.now() + 5000
|
|
while (blocked < 2) { assert(Date.now() < until, "Read traffic blocked before reaching RouterOS"); await delay(10) }
|
|
assert.equal(blocked, 2, "72 simultaneous requests share one RouterOS poll per catalogue")
|
|
hold = false
|
|
for (const job of ["uptime_resources", "uptime_ping", "traffic", "internet_path"]) {
|
|
const run = await runSchedulerJobNow(job)
|
|
assert.equal(run.status, "ok", job + ": " + run.error)
|
|
}
|
|
const apply = () => independent.runInAsyncScope(() => applyRecursiveToServer(server, [route], "apply", () =>
|
|
independent.runInAsyncScope(() => assert.rejects(withApplicationMutationLock(async () => assert.fail("Overlapping writer")), ConfigurationBusyError))))
|
|
let pending!: Promise<PromiseSettledResult<Awaited<ReturnType<typeof apply>>>[]>
|
|
await withApplicationCollectorLock(async () => {
|
|
pending = Promise.allSettled([apply(), apply()])
|
|
await delay(500)
|
|
assert.equal(put.mock.callCount(), 0)
|
|
})
|
|
const results = await pending
|
|
assert.equal(results.filter(result => result.status === "fulfilled" && result.value.pushed === 1).length, 1)
|
|
assert.equal(results.filter(result => result.status === "rejected" && result.reason.code === "STATE_CONFLICT").length, 1)
|
|
} finally { hold = false; resume(); await reading }
|
|
for (const [filters, catalog, routes] of await reading) {
|
|
assert(filters[0].live && catalog.live && routes.live)
|
|
assert.equal(catalog.routes[0].dstAddress, route.dstAddress)
|
|
assert.match(routes.routes[0].id, /^\d+$/)
|
|
}
|
|
assert.equal(put.mock.callCount(), 1)
|
|
assert.equal((await revisions()).rowCount, 3, "Late reads must not overwrite the applied revision")
|
|
let writes = 0
|
|
await assert.rejects(readCatalogWithObservedCache(server, async () => ({ current: false }), async () => {
|
|
writes++; throw new ConfigurationBusyError()
|
|
}), ConfigurationBusyError)
|
|
assert.equal(writes, 1)
|
|
await assert.rejects(readCatalogWithObservedCache({ ...server, routingEndpointEpoch: "retired" },
|
|
async () => ({ current: false }), async () => assert.fail("Old endpoint wrote to cache")), { code: "STATE_CONFLICT" })
|
|
console.log("Catalog contention: 72 simultaneous WebUI reads, two shared catalogue polls, four scheduler jobs, one verified route write and no stale cache publication")
|
|
} finally { get.mock.restore(); post.mock.restore(); put.mock.restore(); independent.emitDestroy() }
|
|
}
|