Files
MikrotikManager/backend/src/services/bandwidth-admission.ts
T

311 lines
21 KiB
TypeScript

import { assertBandwidthTestCompleted } from "./bandwidth-test-status.js"
import { isDeepStrictEqual } from "node:util"
import { performance } from "node:perf_hooks"
import { dispatchBandwidthNativeRequest, type BandwidthNativeDispatchGate, type BandwidthNativeRequestBinder } from "./bandwidth-native-dispatch.js"
/** Pure foundation: all identities, control generations, proofs and durable I/O
* must come from trusted composition. This module enrolls no physical nodes and
* provides no default journal, readiness, native transport or recovery policy. */
export const BANDWIDTH_CALLER_KINDS = ["rest-speed", "scheduled-speed", "mcp-speed", "routing-measurement", "rest-diagnostic", "mcp-diagnostic", "legacy-diagnostic", "speed-inner"] as const
export type BandwidthCallerKind = typeof BANDWIDTH_CALLER_KINDS[number]
type Json = null | boolean | number | string | Json[] | { [key: string]: Json }
export interface BandwidthParticipant { canonicalNodeId: string; endpointProof: string }
export interface BandwidthAdmissionInput {
attemptId: string
callerKind: BandwidthCallerKind
operationId: string
request: { [key: string]: Json }
source: BandwidthParticipant
destination: BandwidthParticipant
authorityProof: string
authorityGeneration: string
controlGeneration: string
expiresAt: number
durationSec: number
/** Exact native body, including destination credentials and every extra field. */
nativeBody: Record<string, string>
}
export interface BandwidthBinding {
attemptId: string; callerKind: BandwidthCallerKind; operationId: string
source: BandwidthParticipant; destination: BandwidthParticipant
authorityProof: string; authorityGeneration: string; controlGeneration: string
expiresAt: number; durationSec: number
requestProof: string; commandProof: string; bindingProof: string
}
export interface BandwidthScope { signal?: AbortSignal; deadlineAt: number }
export type BandwidthTransition = "reserve" | "arm" | "complete" | "release-before-dispatch" | "quarantine"
/** Only a NEW, transaction-committed transition may return this acknowledgement.
* A row read, existing/idempotent transition or uncertain COMMIT is not an ACK. */
export interface BandwidthJournalAck {
outcome: "new"; transition: BandwidthTransition; ackId: string
attemptId: string; bindingProof: string; controlGeneration: string
}
export interface BandwidthJournal {
/** Every adapter must own an active I/O lifetime and recheck it, the original
* signal and absolute deadline at SQL dispatch and immediately before COMMIT.
* A model timeout retires its continuation, not a physical in-flight COMMIT.
* Late/uncertain writes stay fenced; they never justify retry or adoption. */
reserve(binding: Readonly<BandwidthBinding>, scope: BandwidthScope): Promise<BandwidthJournalAck>
arm(binding: Readonly<BandwidthBinding>, scope: BandwidthScope): Promise<BandwidthJournalAck>
/** Atomically authenticate terminal evidence and release both exact owners. */
complete(binding: Readonly<BandwidthBinding>, evidence: Readonly<{ terminalProof: string }>, scope: BandwidthScope): Promise<BandwidthJournalAck>
releaseBeforeDispatch(binding: Readonly<BandwidthBinding>, evidence: Readonly<{ from: "reserved" | "armed"; proof: "private-no-send" }>, scope: BandwidthScope): Promise<BandwidthJournalAck>
/** Failure of this bookkeeping must never clear reserved/armed occupancy. */
quarantine(binding: Readonly<BandwidthBinding>, scope: BandwidthScope): Promise<BandwidthJournalAck>
}
export interface BandwidthAdmissionDependencies {
now(): number
cleanupBudgetMs: number
/** REQUIRED keyed, purpose-separated trusted proof; never plain SHA of secrets. */
keyedProof(purpose: string, value: unknown): Promise<string>
authorize(binding: Readonly<BandwidthBinding>, scope: BandwidthScope): Promise<{ authorityProof: string; authorityGeneration: string; controlGeneration: string; expiresAt: number }>
endpoints(binding: Readonly<BandwidthBinding>, scope: BandwidthScope): Promise<{ source: BandwidthParticipant; destination: BandwidthParticipant }>
journal: BandwidthJournal
/** Fixed trusted transport. Invocation means a physical send may have happened,
* even if it throws synchronously; no model-supplied execution callback exists. */
send(binding: Readonly<BandwidthBinding>, nativeBody: Readonly<Record<string, string>>, scope: BandwidthScope, permit: BandwidthNativePermit): Promise<unknown>
/** Fixed native client object captured by trusted broker composition. Without
* this target, a model-only admission cannot issue a usable transport permit. */
nativeClient?: object
/** Fixed server-owned dispatch gate. No request supplies lease or authority callbacks. */
nativeDispatchGate?: BandwidthNativeDispatchGate
}
export class BandwidthAdmissionError extends Error {
constructor(readonly code: "INVALID_INPUT" | "REFUSED" | "EXPIRED" | "ABORTED" | "PERSISTENCE_UNKNOWN" | "REMOTE_UNKNOWN" | "COMPLETION_PERSISTENCE_UNKNOWN") { super("Bandwidth admission: " + code) }
}
declare const capabilityBrand: unique symbol
export type BandwidthDispatchCapability = Readonly<{ [capabilityBrand]: true }>
declare const nativePermitBrand: unique symbol
export type BandwidthNativePermit = Readonly<{ [nativePermitBrand]: true }>
type NativePermitState={active:boolean;client:object|undefined;body:Readonly<Record<string,string>>;scope:Readonly<BandwidthScope>;monotonicEnd:number;nativeDispatchGate?:Readonly<BandwidthNativeDispatchGate>}
const nativePermits=new WeakMap<object,NativePermitState>()
/** Verification only. Minting remains private to the committed admission
* dispatch below. A failed use consumes the permit before any comparison. */
export function consumeBandwidthNativePermit(permit:unknown,client:object,path:string,body:unknown,signal?:AbortSignal):void{
const state=permit&&typeof permit==="object"?nativePermits.get(permit):undefined
if(!state?.active)throw new BandwidthAdmissionError("REFUSED")
state.active=false
if(state.nativeDispatchGate||state.client!==client||path!=="/tool/bandwidth-test"||state.scope.signal!==signal
||signal?.aborted||Date.now()>=state.scope.deadlineAt||performance.now()>=state.monotonicEnd
||!isDeepStrictEqual(body,state.body))throw new BandwidthAdmissionError("REFUSED")
}
/** Private transport integration only. Retire before any await; the historical
* consume-only API cannot bypass a gate-bound permit. start is fixed rosPost,
* never a public command/body callback. Ungated v1 behavior remains unchanged. */
export function dispatchBandwidthNativePermit<T>(permit:unknown,client:object,path:string,body:unknown,signal:AbortSignal|undefined,
start:(bindRequest?:BandwidthNativeRequestBinder)=>Promise<T>):Promise<T>{
const state=permit&&typeof permit==="object"?nativePermits.get(permit):undefined
if(!state?.active)throw new BandwidthAdmissionError("REFUSED")
state.active=false
const assertOriginal=()=>{
if(state.client!==client||path!=="/tool/bandwidth-test"||state.scope.signal!==signal
||signal?.aborted||Date.now()>=state.scope.deadlineAt||performance.now()>=state.monotonicEnd
||!isDeepStrictEqual(body,state.body))throw new BandwidthAdmissionError("REFUSED")
}
assertOriginal()
return state.nativeDispatchGate
?dispatchBandwidthNativeRequest(state.nativeDispatchGate,state.scope,state.monotonicEnd,assertOriginal,start)
:start()
}
type Phase = "new" | "reserving" | "reserved" | "arming" | "armed" | "checking" | "sending" | "released" | "unknown-busy"
function fail(code: BandwidthAdmissionError["code"]): never { throw new BandwidthAdmissionError(code) }
const hash = (value: unknown): value is string => typeof value === "string" && /^[a-f0-9]{64}$/.test(value)
const label = (value: unknown): value is string => typeof value === "string" && /^[a-zA-Z0-9_.:-]{1,200}$/.test(value)
const plain = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype
function json(value: unknown, depth = 0): boolean {
if (depth > 16) return false
if (value === null || typeof value === "string" || typeof value === "boolean") return true
if (typeof value === "number") return Number.isFinite(value) && (!Number.isInteger(value) || Number.isSafeInteger(value))
if (Array.isArray(value)) return value.length <= 2000 && value.every(item => json(item, depth + 1))
return plain(value) && Object.keys(value).length <= 256 && Object.values(value).every(item => json(item, depth + 1))
}
function freeze<T>(value: T): T {
const pending: unknown[] = [value]
while (pending.length) {
const item = pending.pop()
if (!item || typeof item !== "object" || Object.isFrozen(item)) continue
Object.freeze(item)
for (const child of Object.values(item)) if (child && typeof child === "object") pending.push(child)
}
return value
}
/** Native transport already supplies JSON. Preserve its complete existing 8 MiB
* envelope independently of the tighter request schema. JSON snapshot failures
* (cycles, unsupported values, serializer exhaustion) leave occupancy unknown;
* native rows, object keys and nesting receive no new business limits. */
function nativeSnapshot(value: unknown): unknown {
try {
const text = JSON.stringify(value)
if (typeof text !== "string" || Buffer.byteLength(text) > 8 * 1048576) fail("REMOTE_UNKNOWN")
return freeze(JSON.parse(text) as unknown)
} catch { fail("REMOTE_UNKNOWN") }
}
function participant(value: unknown): value is BandwidthParticipant { return plain(value) && Object.keys(value).sort().join(",") === "canonicalNodeId,endpointProof" && label(value.canonicalNodeId) && hash(value.endpointProof) }
function sameEndpoints(value: { source: BandwidthParticipant; destination: BandwidthParticipant }, expected: BandwidthAdmissionInput) {
return participant(value.source) && participant(value.destination) && value.source.canonicalNodeId === expected.source.canonicalNodeId && value.source.endpointProof === expected.source.endpointProof && value.destination.canonicalNodeId === expected.destination.canonicalNodeId && value.destination.endpointProof === expected.destination.endpointProof
}
export function createBandwidthAdmission(input: BandwidthAdmissionInput, deps: BandwidthAdmissionDependencies) {
if (!json(input) || Object.keys(input).sort().join(",") !== "attemptId,authorityGeneration,authorityProof,callerKind,controlGeneration,destination,durationSec,expiresAt,nativeBody,operationId,request,source"
|| Buffer.byteLength(JSON.stringify(input)) > 1048576 || !plain(input.request) || !plain(input.nativeBody)
|| Object.values(input.nativeBody).some(value => typeof value !== "string")
|| !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(input.attemptId)
|| !BANDWIDTH_CALLER_KINDS.includes(input.callerKind) || !label(input.operationId)
|| !participant(input.source) || !participant(input.destination) || input.source.canonicalNodeId === input.destination.canonicalNodeId
|| !hash(input.authorityProof) || !label(input.authorityGeneration) || !label(input.controlGeneration)
|| !Number.isSafeInteger(input.expiresAt) || input.expiresAt <= 0
|| !Number.isSafeInteger(input.durationSec) || input.durationSec < 3 || input.durationSec > 2147483647
|| input.nativeBody.duration !== `${input.durationSec}s`
|| !Number.isSafeInteger(deps.cleanupBudgetMs) || deps.cleanupBudgetMs <= 0 || deps.cleanupBudgetMs > 10000) fail("INVALID_INPUT")
const captured = freeze(structuredClone(input))
const now = deps.now.bind(deps), keyedProof = deps.keyedProof.bind(deps), authorize = deps.authorize.bind(deps), endpoints = deps.endpoints.bind(deps), send = deps.send.bind(deps)
const nativeClient=deps.nativeClient
const configuredDispatchGate=deps.nativeDispatchGate
const nativeDispatchGate=configuredDispatchGate?Object.freeze({acquire:configuredDispatchGate.acquire.bind(configuredDispatchGate)}):undefined
const journal = { reserve: deps.journal.reserve.bind(deps.journal), arm: deps.journal.arm.bind(deps.journal), complete: deps.journal.complete.bind(deps.journal), releaseBeforeDispatch: deps.journal.releaseBeforeDispatch.bind(deps.journal), quarantine: deps.journal.quarantine.bind(deps.journal) }
const cleanupBudgetMs = deps.cleanupBudgetMs
let phase: Phase = "new", binding: Readonly<BandwidthBinding> | undefined, originalScope: BandwidthScope | undefined, remoteCompletionConfirmed = false
let nativeMonotonicEnd=0
const capabilities = new WeakMap<object, { active: boolean }>(), acknowledgements = new Set<string>(), partials = new WeakMap<object, unknown>()
function check(scope: BandwidthScope) {
if (scope.signal?.aborted) fail("ABORTED")
if (now() >= scope.deadlineAt) fail("EXPIRED")
}
/** Race only closes our continuation. A late journal/transport result cannot
* mint a capability, release occupancy or resume dispatch in this scope. */
function bounded<T>(scope: BandwidthScope, work: () => Promise<T>): Promise<T> {
check(scope)
return new Promise((resolve, reject) => {
let settled = false, timer: ReturnType<typeof setTimeout> | undefined
const finish = (value: T | unknown, failed: boolean) => {
if (settled) return
settled = true; if (timer) clearTimeout(timer); scope.signal?.removeEventListener("abort", abort)
if (failed) reject(value); else resolve(value as T)
}
const abort = () => finish(new BandwidthAdmissionError("ABORTED"), true)
const tick = () => { if (settled) return; const remaining = scope.deadlineAt - now(); if (remaining <= 0) finish(new BandwidthAdmissionError("EXPIRED"), true); else timer = setTimeout(tick, Math.min(remaining, 2147483647)) }
scope.signal?.addEventListener("abort", abort, { once: true }); tick()
if (settled) return
if (scope.signal?.aborted) { abort(); return }
try { void work().then(value => finish(value, false), error => finish(error, true)) } catch (error) { finish(error, true) }
})
}
function ack(value: BandwidthJournalAck, transition: BandwidthTransition) {
if (!value || value.outcome !== "new" || value.transition !== transition || !label(value.ackId) || acknowledgements.has(value.ackId)
|| value.attemptId !== binding!.attemptId || value.bindingProof !== binding!.bindingProof || value.controlGeneration !== binding!.controlGeneration) fail("PERSISTENCE_UNKNOWN")
acknowledgements.add(value.ackId)
}
const cleanupScope = (): BandwidthScope => ({ deadlineAt: now() + cleanupBudgetMs })
async function quarantine() {
phase = "unknown-busy"
if (!binding) return
const scope = cleanupScope()
try { ack(await bounded(scope, () => journal.quarantine(binding!, scope)), "quarantine") } catch { /* Existing occupancy remains authoritative even without this ACK. */ }
}
async function release(from: "reserved" | "armed") {
const scope = cleanupScope()
try { ack(await bounded(scope, () => journal.releaseBeforeDispatch(binding!, { from, proof: "private-no-send" }, scope)), "release-before-dispatch"); phase = "released" }
catch { await quarantine(); fail("PERSISTENCE_UNKNOWN") }
}
async function fresh(scope: BandwidthScope) {
const value = await bounded(scope, () => authorize(binding!, scope)); check(scope)
if (value.authorityProof !== captured.authorityProof || value.authorityGeneration !== captured.authorityGeneration || value.controlGeneration !== captured.controlGeneration || value.expiresAt !== captured.expiresAt) fail("REFUSED")
}
function take(capability: BandwidthDispatchCapability) {
const owned = capability && typeof capability === "object" ? capabilities.get(capability) : undefined
if (!owned?.active || phase !== "armed") fail("REFUSED")
owned.active = false // Retire before the first async boundary, including cancellation.
}
return Object.freeze({
status: () => Object.freeze({ phase, remoteCompletionConfirmed }),
/** Private error-identity lookup for bounded diagnostic presentation. A local
* diagnostic may finish displaying partials while occupancy stays unknown.
* JSON copies of the error cannot retrieve/adopt these rows or retry native. */
partialResponse: (error: unknown): unknown => error && typeof error === "object" && partials.has(error) ? nativeSnapshot(partials.get(error)) : undefined,
async reserveAndArm(options: BandwidthScope): Promise<BandwidthDispatchCapability> {
if (phase !== "new") fail("REFUSED")
if (!Number.isSafeInteger(options.deadlineAt) || options.deadlineAt <= 0) fail("INVALID_INPUT")
originalScope = Object.freeze({ signal: options.signal, deadlineAt: Math.min(options.deadlineAt, captured.expiresAt) })
nativeMonotonicEnd=performance.now()+Math.max(0,originalScope.deadlineAt-Date.now())
const scope = originalScope
// No operation may be resumed/retried through this admission instance.
phase = "checking"
try {
const requestProof = await bounded(scope, () => keyedProof("bandwidth-request-v1", captured.request))
const commandProof = await bounded(scope, () => keyedProof("bandwidth-command-v1", captured.nativeBody))
const core = { attemptId: captured.attemptId, callerKind: captured.callerKind, operationId: captured.operationId, source: captured.source, destination: captured.destination, authorityProof: captured.authorityProof, authorityGeneration: captured.authorityGeneration, controlGeneration: captured.controlGeneration, expiresAt: captured.expiresAt, durationSec: captured.durationSec, requestProof, commandProof }
const bindingProof = await bounded(scope, () => keyedProof("bandwidth-binding-v1", core))
if (![requestProof, commandProof, bindingProof].every(hash)) fail("REFUSED")
binding = freeze({ ...core, bindingProof })
await fresh(scope)
phase = "reserving"; ack(await bounded(scope, () => journal.reserve(binding!, scope)), "reserve"); phase = "reserved"
await fresh(scope)
const current = await bounded(scope, () => endpoints(binding!, scope)); check(scope)
if (!sameEndpoints(current, captured)) fail("REFUSED")
await fresh(scope)
phase = "arming"; ack(await bounded(scope, () => journal.arm(binding!, scope)), "arm"); phase = "armed"
check(scope)
const capability = Object.freeze(Object.create(null)) as BandwidthDispatchCapability
capabilities.set(capability, { active: true }); return capability
} catch (error) {
if (phase === "checking") {
phase = "released" // No reserve was attempted.
if (error instanceof BandwidthAdmissionError) throw error
fail("REFUSED")
}
if (phase === "reserved" || phase === "armed") await release(phase)
else if (phase === "reserving" || phase === "arming") await quarantine()
if (error instanceof BandwidthAdmissionError) throw error
fail("PERSISTENCE_UNKNOWN")
}
},
async cancel(capability: BandwidthDispatchCapability): Promise<void> { take(capability); phase = "checking"; await release("armed") },
async dispatch(capability: BandwidthDispatchCapability): Promise<{ remoteCompletionConfirmed: true; raw: Array<Record<string, unknown>> }> {
take(capability); phase = "checking"
const scope = originalScope!
let invoked = false, partialRaw: unknown
try {
await fresh(scope)
const current = await bounded(scope, () => endpoints(binding!, scope)); check(scope)
if (!sameEndpoints(current, captured)) fail("REFUSED")
await fresh(scope); check(scope)
const received = await bounded(scope, async () => {
invoked = true; phase = "sending"
const permit=Object.freeze(Object.create(null)) as BandwidthNativePermit
const state:NativePermitState={active:true,client:nativeClient,body:captured.nativeBody,scope,
monotonicEnd:nativeMonotonicEnd,nativeDispatchGate}
nativePermits.set(permit,state)
try{return await send(binding!,captured.nativeBody,scope,permit)}
finally{state.active=false;nativePermits.delete(permit)}
})
check(scope)
const raw = nativeSnapshot(received)
partialRaw = raw
try { assertBandwidthTestCompleted(raw) } catch { fail("REMOTE_UNKNOWN") }
remoteCompletionConfirmed = true
// Terminal bookkeeping is independent of expired/revoked execute authority.
const cleanup = cleanupScope()
try {
const terminalProof = await bounded(cleanup, () => keyedProof("bandwidth-terminal-v1", { bindingProof: binding!.bindingProof, raw }))
if (!hash(terminalProof)) fail("COMPLETION_PERSISTENCE_UNKNOWN")
ack(await bounded(cleanup, () => journal.complete(binding!, { terminalProof }, cleanup)), "complete")
phase = "released"
} catch { await quarantine(); fail("COMPLETION_PERSISTENCE_UNKNOWN") }
return { remoteCompletionConfirmed: true, raw: raw as Array<Record<string, unknown>> }
} catch (error) {
if (!invoked) {
await release("armed")
if (error instanceof BandwidthAdmissionError) throw error
fail("REFUSED")
}
else if ((phase as Phase) !== "released" && (phase as Phase) !== "unknown-busy") await quarantine()
if (error instanceof BandwidthAdmissionError && error.code === "COMPLETION_PERSISTENCE_UNKNOWN") throw error
const unknown = new BandwidthAdmissionError("REMOTE_UNKNOWN")
if (partialRaw !== undefined) partials.set(unknown, partialRaw)
throw unknown
}
},
})
}