86 lines
4.9 KiB
TypeScript
86 lines
4.9 KiB
TypeScript
/** Trusted assembly only. Acquire the global mapping barrier BEFORE the
|
|
* registry/owner barrier; retain both through the existing private native
|
|
* ClientRequest.finish handoff. This is transport composition, not a mapping
|
|
* issuer, RouterOS route proof, or all-writer activation. */
|
|
import { performance } from "node:perf_hooks"
|
|
import type { BandwidthScope } from "./bandwidth-admission.js"
|
|
import type { BandwidthNativeDispatchGate, BandwidthNativeDispatchLease } from "./bandwidth-native-dispatch.js"
|
|
|
|
const refused = () => new Error("Bandwidth composite native fence refused")
|
|
function captureScope(raw: Readonly<BandwidthScope>): Readonly<BandwidthScope> {
|
|
if (!raw || Object.getPrototypeOf(raw) !== Object.prototype) throw refused()
|
|
const fields = Object.getOwnPropertyDescriptors(raw)
|
|
if (Reflect.ownKeys(raw).length !== Object.keys(fields).length || Object.keys(fields).some(key => !["deadlineAt", "signal"].includes(key))
|
|
|| Object.values(fields).some(field => !("value" in field) || !field.enumerable)) throw refused()
|
|
const deadlineAt = fields.deadlineAt?.value as number, signal = fields.signal?.value as AbortSignal | undefined
|
|
if (!Number.isSafeInteger(deadlineAt) || signal !== undefined && !(signal instanceof AbortSignal)) throw refused()
|
|
return Object.freeze({ deadlineAt, signal })
|
|
}
|
|
|
|
export function createBandwidthNativeDispatchCompositeGate(gates: readonly Readonly<BandwidthNativeDispatchGate>[]): Readonly<BandwidthNativeDispatchGate> {
|
|
if (!Array.isArray(gates) || gates.length < 2 || gates.length > 4 || new Set(gates).size !== gates.length) throw refused()
|
|
const acquire = Object.freeze(gates.map(gate => {
|
|
if (!gate || typeof gate.acquire !== "function") throw refused()
|
|
return gate.acquire.bind(gate)
|
|
}))
|
|
let used = false
|
|
return Object.freeze({ async acquire(input: Readonly<BandwidthScope>): Promise<BandwidthNativeDispatchLease> {
|
|
if (used) throw refused(); used = true
|
|
const scope = captureScope(input), mono = performance.now(), wall = Date.now()
|
|
const end = mono + Math.max(0, Math.min(5000, scope.deadlineAt - wall))
|
|
const leases: Array<Readonly<BandwidthNativeDispatchLease>> = []
|
|
let active = true, verifying = false
|
|
let rejectStopped!: (error: Error) => void
|
|
const stopped = new Promise<never>((_resolve, reject) => { rejectStopped = reject })
|
|
void stopped.catch(() => {})
|
|
const live = () => { if (!active || scope.signal?.aborted || Date.now() >= scope.deadlineAt || performance.now() >= end) throw refused() }
|
|
// Retry a failed child's physical close when the private kernel retries
|
|
// close(); successfully retired children are never returned to healthy use.
|
|
const close = () => {
|
|
active = false; clearTimeout(timer); scope.signal?.removeEventListener("abort", stop)
|
|
let failure: unknown
|
|
for (let index = leases.length - 1; index >= 0; index--) {
|
|
try { leases[index].close(); leases.splice(index, 1) } catch (error) { failure ??= error }
|
|
}
|
|
if (failure) throw failure
|
|
}
|
|
const stop = () => { try { close() } catch { /* Kernel close retries failed physical destruction. */ } rejectStopped(refused()) }
|
|
const captureLease = (value: Readonly<BandwidthNativeDispatchLease>) => {
|
|
if (!value || typeof value.verify !== "function" || typeof value.close !== "function") {
|
|
try { value?.close?.() } catch { /* Invalid late lease cannot become authority. */ }
|
|
throw refused()
|
|
}
|
|
return Object.freeze({ verify: value.verify.bind(value), close: value.close.bind(value) })
|
|
}
|
|
const timer = setTimeout(stop, Math.max(1, end - performance.now()))
|
|
scope.signal?.addEventListener("abort", stop, { once: true })
|
|
try {
|
|
live()
|
|
for (const open of acquire) {
|
|
live()
|
|
const pending = Promise.resolve().then(() => { live(); return open(scope) }).then(value => {
|
|
// Track before checking time: even a boundary expiry must retire the
|
|
// just-returned physical lease. A stalled acquire can resolve late.
|
|
const child = captureLease(value); leases.push(child)
|
|
if (!active) { try { close() } catch { try { close() } catch { /* Source must also bound its own physical lease. */ } } }
|
|
return child
|
|
})
|
|
await Promise.race([pending, stopped]); live()
|
|
}
|
|
live()
|
|
return Object.freeze({
|
|
async verify(current: Readonly<BandwidthScope>) {
|
|
try {
|
|
const next = captureScope(current)
|
|
if (verifying || next.deadlineAt !== scope.deadlineAt || next.signal !== scope.signal) throw refused()
|
|
live(); verifying = true
|
|
for (const lease of leases) { live(); await Promise.race([lease.verify(scope), stopped]); live() }
|
|
} catch (error) { stop(); throw error }
|
|
finally { verifying = false }
|
|
},
|
|
close,
|
|
})
|
|
} catch (error) { try { close() } catch { /* Every owned child was attempted. */ } throw error }
|
|
} })
|
|
}
|