118 lines
15 KiB
TypeScript
118 lines
15 KiB
TypeScript
import assert from "node:assert/strict"
|
||
import { classifyServerProbeMtu, planServerProbeExecution, projectServerProbeBandwidth, projectServerProbeDns, projectServerProbeMtu, projectServerProbePing, projectServerProbeRoute, projectServerProbeTrace, ServerProbeDataError, serverProbeExecutionRequest } from "./server-probe-execution-model.js"
|
||
import { normalizeServerProbeRestRequest, parseServerProbeRestServerId, resolveServerProbeRestBandwidthPeer, serverProbeRestErrorReply, serverProbeRestReceiptReply, ServerProbeRestContractError, type ServerProbeRestPeerMetadata, type ServerProbeRestPeerReader } from "./server-probe-rest-contract.js"
|
||
import type { ServerProbeReceipt } from "./server-probe-execution.js"
|
||
|
||
// Frozen expected strings/bodies below are copied from the existing REST
|
||
// contract, not calculated with the projector under test. No DB/DNS/native I/O.
|
||
let cases = 0
|
||
const target = "192.0.2.2"
|
||
const plan = (raw: unknown) => planServerProbeExecution(normalizeServerProbeRestRequest(raw))
|
||
const equal = (actual: unknown, expected: unknown) => { assert.deepEqual(actual, expected); cases++ }
|
||
const refused = (work: () => unknown) => { assert.throws(work); cases++ }
|
||
equal(plan({ tool: "ping", target }).nativeBody, { address: target, count: "5", size: "64", ttl: "64", interval: "0.2s" })
|
||
equal(plan({ tool: "traceroute", target }).nativeBody, { address: target, protocol: "icmp", "max-hops": "30", timeout: "00:00:01", count: "1", "use-dns": "false" })
|
||
equal(plan({ tool: "bandwidth", bwRemoteAddress: target }).nativeBody, { address: target, protocol: "tcp", direction: "both", duration: "10s" })
|
||
equal(plan({ tool: "mtu", target }).mtuSizes, [1500, 1492, 1480, 1476, 1472, 1468, 1400, 1280, 1024, 576])
|
||
for (const [tool, wire, wall] of [["ping", 120000, 130000], ["traceroute", 58000, 68000], ["bandwidth", 30000, 30000], ["dns", 30000, 30000], ["route", 10000, 10000], ["mtu", 25000, 260000]] as const) {
|
||
const planned = plan({ tool, target, bwRemoteAddress: target }); equal([planned.wireTimeoutMs, planned.wallBudgetMs], [wire, wall])
|
||
}
|
||
equal(plan({ tool: "ping", target, pingCount: 999, pingSize: 99999, pingTtl: 999 }).nativeBody, { address: target, count: "100", size: "8192", ttl: "255", interval: "0.2s" })
|
||
equal(plan({ tool: "ping", target, pingCount: 1, pingSize: 1, pingTtl: 1 }).nativeBody, { address: target, count: "1", size: "28", ttl: "1", interval: "0.2s" })
|
||
for (const [duration, expected] of [[1, "3s"], [999, "120s"]] as const) equal(plan({ tool: "bandwidth", bwRemoteAddress: target, bwProto: "udp", bwDuration: duration }).nativeBody, { address: target, protocol: "udp", direction: "both", duration: expected })
|
||
for (const [input, timeout] of [["800ms", "00:00:00.800"], ["0.001s", "00:00:00.010"], ["99s", "00:00:03"], ["00:00:00.125", "00:00:00.125"], ["01:00:00", "00:00:03"]]) equal(plan({ tool: "traceroute", target, traceHopTimeout: input }).nativeBody?.timeout, timeout)
|
||
const capped = plan({ tool: "traceroute", target, traceProto: "tcp", traceMaxHops: 999, traceProbeCount: 999, traceHopTimeout: "3s", traceUseDns: true })
|
||
equal(capped.nativeBody, { address: target, protocol: "tcp", "max-hops": "5", timeout: "00:00:03", count: "3", "use-dns": "true" })
|
||
equal(plan({ tool: "traceroute", target, traceProto: "udp", traceMaxHops: 1, traceProbeCount: 1, traceUseDns: false }).nativeBody?.protocol, "udp")
|
||
|
||
const allDocumented = { tool: " ping ", target: " 192.0.2.2 ", pingCount: 2, pingSize: 128, pingTtl: 20, traceProto: "udp", traceMaxHops: 12, traceHopTimeout: "800ms", traceProbeCount: 2, traceUseDns: false, dnsType: " txt ", bwRemoteAddress: " peer.test ", dstServerId: 9, bwProto: "udp", bwDuration: 19 }
|
||
equal(normalizeServerProbeRestRequest({ ...allDocumented, ignoredLegacyField: { arbitrary: true }, clients: "untrusted", authority: "untrusted", transport: "rest" }), { ...allDocumented, tool: "ping", target, dnsType: "TXT", bwRemoteAddress: "peer.test" })
|
||
assert(!serverProbeExecutionRequest.safeParse({ tool: "ping", target, ignoredLegacyField: true }).success); cases++
|
||
for (const tool of ["ping", "traceroute", "bandwidth", "dns", "route", "mtu"]) equal(normalizeServerProbeRestRequest({ tool, target, bwRemoteAddress: target, ignored: true }).tool, tool)
|
||
for (const invalid of [[], null, {}, { tool: "ssh" }, { tool: "ping" }, { tool: "bandwidth", target }, { tool: "route", target: "::1" }, { tool: "route", target: "example.test" }]) refused(() => normalizeServerProbeRestRequest(invalid))
|
||
for (const field of [{ pingCount: "5" }, { pingCount: 0 }, { pingSize: -1 }, { pingTtl: 1.2 }, { traceUseDns: "false" }, { traceProto: "junk" }, { traceMaxHops: 0 }, { traceHopTimeout: "00:99:01" }, { traceHopTimeout: "0s" }, { traceProbeCount: 0 }, { dnsType: "ANY" }, { target: {} }, { dstServerId: -1 }, { bwProto: "junk" }, { bwDuration: 0 }]) refused(() => normalizeServerProbeRestRequest({ tool: "ping", target, ...field }))
|
||
for (const raw of ["0", "-1", "01", "1oops", "1.2", "9007199254740993", " 1"]) refused(() => parseServerProbeRestServerId(raw))
|
||
equal(parseServerProbeRestServerId("12"), 12)
|
||
for (const [raw, error] of [[{ tool: "ping" }, "Некорректные параметры диагностики: target"], [{ tool: "bandwidth" }, "Некорректные параметры диагностики: bwRemoteAddress"], [{ tool: "route", target: "x" }, "Некорректные параметры диагностики: target"]] as const) {
|
||
try { normalizeServerProbeRestRequest(raw); assert.fail("expected validation error") } catch (failure) { assert(failure instanceof ServerProbeRestContractError); equal(serverProbeRestErrorReply(failure), { statusCode: 400, body: { error } }) }
|
||
}
|
||
|
||
equal(projectServerProbePing([{ seq: "0", ttl: "64", time: " 0ms " }, { seq: "1", status: "timeout" }, { seq: "2", ttl: 63, time: "1ms", status: "reply" }, { sent: "3", received: "2", "packet-loss": " 33% " }], target).output,
|
||
"PING 192.0.2.2\n seq=0 ttl=64 time=0ms\n seq=1 timeout\n seq=2 ttl=63 time=1ms status=reply\n sent=3 received=2 packet-loss=33%")
|
||
equal(projectServerProbePing([], target).output, "PING 192.0.2.2\n API не вернул измерений ping.")
|
||
equal(projectServerProbePing([{ status: "" }, { sent: "0", received: "0" }], target).output, "PING 192.0.2.2\n seq=? ttl=? time=—\n sent=0 received=0 packet-loss=—")
|
||
equal(projectServerProbeTrace([{ host: " hop.test ", "packet-loss": " 0% ", time: " 1ms ", "avg-rtt": " 2ms " }], plan({ tool: "traceroute", target })).output,
|
||
" # ADDRESS LOSS LAST AVG\n 1 hop.test 0% 1ms 2ms")
|
||
equal(projectServerProbeTrace([], capped).output, ";; REST API RouterOS: сессия ~60 с (параметры traceroute не продлевают лимит). max-hops снижен с 64 до 5 (count=3, timeout=00:00:03).\n # ADDRESS LOSS LAST AVG")
|
||
equal(projectServerProbeBandwidth([]).output, "(no bandwidth-test output)")
|
||
equal(projectServerProbeBandwidth([{ "tx-current": " 0 ", "rx-current": "", "test-duration": "1s" }, { "tx-total-average": "10Mbps", "rx-total-average": "20Mbps" }]).output, "bandwidth-test:\n tx=0 rx=— t=1s\n tx=10Mbps rx=20Mbps")
|
||
equal(projectServerProbeBandwidth([{ "tx-current": "", "tx-total-average": "99Mbps", "rx-current": 0 }]).output, "bandwidth-test:\n tx=— rx=0")
|
||
|
||
const dnsFixtures: Array<{ type: string; raw: unknown; name?: string; expected: string }> = [
|
||
{ type: "A", raw: ["192.0.2.10", "192.0.2.11"], expected: "example.test. IN A 192.0.2.10\nexample.test. IN A 192.0.2.11" },
|
||
{ type: "AAAA", raw: ["2001:db8::1"], expected: "example.test. IN AAAA 2001:db8::1" },
|
||
{ type: "MX", raw: [{ priority: 20, exchange: "mx2.test" }, { priority: 10, exchange: "mx1.test" }], expected: "example.test. IN MX 10 mx1.test\nexample.test. IN MX 20 mx2.test" },
|
||
{ type: "NS", raw: ["ns1.test", "ns2.test"], expected: "example.test. IN NS ns1.test\nexample.test. IN NS ns2.test" },
|
||
{ type: "TXT", raw: [["hello", " world"], [""]], expected: "example.test. IN TXT \"hello world\"\nexample.test. IN TXT \"\"" },
|
||
{ type: "CNAME", raw: ["a.test", "b.test"], expected: "example.test. IN CNAME a.test,b.test" },
|
||
{ type: "CNAME", raw: [], expected: "example.test. IN CNAME " },
|
||
{ type: "PTR", raw: ["router.test"], name: "192.0.2.2", expected: "192.0.2.2.in-addr.arpa. IN PTR router.test" },
|
||
{ type: "PTR", raw: ["router.test"], name: "2.2.0.192.in-addr.arpa", expected: "2.2.0.192.in-addr.arpa. IN PTR router.test" },
|
||
{ type: "PTR", raw: ["router.test"], name: "reverse.test", expected: "reverse.test. IN PTR router.test" },
|
||
]
|
||
for (const fixture of dnsFixtures) {
|
||
const name = fixture.name ?? "example.test"
|
||
equal(projectServerProbeDns(fixture.raw, name, fixture.type).output, `;; QUESTION: ${name} ${fixture.type}\n\n${fixture.expected}`)
|
||
equal(normalizeServerProbeRestRequest({ tool: "dns", target: name, dnsType: fixture.type.toLowerCase() }).dnsType, fixture.type)
|
||
}
|
||
equal(projectServerProbeDns([], "example.test", "A").output, ";; QUESTION: example.test A\n")
|
||
equal(projectServerProbeRoute([], target).output, "no route for 192.0.2.2 (route records checked: 0)")
|
||
equal(projectServerProbeRoute([{}], target).output, "Маршрут не подтверждён: неизвестных записей 1.")
|
||
const routeRows = [
|
||
{ active: "true", "dst-address": "0.0.0.0/0", gateway: "default", distance: "1" },
|
||
{ active: "true", "dst-address": "192.0.2.0/24", gateway: "wrong-vrf", "routing-table": "vrf", distance: "1" },
|
||
{ active: "false", "dst-address": "192.0.2.2/32", gateway: "inactive" },
|
||
{ active: "true", "dst-address": "192.0.2.0/24", gateway: "", distance: "5", "routing-mark": "" },
|
||
{ active: "yes", "dst-address": "192.0.2.0/24", gateway: "best", distance: "5", "routing-mark": "mark" },
|
||
{ active: "true", disabled: "true", "dst-address": "192.0.2.2/32", gateway: "disabled" },
|
||
{ active: "true", inactive: "true", "dst-address": "192.0.2.2/32", gateway: "inactive2" },
|
||
]
|
||
equal(projectServerProbeRoute(routeRows, target).output, "lookup 192.0.2.2 → best match:\n dst-address: 192.0.2.0/24\n gateway: best\n distance: 5\n routing-mark: mark")
|
||
equal(projectServerProbeRoute([{ active: " true ", "dst-address": " 192.0.2.0 / 24 ", gateway: "", interface: "ether1", "routing-mark": "", distance: "junk" }], target).output, "lookup 192.0.2.2 → best confirmed match (неизвестных записей: 1):\n dst-address: 192.0.2.0 / 24 \n gateway: \n distance: —\n routing-mark: ")
|
||
equal(projectServerProbeRoute([{ active: "true", "dst-address": "192.0.2.2", interface: "ether1", distance: 0 }], target).output, "lookup 192.0.2.2 → best match:\n dst-address: 192.0.2.2\n gateway: ether1\n distance: 0\n routing-mark: —")
|
||
equal(classifyServerProbeMtu([{ received: "1" }]), "reply")
|
||
equal(classifyServerProbeMtu([{ seq: "0", time: "00:00:00.001" }]), "reply")
|
||
equal(classifyServerProbeMtu([{ status: "timeout" }]), "timeout")
|
||
equal(projectServerProbeMtu([{ size: 1500, result: "timeout" }, { size: 1492, result: "reply" }], target).output, "MTU discovery (do-not-fragment ping) → 192.0.2.2\n\n1500 timeout; причина не определена\n 1492 ✓ ok\n\nMTU (DF): ~1492 bytes")
|
||
const timeouts = [1500, 1492, 1480, 1476, 1472, 1468, 1400, 1280, 1024, 576].map(size => ({ size, result: "timeout" as const }))
|
||
equal(projectServerProbeMtu(timeouts, target).data.mtu, null)
|
||
assert(projectServerProbeMtu(timeouts, target).output.endsWith("\n\nMTU: could not determine")); cases++
|
||
for (const raw of [[], [{}], [{ seq: "0", time: "junk" }], [{ received: "99999999999999999999999999" }]]) refused(() => classifyServerProbeMtu(raw))
|
||
for (const measurements of [[], [{ size: 1492, result: "reply" as const }], [{ size: 1500, result: "timeout" as const }], [{ size: 1500, result: "reply" as const }, { size: 1492, result: "reply" as const }]]) refused(() => projectServerProbeMtu(measurements, target))
|
||
for (const work of [() => projectServerProbePing([{ seq: "junk" }], target), () => projectServerProbeTrace("raw provider diagnostic", capped), () => projectServerProbeBandwidth([{ "tx-current": {} }]), () => projectServerProbeDns(["not IPv4"], "test", "A"), () => projectServerProbeDns([[123]], "test", "TXT"), () => projectServerProbeDns([123], "test", "NS"), () => projectServerProbeDns([], "test", "ANY")]) { assert.throws(work, ServerProbeDataError); cases++ }
|
||
|
||
const peers: ServerProbeRestPeerMetadata[] = [{ id: 2, host: " PEER.test ", enabled: true }, { id: 3, host: "peer.test", enabled: true }, { id: 4, host: "disabled.test", enabled: false }]
|
||
const lookups: Array<{ kind: string; value: string | number; scope: readonly number[] }> = []
|
||
const reader: ServerProbeRestPeerReader = {
|
||
async byId(id, scope) { lookups.push({ kind: "id", value: id, scope }); return peers.find(row => row.id === id && scope.includes(row.id)) },
|
||
async enabledByHost(host, scope) { lookups.push({ kind: "host", value: host, scope }); return peers.filter(row => scope.includes(row.id) && row.enabled && row.host.trim().toLowerCase() === host) },
|
||
}
|
||
equal(await resolveServerProbeRestBandwidthPeer("different.test", 3, [2, 3, 4], reader), peers[1])
|
||
equal(lookups.at(-1), { kind: "id", value: 3, scope: [2, 3, 4] })
|
||
equal(await resolveServerProbeRestBandwidthPeer(" PEER.TEST ", 999, [2, 3, 4], reader), peers[0])
|
||
equal(lookups.slice(-2), [{ kind: "id", value: 999, scope: [2, 3, 4] }, { kind: "host", value: "peer.test", scope: [2, 3, 4] }])
|
||
equal(await resolveServerProbeRestBandwidthPeer("peer.test", undefined, [3], reader), peers[1])
|
||
for (const [remote, id, status] of [["peer.test", 4, 409], ["missing.test", undefined, 400]] as const) {
|
||
const before = lookups.length
|
||
await assert.rejects(resolveServerProbeRestBandwidthPeer(remote, id, [2, 3, 4], reader), (failure: unknown) => failure instanceof ServerProbeRestContractError && failure.statusCode === status); cases++
|
||
if (id === 4) equal(lookups.length, before + 1)
|
||
}
|
||
await assert.rejects(resolveServerProbeRestBandwidthPeer("peer.test", undefined, [2], { ...reader, async enabledByHost() { return [peers[1]] } }), (failure: unknown) => failure instanceof ServerProbeRestContractError && failure.statusCode === 403); cases++
|
||
const completed: ServerProbeReceipt = { receiptId: "00000000-0000-4000-8000-000000000001", tool: "ping", serverId: 1, state: "completed", httpStatus: 200, output: "PING fixture", data: { kind: "ping" }, attemptedStages: 1, completedStages: 1, automaticReplay: false, forwardingVerified: false }
|
||
equal(serverProbeRestReceiptReply(completed), { statusCode: 200, body: { output: "PING fixture" } })
|
||
for (const output of [";; QUESTION: test A\n;; ERROR: safe failure", " ERROR: safe failure"]) equal(serverProbeRestReceiptReply({ ...completed, output }), { statusCode: 502, body: { error: output } })
|
||
for (const [code, status] of [["NOT_FOUND", 404], ["SOURCE_UNAVAILABLE", 409], ["DESTINATION_DISABLED", 409], ["DESTINATION_UNAVAILABLE", 400], ["CANCELLED", 502], ["MEASUREMENT_UNKNOWN", 502], ["JOURNAL_UNKNOWN", 503], ["PERMISSION_DENIED", 403]] as const) equal(serverProbeRestErrorReply({ code }).statusCode, status)
|
||
equal(serverProbeRestReceiptReply({ ...completed, state: "unknown", httpStatus: 503, errorCode: "JOURNAL_UNKNOWN", output: "must not publish" }).statusCode, 503)
|
||
assert(!JSON.stringify(serverProbeRestErrorReply(Object.assign(new Error("NEVER_RAW_PROVIDER_PASSWORD"), { code: "ECONNRESET" }))).includes("NEVER_RAW_PROVIDER_PASSWORD")); cases++
|
||
console.log(`server probe REST contract: ${cases} inert parity cases passed`)
|