Files
MikrotikManager/backend/src/services/server-poll-cost-diagnostics.test.ts
T

115 lines
7.4 KiB
TypeScript

import assert from "node:assert/strict"
import { test } from "node:test"
import { installServerPollCostDiagnostics } from "./server-poll-cost-diagnostics.js"
test("promise identity, receiver, arguments and exact descriptor survive instrumentation", async () => {
const result = Promise.resolve({ secret: "result" }), values = ["private-parameter"]
const config = { text: "SELECT * FROM server_poll_acks WHERE secret=$1", values }
const prototype = { query(this: unknown, ...args: unknown[]) { assert.equal(this, client); assert.deepEqual(args, [config]); return result } }
const descriptor = Object.getOwnPropertyDescriptor(prototype, "query")
const client = Object.create(prototype) as typeof prototype
let time = 10
const diagnostics = installServerPollCostDiagnostics({ prototype, now: () => time })
try {
assert.equal(client.query(config), result); time = 17; await result
assert.deepEqual(diagnostics.snapshot().categories, [{ category: "server_poll_acks:SELECT", count: 1, totalMs: 7, maxMs: 7, errors: 0 }])
assert(!JSON.stringify(diagnostics.snapshot()).includes("private"))
const snapshot = diagnostics.snapshot(); snapshot.categories[0].count = 99
assert.equal(diagnostics.snapshot().categories[0].count, 1)
} finally { diagnostics.restore() }
assert.deepEqual(Object.getOwnPropertyDescriptor(prototype, "query"), descriptor)
})
test("callback receiver, all arguments, return and original query return are preserved", () => {
const receiver = {}, error = new Error("private-error"), result = { secret: "private-result" }, queryReturn = {}
const callbackReturn = {}, params = ["private-param"]
const prototype = { query(this: unknown, ...args: unknown[]) {
assert.equal(this, client); assert.equal(args[0], "INSERT INTO server_poll_intents VALUES($1)"); assert.equal(args[1], params)
assert.equal(Reflect.apply(args[2] as (...values: unknown[]) => unknown, receiver, [error, result, 3]), callbackReturn)
return queryReturn
} }
const client = Object.create(prototype) as typeof prototype
const diagnostics = installServerPollCostDiagnostics({ prototype })
try {
const callback = function(this: unknown, ...args: unknown[]) { assert.equal(this, receiver); assert.deepEqual(args, [error, result, 3]); return callbackReturn }
assert.equal(client.query("INSERT INTO server_poll_intents VALUES($1)", params, callback), queryReturn)
const snapshot = diagnostics.snapshot(); assert.equal(snapshot.categories[0].errors, 1)
assert(!JSON.stringify(snapshot).includes("private"))
} finally { diagnostics.restore() }
})
test("rejected promise and synchronous throw keep original identities and are counted once", async () => {
const failure = new Error("do-not-log"), promise = Promise.reject(failure)
let sync = false
const prototype = { query() { if (sync) throw failure; return promise } }
const diagnostics = installServerPollCostDiagnostics({ prototype })
try {
assert.equal(prototype.query(), promise); await assert.rejects(promise, error => error === failure)
sync = true; assert.throws(() => prototype.query(), error => error === failure)
assert.equal(diagnostics.snapshot().categories[0].count, 2); assert.equal(diagnostics.snapshot().categories[0].errors, 2)
assert(!JSON.stringify(diagnostics.snapshot()).includes("do-not-log"))
} finally { diagnostics.restore() }
})
test("deferred callbacks aggregate completion costs and preserve receiver", () => {
let pending: ((...values: unknown[]) => unknown) | undefined, time = 0
const returned = {}, receiver = {}
const prototype = { query(...args: unknown[]) { pending = args[1] as typeof pending; return returned } }
const diagnostics = installServerPollCostDiagnostics({ prototype, now: () => time })
try {
const callback = function(this: unknown, error: unknown, value: unknown) { assert.equal(this, receiver); assert.equal(error, null); return value }
assert.equal(prototype.query("UPDATE servers SET name=$1", callback), returned)
assert.equal(diagnostics.snapshot().categories.length, 0)
time = 5; assert.equal(Reflect.apply(pending!, receiver, [null, "first"]), "first")
time = 10; prototype.query("UPDATE servers SET name=$1", callback)
time = 13; assert.equal(Reflect.apply(pending!, receiver, [null, "second"]), "second")
assert.deepEqual(diagnostics.snapshot().categories, [{ category: "servers:UPDATE", count: 2, totalMs: 8, maxMs: 5, errors: 0 }])
} finally { diagnostics.restore() }
})
test("callback throw propagates without double counting or changing error", () => {
const failure = new Error("callback"), prototype = { query(...args: unknown[]) { return Reflect.apply(args[1] as (...values: unknown[]) => unknown, null, [null, {}]) } }
const diagnostics = installServerPollCostDiagnostics({ prototype })
try {
assert.throws(() => prototype.query("SELECT 1", () => { throw failure }), error => error === failure)
assert.equal(diagnostics.snapshot().categories[0].count, 1)
assert.equal(diagnostics.snapshot().categories[0].errors, 0)
} finally { diagnostics.restore() }
})
test("bounded categories use only fixed tags, including overflow", () => {
const prototype = { query(...args: unknown[]) { return Reflect.apply(args[1] as (...values: unknown[]) => unknown, null, [null, {}]) } }
const diagnostics = installServerPollCostDiagnostics({ prototype })
try {
const tables = ["server_poll_storage_admissions", "server_poll_storage_usage", "server_poll_archives", "server_poll_executions", "server_poll_intents", "server_poll_acks", "server_poll_receipts", "server_poll_quarantines", "mcp_operations", "mcp_operation_steps", "mcp_plans", "mcp_connections", "mcp_credentials", "mcp_settings"]
for (const table of tables) for (const command of ["SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK", "SET", "WITH", "SHOW"]) {
// Callback completion is synchronous for this test double.
prototype.query(`${command} ${table} private-name`, () => {})
}
const categories = diagnostics.snapshot().categories
assert.equal(categories.length, 128)
assert.equal(categories.reduce((sum, item) => sum + item.count, 0), 140)
assert.equal(categories.find(item => item.category === "overflow:OTHER")?.count, 13)
assert(!JSON.stringify(categories).includes("private"))
} finally { diagnostics.restore() }
})
test("opaque config getters and unsupported return values remain untouched", () => {
const config = { get text(): string { throw Error("must not inspect getter") } }, returned = { opaque: true }
const prototype = { query(...args: unknown[]) { assert.equal(args[0], config); return returned } }
const diagnostics = installServerPollCostDiagnostics({ prototype, now: () => { throw Error("clock") } })
try {
assert.equal(prototype.query(config), returned)
assert.deepEqual(diagnostics.snapshot().categories, [])
} finally { diagnostics.restore() }
})
test("current authority and portal tables have fixed diagnostic categories", () => {
const prototype = { query(...args: unknown[]) { return Reflect.apply(args[1] as (...values: unknown[]) => unknown, null, [null, {}]) } }
const diagnostics = installServerPollCostDiagnostics({ prototype })
try {
for (const table of ["mcp_grants", "mcp_protections", "mcp_owner_revocations"]) prototype.query(`SELECT * FROM ${table}`, () => {})
assert.deepEqual(diagnostics.snapshot().categories.map(row => row.category), ["mcp_grants:SELECT", "mcp_owner_revocations:SELECT", "mcp_protections:SELECT"])
} finally { diagnostics.restore() }
})