392 lines
30 KiB
TypeScript
392 lines
30 KiB
TypeScript
/** Trusted internal execution composition only. No enrollment, default source,
|
|
* production activation or model-supplied transport/authority callbacks. Raw
|
|
* results are for the complete internal workflow, never a public readiness API.
|
|
* The staged native SQL producer retains registry and exact owner locks through
|
|
* the private ClientRequest.finish barrier. Runtime callers remain disabled. */
|
|
import { isDeepStrictEqual } from "node:util"
|
|
import { performance } from "node:perf_hooks"
|
|
import { z } from "zod"
|
|
import { BANDWIDTH_CALLER_KINDS, createBandwidthAdmission, type BandwidthAdmissionInput, type BandwidthBinding, type BandwidthJournal, type BandwidthScope, type BandwidthTransition } from "./bandwidth-admission.js"
|
|
import { createBandwidthAdmissionSqlJournal } from "./bandwidth-admission-storage.js"
|
|
import type { createConfiguredBandwidthControlSource, BandwidthControlDispatchFence } from "./bandwidth-control-source.js"
|
|
import type { createConfiguredBandwidthNodeSource } from "./bandwidth-node-source.js"
|
|
import type { createBandwidthPeerObservationReader, BandwidthPeerObservationEvidence } from "./bandwidth-peer-observation.js"
|
|
import { parseBandwidthPeerRef } from "./bandwidth-peer-reference.js"
|
|
import { createBandwidthPeerResolver } from "./bandwidth-peer-resolver.js"
|
|
import { bandwidthPeerRefKey } from "./bandwidth-peer-reference.js"
|
|
import type { BandwidthPeerRegistryReceipt } from "./bandwidth-peer-fence.js"
|
|
import type { ProbeStorageConnection } from "./server-probe-journal-maintenance.js"
|
|
import { createBandwidthNativeDispatchSqlGate } from "./bandwidth-native-dispatch-source.js"
|
|
import { createBandwidthNativeDispatchCompositeGate } from "./bandwidth-native-dispatch-composite.js"
|
|
import type { BandwidthNativeDispatchLease } from "./bandwidth-native-dispatch.js"
|
|
|
|
type Core = ReturnType<typeof createConfiguredBandwidthControlSource>
|
|
type Nodes = ReturnType<typeof createConfiguredBandwidthNodeSource>
|
|
type Observer = ReturnType<typeof createBandwidthPeerObservationReader>
|
|
type NodeSession = Awaited<ReturnType<Nodes["open"]>>
|
|
type NodeBinding = Awaited<ReturnType<NodeSession["binding"]>>
|
|
const hash = z.string().regex(/^[a-f0-9]{64}$/), label = z.string().regex(/^[a-zA-Z0-9_.:-]{1,200}$/)
|
|
const positive = z.number().int().positive().safe()
|
|
const intentSchema = z.object({ attemptId: z.string().uuid(), operationId: label, callerKind: z.enum(BANDWIDTH_CALLER_KINDS),
|
|
sourceServerId: positive, actualRemotePeer: z.union([z.object({kind:z.literal("server"),serverId:positive}).strict(),z.object({kind:z.literal("external"),enrollmentId:z.string().uuid()}).strict()]).transform(parseBandwidthPeerRef), credentialServerId: positive,
|
|
request: z.record(z.string(), z.unknown()).transform(value => value as BandwidthAdmissionInput["request"]), nativeBody: z.record(z.string(), z.string()),
|
|
durationSec: z.number().int().min(3).max(2147483647), socketTimeoutMs: z.number().int().min(1).max(2147483647),
|
|
authorityProof: hash, authorityGeneration: label, expiresAt: positive }).strict()
|
|
export type BandwidthPeerExecutionIntent = Readonly<z.infer<typeof intentSchema>>
|
|
export interface BandwidthPeerExecutionRemoteEvidence {
|
|
readonly sourceEvidence: Readonly<BandwidthPeerObservationEvidence>
|
|
readonly remoteEvidence: Readonly<BandwidthPeerObservationEvidence>
|
|
readonly sourceReceipt: Readonly<BandwidthPeerRegistryReceipt>
|
|
readonly remoteReceipt: Readonly<BandwidthPeerRegistryReceipt>
|
|
}
|
|
export interface BandwidthPeerExecutionHostDependencies {
|
|
coreSource: Core
|
|
nodeSource: Nodes
|
|
observer: Observer
|
|
/** Fixed server-owned original human/scheduler/MCP context verifier. Every
|
|
* read authenticates exact sealed intent AND current rights to ALL THREE IDs,
|
|
* current source/destination credentials and original nonrenewed expiry. */
|
|
readOriginal(originalContext: unknown, scope: Readonly<BandwidthScope>): Promise<BandwidthPeerExecutionIntent>
|
|
/** Independently authenticate wire address/VRF/zone against the ACTUAL remote
|
|
* canonical receipt. Credential provider identity alone is insufficient. */
|
|
verifyRemote(originalContext: unknown, intent: BandwidthPeerExecutionIntent, evidence: Readonly<BandwidthPeerExecutionRemoteEvidence>, scope: Readonly<BandwidthScope>): Promise<{ proof: string; expiresAt: number }>
|
|
/** Trusted production mapping assembly must hold its actual configuration/
|
|
* path fence, bound to this exact previously authenticated proof, until the
|
|
* private native finish barrier closes it. The optional legacy seam remains
|
|
* for scoped synthetic acceptance; its absence is not production readiness. */
|
|
acquireRemoteFence?(originalContext: unknown, intent: BandwidthPeerExecutionIntent, evidence: Readonly<BandwidthPeerExecutionRemoteEvidence>,
|
|
expected: Readonly<{ proof: string; expiresAt: number }>, scope: Readonly<BandwidthScope>): Promise<Readonly<BandwidthNativeDispatchLease>>
|
|
}
|
|
export class BandwidthPeerExecutionHostError extends Error {
|
|
readonly automaticReplay = false
|
|
constructor(readonly code: "REFUSED" | "OUTCOME_UNKNOWN",readonly phase?:BandwidthPeerExecutionPhase) { super("Bandwidth execution " + code) }
|
|
}
|
|
type BandwidthPeerExecutionPhase="original-context"|"source-observation"|"remote-observation"|"source-resolution"|"remote-resolution"|"remote-policy"|"participant-proof"|"strict-client"|"reserve-arm"|"native-send"|"terminal-proof"|BandwidthTransition
|
|
function refuse(): never { throw new BandwidthPeerExecutionHostError("REFUSED") }
|
|
const executionHosts = new WeakSet<object>()
|
|
const completions = new WeakMap<object, Readonly<{ originalContext: unknown; intent: BandwidthPeerExecutionIntent }>>()
|
|
/** Internal proof of this exact native completion AND durable completion ACK.
|
|
* JSON, copied results and another original cannot authorize post-run work. */
|
|
export function readBandwidthPeerCompletion(value: unknown, originalContext: unknown): Readonly<BandwidthPeerExecutionIntent> {
|
|
const completion = value && typeof value === "object" ? completions.get(value) : undefined
|
|
if (!completion || completion.originalContext !== originalContext) return refuse()
|
|
return completion.intent
|
|
}
|
|
export function assertBandwidthPeerExecutionHost(value: unknown): asserts value is ReturnType<typeof createBandwidthPeerExecutionHost> {
|
|
if (!value || typeof value !== "object" || !executionHosts.has(value)) refuse()
|
|
}
|
|
function freeze<T>(value: T): T {
|
|
if (value && typeof value === "object") { Object.values(value).forEach(freeze); Object.freeze(value) }
|
|
return value
|
|
}
|
|
/** Reject getters, serializers, symbols and non-JSON values before any await. */
|
|
function capture(value: unknown, limit = 1048576): unknown {
|
|
const seen = new Set<object>()
|
|
const walk = (item: unknown, depth: number): unknown => {
|
|
if (depth > 32) refuse()
|
|
if (item === null || typeof item === "string" || typeof item === "boolean") return item
|
|
if (typeof item === "number") { if (!Number.isFinite(item) || Number.isInteger(item) && !Number.isSafeInteger(item)) refuse(); return item }
|
|
if (!item || typeof item !== "object" || seen.has(item)) refuse()
|
|
seen.add(item)
|
|
try {
|
|
if (Array.isArray(item)) {
|
|
const descriptors = Object.getOwnPropertyDescriptors(item)
|
|
if (Reflect.ownKeys(item).length !== item.length + 1 || Object.keys(descriptors).some(key => key !== "length" && (!/^(0|[1-9][0-9]*)$/.test(key) || !("value" in descriptors[key])))) refuse()
|
|
return Array.from({ length: item.length }, (_, index) => walk(descriptors[String(index)].value, depth + 1))
|
|
}
|
|
if (Object.getPrototypeOf(item) !== Object.prototype) refuse()
|
|
const descriptors = Object.getOwnPropertyDescriptors(item)
|
|
if (Reflect.ownKeys(item).length !== Object.keys(descriptors).length || Object.values(descriptors).some(entry => !("value" in entry) || !entry.enumerable)) refuse()
|
|
return Object.fromEntries(Object.entries(descriptors).map(([key, entry]) => [key, walk(entry.value, depth + 1)]))
|
|
} finally { seen.delete(item) }
|
|
}
|
|
const result = walk(value, 0)
|
|
if (Buffer.byteLength(JSON.stringify(result)) > limit) refuse()
|
|
return freeze(result)
|
|
}
|
|
const readIntent = (value: unknown): BandwidthPeerExecutionIntent => {
|
|
const parsed = intentSchema.parse(capture(value))
|
|
if (parsed.nativeBody.duration !== `${parsed.durationSec}s` || !parsed.nativeBody.address?.trim()) refuse()
|
|
return freeze(parsed)
|
|
}
|
|
const nodeSubject=(value:Readonly<BandwidthPeerObservationEvidence>)=>({version:value.version,peerRef:value.peerRef,sourceProof:value.sourceProof,
|
|
authorityGeneration:value.authorityGeneration,routingEndpointEpoch:value.routingEndpointEpoch,claims:value.claims,
|
|
physicalUniquenessVerified:value.physicalUniquenessVerified,cloneResistanceVerified:value.cloneResistanceVerified})
|
|
|
|
export function createBandwidthPeerExecutionHost(dependencies: BandwidthPeerExecutionHostDependencies) {
|
|
// Capture the trusted assembly once; request values never choose providers.
|
|
const readOriginal = dependencies.readOriginal.bind(dependencies), verifyRemote = dependencies.verifyRemote.bind(dependencies)
|
|
const acquireRemoteFence = dependencies.acquireRemoteFence?.bind(dependencies)
|
|
const core = Object.freeze({ connect: dependencies.coreSource.connect.bind(dependencies.coreSource),
|
|
admissionProof: dependencies.coreSource.admissionProof.bind(dependencies.coreSource), eventProof: dependencies.coreSource.eventProofOnConnection.bind(dependencies.coreSource) })
|
|
const nodes = Object.freeze({ open: dependencies.nodeSource.open.bind(dependencies.nodeSource), assertResolvedPeersOnFence: dependencies.nodeSource.assertResolvedPeersOnFence.bind(dependencies.nodeSource) })
|
|
const observer = Object.freeze({ observe: dependencies.observer.observe.bind(dependencies.observer), inspect: dependencies.observer.inspect.bind(dependencies.observer), strictClient: dependencies.observer.strictClient.bind(dependencies.observer) })
|
|
const host = Object.freeze({ async execute(originalContext: unknown, inputScope: BandwidthScope) {
|
|
if (!inputScope || !Number.isSafeInteger(inputScope.deadlineAt) || inputScope.signal !== undefined && !(inputScope.signal instanceof AbortSignal)) refuse()
|
|
const entered = Date.now(), enteredMonotonic=performance.now(), controller = new AbortController()
|
|
let monotonicEnd=enteredMonotonic+Math.max(0,inputScope.deadlineAt-entered),mutationPossible=false
|
|
let phase:BandwidthPeerExecutionPhase="original-context"
|
|
const parentDeadline = inputScope.deadlineAt, parentSignal = inputScope.signal
|
|
let running = true, intent: BandwidthPeerExecutionIntent | undefined, timer: ReturnType<typeof setTimeout> | undefined
|
|
// Separate short preparation cap; clearing it never changes/renews the
|
|
// original monotonic horizon above. Reuse the existing owner timer.
|
|
let remotePhase: Readonly<{ deadlineAt: number; end: number }> | undefined, retireRemote: (() => void) | undefined, stopping = false
|
|
const abort = () => controller.abort()
|
|
parentSignal?.addEventListener("abort", abort, { once: true }); if (parentSignal?.aborted) abort()
|
|
const scope: BandwidthScope = Object.freeze({ deadlineAt: parentDeadline, signal: controller.signal })
|
|
let rejectStopped!: (error: BandwidthPeerExecutionHostError) => void
|
|
const stopped = new Promise<never>((_resolve, reject) => { rejectStopped = reject })
|
|
const stop = () => {
|
|
if (!running || stopping) return; stopping = true
|
|
try { retireRemote?.() } catch { /* Conservative unknown; physical destruction was retried. */ }
|
|
controller.abort(); rejectStopped(new BandwidthPeerExecutionHostError(mutationPossible?"OUTCOME_UNKNOWN":"REFUSED"))
|
|
}
|
|
controller.signal.addEventListener("abort", stop, { once: true })
|
|
const live = (current: BandwidthScope = scope) => {
|
|
if (!running || current.signal?.aborted || controller.signal.aborted || Date.now() >= Math.min(current.deadlineAt, intent?.expiresAt ?? Infinity, remotePhase?.deadlineAt ?? Infinity)
|
|
|| performance.now() >= Math.min(monotonicEnd, remotePhase?.end ?? Infinity)) refuse()
|
|
}
|
|
const schedule = () => {
|
|
clearTimeout(timer)
|
|
const remaining = Math.min(Math.min(parentDeadline, intent?.expiresAt ?? Infinity, remotePhase?.deadlineAt ?? Infinity) - Date.now(),
|
|
Math.min(monotonicEnd, remotePhase?.end ?? Infinity) - performance.now())
|
|
timer = setTimeout(() => { if (remaining > 2147483647) schedule(); else stop() }, Math.max(1, Math.min(2147483647, remaining)))
|
|
}
|
|
schedule()
|
|
const work = async () => {
|
|
live(); intent = readIntent(await readOriginal(originalContext, scope))
|
|
monotonicEnd=Math.min(monotonicEnd,enteredMonotonic+Math.max(0,intent.expiresAt-entered))
|
|
live(); schedule()
|
|
const original = intent, executeScope = Object.freeze({ deadlineAt: Math.min(parentDeadline, original.expiresAt), signal: controller.signal })
|
|
const actor = async (current: BandwidthScope) => { live(current); const fresh = readIntent(await readOriginal(originalContext, current)); live(current); if (!isDeepStrictEqual(fresh, original)) refuse() }
|
|
await actor(executeScope)
|
|
phase="source-observation";let sourceToken = await observer.observe({kind:"server",serverId:original.sourceServerId}, executeScope); live()
|
|
phase="remote-observation";let remoteToken = await observer.observe(original.actualRemotePeer, executeScope); live()
|
|
let sourceEvidence = freeze(await observer.inspect(sourceToken, executeScope)), remoteEvidence = freeze(await observer.inspect(remoteToken, executeScope))
|
|
const originalSourceSubject=freeze(structuredClone(nodeSubject(sourceEvidence))),originalRemoteSubject=freeze(structuredClone(nodeSubject(remoteEvidence)))
|
|
let preScope = Object.freeze({ deadlineAt: Math.min(executeScope.deadlineAt, sourceEvidence.expiresAt, remoteEvidence.expiresAt), signal: controller.signal })
|
|
// Each short phase obtains NEW real observations of the SAME original
|
|
// approved subjects. Expired capabilities are never inspected/adopted;
|
|
// actor/peer expiry, credentials, epochs and claims cannot be renewed.
|
|
// Call only between transitions, with no journal/registry lease held.
|
|
const observePhase=async()=>{
|
|
await actor(executeScope)
|
|
const tokens=await Promise.all([observer.observe({kind:"server",serverId:original.sourceServerId},executeScope),observer.observe(original.actualRemotePeer,executeScope)])
|
|
const evidence=await Promise.all(tokens.map(token=>observer.inspect(token,executeScope)))
|
|
if(!isDeepStrictEqual(nodeSubject(evidence[0]),originalSourceSubject)||!isDeepStrictEqual(nodeSubject(evidence[1]),originalRemoteSubject))refuse()
|
|
live()
|
|
sourceToken=tokens[0];remoteToken=tokens[1];sourceEvidence=freeze(evidence[0]);remoteEvidence=freeze(evidence[1])
|
|
preScope=Object.freeze({deadlineAt:Math.min(executeScope.deadlineAt,sourceEvidence.expiresAt,remoteEvidence.expiresAt),signal:controller.signal})
|
|
await actor(preScope)
|
|
}
|
|
const nativeFresh = async (current: BandwidthScope) => {
|
|
live(current)
|
|
if (!isDeepStrictEqual(await observer.inspect(sourceToken, current), sourceEvidence) || !isDeepStrictEqual(await observer.inspect(remoteToken, current), remoteEvidence)) refuse()
|
|
live(current)
|
|
}
|
|
const originalGuard = async () => { await nativeFresh(preScope); await actor(preScope) }
|
|
let pin: NodeBinding | undefined
|
|
const resolve = async (token: unknown, evidence: Readonly<BandwidthPeerObservationEvidence>) => {
|
|
await originalGuard(); const session = await nodes.open(preScope, originalGuard)
|
|
try {
|
|
const binding = freeze(await session.binding()); if (pin && !isDeepStrictEqual(pin, binding)) refuse(); pin ??= binding
|
|
const resolver = createBandwidthPeerResolver({connect:async()=>session.connection,
|
|
inspect:(value,current)=>observer.inspect(value,current),keyedProof:(purpose,value)=>session.keyedProof(purpose,value),
|
|
keyedProofs:session.keyedProofs?.bind(session),
|
|
authorize:async(peer,current,genuine)=>{
|
|
if(bandwidthPeerRefKey(peer)!==bandwidthPeerRefKey(evidence.peerRef)||!isDeepStrictEqual(genuine,evidence))refuse()
|
|
if(!isDeepStrictEqual(await session.binding(),pin))refuse()
|
|
await nativeFresh(current);await actor(current)
|
|
return {installationId:binding.installationId,issuerKeySha256:binding.issuerKeySha256,quiescenceProof:binding.quiescenceProof,
|
|
authorityProof:original.authorityProof,authorityGeneration:original.authorityGeneration,expiresAt:original.expiresAt}
|
|
}})
|
|
const receipt = freeze(await resolver.resolve(token,preScope))
|
|
return receipt
|
|
} finally { session.close() }
|
|
}
|
|
phase="source-resolution";const sourceReceipt = await resolve(sourceToken, sourceEvidence)
|
|
await observePhase()
|
|
phase="remote-resolution";const remoteReceipt = await resolve(remoteToken, remoteEvidence)
|
|
if (!pin || sourceReceipt.canonicalNodeId === remoteReceipt.canonicalNodeId) refuse()
|
|
const originalPin = pin
|
|
const participants = ()=>freeze({ sourceEvidence, remoteEvidence, sourceReceipt, remoteReceipt })
|
|
const remoteSchema = z.object({ proof: hash, expiresAt: positive }).strict()
|
|
await observePhase()
|
|
phase="remote-policy";const peer = freeze(remoteSchema.parse(capture(await verifyRemote(originalContext, original, participants(), preScope))))
|
|
if (peer.expiresAt <= Date.now()) refuse()
|
|
const peerMonotonicEnd=enteredMonotonic+Math.max(0,peer.expiresAt-entered)
|
|
const beforeDispatch = async () => {
|
|
await nativeFresh(preScope)
|
|
const currentPeer = remoteSchema.parse(capture(await verifyRemote(originalContext, original, participants(), preScope)))
|
|
if (!isDeepStrictEqual(currentPeer, peer) || Date.now() >= peer.expiresAt || performance.now()>=peerMonotonicEnd) refuse()
|
|
await actor(preScope)
|
|
}
|
|
type PreparedRemote = Readonly<{ verify(): Promise<void>; close(): void }>
|
|
let preparedRemote: PreparedRemote | undefined
|
|
const prepareRemote = async (current: Readonly<BandwidthScope>): Promise<PreparedRemote | undefined> => {
|
|
if (!acquireRemoteFence) return undefined
|
|
if (preparedRemote || remotePhase || retireRemote) refuse()
|
|
live(current)
|
|
const wall = Date.now(), mono = performance.now()
|
|
const originalScope = Object.freeze({ deadlineAt: Math.min(current.deadlineAt, peer.expiresAt, wall + 5000), signal: current.signal })
|
|
const cap = Object.freeze({ deadlineAt: originalScope.deadlineAt, end: Math.min(monotonicEnd, peerMonotonicEnd, mono + Math.max(0, originalScope.deadlineAt - wall)) })
|
|
remotePhase = cap; schedule()
|
|
let active = true, pending = true, physicallyClosed = false, closeFailed = false
|
|
let owned: Readonly<BandwidthNativeDispatchLease> | undefined
|
|
const close = () => {
|
|
active = false
|
|
if (physicallyClosed) { if (closeFailed) refuse(); return }
|
|
if (!owned && pending) return // Late acquire must still be captured/destroyed.
|
|
let failure = false
|
|
if (owned) {
|
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
try { owned.close(); physicallyClosed = true; break } catch { failure = true }
|
|
}
|
|
} else physicallyClosed = true
|
|
if (failure || !physicallyClosed) { closeFailed = true; refuse() }
|
|
if (remotePhase === cap) remotePhase = undefined
|
|
if (retireRemote === close) retireRemote = undefined
|
|
if (running && !stopping && !controller.signal.aborted) schedule()
|
|
}
|
|
retireRemote = close
|
|
const verify = async () => {
|
|
if (!active || !owned || physicallyClosed || remotePhase !== cap) refuse()
|
|
live(originalScope)
|
|
// Actual producer receives the EXACT preparation scope it acquired;
|
|
// the private kernel/composite's later scope cannot renew this lease.
|
|
await owned.verify(originalScope); live(originalScope)
|
|
await actor(originalScope); live(originalScope)
|
|
}
|
|
try {
|
|
const acquired = await acquireRemoteFence(originalContext, original, participants(), peer, originalScope)
|
|
pending = false
|
|
if (!acquired || typeof acquired.verify !== "function" || typeof acquired.close !== "function") {
|
|
try { acquired?.close?.() } catch { try { acquired?.close?.() } catch { /* Never return a malformed/late lease healthy. */ } }
|
|
refuse()
|
|
}
|
|
owned = Object.freeze({ verify: acquired.verify.bind(acquired), close: acquired.close.bind(acquired) })
|
|
if (!active) { close(); refuse() }
|
|
await verify(); await beforeDispatch(); live(originalScope)
|
|
return Object.freeze({ verify, close })
|
|
} catch (error) { pending = false; try { close() } catch { /* Conservative refusal/unknown; no post. */ } throw error }
|
|
}
|
|
const identityMatches = (value: { installationId: string; controlGeneration: string; sourceRecordSha256: string }) => {
|
|
if (value.installationId !== originalPin.installationId || value.controlGeneration !== originalPin.controlGeneration || value.sourceRecordSha256 !== originalPin.sourceRecordSha256) refuse()
|
|
}
|
|
const aliasFence = (fence: BandwidthControlDispatchFence, current: BandwidthScope) => nodes.assertResolvedPeersOnFence(fence, {
|
|
binding: originalPin, participants: [{ evidence: sourceEvidence, receipt: sourceReceipt }, { evidence: remoteEvidence, receipt: remoteReceipt }],
|
|
}, current)
|
|
const dispatchGuard = (current: BandwidthScope, execute: boolean) => async (fence: BandwidthControlDispatchFence) => {
|
|
identityMatches(await fence.sourceIdentity())
|
|
if (execute) { await aliasFence(fence, current); await beforeDispatch() }
|
|
}
|
|
const endpointProof = async (receipt: BandwidthPeerRegistryReceipt, evidence: BandwidthPeerObservationEvidence) => core.admissionProof("bandwidth-endpoint-v1", { receipt, subject:nodeSubject(evidence), peer, sourceRecordSha256: originalPin.sourceRecordSha256 }, originalPin.sourceRecordSha256, preScope)
|
|
phase="participant-proof";const source = { canonicalNodeId: sourceReceipt.canonicalNodeId, endpointProof: await endpointProof(sourceReceipt, sourceEvidence) }
|
|
const destination = { canonicalNodeId: remoteReceipt.canonicalNodeId, endpointProof: await endpointProof(remoteReceipt, remoteEvidence) }
|
|
phase="strict-client";const client = await observer.strictClient(sourceToken, preScope); await beforeDispatch()
|
|
let activeJournal: { connection: ProbeStorageConnection; scope: BandwidthScope } | undefined
|
|
let originalBinding: Readonly<BandwidthBinding> | undefined, sendInvocations = 0, terminal: { bindingProof: string; proof: string } | undefined
|
|
let transition: BandwidthTransition | undefined
|
|
const own = (binding: Readonly<BandwidthBinding>) => {
|
|
if (originalBinding && !isDeepStrictEqual(originalBinding, binding)) refuse()
|
|
originalBinding ??= freeze(structuredClone(binding))
|
|
}
|
|
const baseJournal = createBandwidthAdmissionSqlJournal({ now: Date.now,
|
|
connect: async current => {
|
|
if (activeJournal) refuse()
|
|
const connection = await core.connect(current, dispatchGuard(current, transition === "reserve" || transition === "arm"))
|
|
activeJournal = { connection, scope: current }
|
|
return { query: (text, values, options) => connection.query(text, values, options), release(unsafe) { activeJournal = undefined; connection.release(unsafe) } }
|
|
},
|
|
authorize: async (binding, current, transition) => { own(binding); if (transition === "reserve" || transition === "arm") await beforeDispatch(); else if (current.signal?.aborted || Date.now() >= current.deadlineAt) refuse() },
|
|
verifyEvidence: async (transition, binding, evidence) => {
|
|
own(binding)
|
|
if (transition === "complete") { if (!terminal || terminal.bindingProof !== binding.bindingProof || !isDeepStrictEqual(evidence, { terminalProof: terminal.proof })) refuse() }
|
|
else if (transition === "release-before-dispatch") { if (sendInvocations !== 0 || !evidence || !["reserved", "armed"].includes((evidence as { from: string }).from) || (evidence as { proof: string }).proof !== "private-no-send") refuse() }
|
|
else if (evidence !== undefined) refuse()
|
|
},
|
|
eventProof: async event => { const current = activeJournal; if (!current) refuse(); return core.eventProof(event, current.connection, current.scope) },
|
|
})
|
|
// Track the transition explicitly: cleanup scopes intentionally do NOT
|
|
// inherit expired execute/native-observation authority or cancellation.
|
|
const inTransition = async <T>(kind: BandwidthTransition, work: () => Promise<T>) => {
|
|
if (transition) refuse(); transition = kind;phase=kind
|
|
try { return await work() } finally { transition = undefined }
|
|
}
|
|
const journal: BandwidthJournal = Object.freeze<BandwidthJournal>({
|
|
reserve: async(binding, current) => {await observePhase();mutationPossible=true;return inTransition("reserve", () => baseJournal.reserve(binding, current))},
|
|
arm: async(binding, current) => {await observePhase();return inTransition("arm", () => baseJournal.arm(binding, current))},
|
|
complete: (binding, evidence, current) => inTransition("complete", () => baseJournal.complete(binding, evidence, current)),
|
|
releaseBeforeDispatch: (binding, evidence, current) => inTransition("release-before-dispatch", () => baseJournal.releaseBeforeDispatch(binding, evidence, current)),
|
|
quarantine: (binding, current) => inTransition("quarantine", () => baseJournal.quarantine(binding, current)),
|
|
})
|
|
const admissionInput: BandwidthAdmissionInput = { attemptId: original.attemptId, callerKind: original.callerKind, operationId: original.operationId,
|
|
request: { originalRequest: original.request, context: { sourceServerId: original.sourceServerId, actualRemotePeer: original.actualRemotePeer, credentialServerId: original.credentialServerId,
|
|
socketTimeoutMs: original.socketTimeoutMs, peerProof: peer.proof } }, source, destination, authorityProof: original.authorityProof,
|
|
authorityGeneration: original.authorityGeneration, controlGeneration: originalPin.controlGeneration, expiresAt: original.expiresAt, durationSec: original.durationSec, nativeBody: original.nativeBody }
|
|
const admission = createBandwidthAdmission(admissionInput, { now: Date.now, cleanupBudgetMs: 10000, nativeClient: client, journal,
|
|
nativeDispatchGate: Object.freeze({ acquire: async (current: Readonly<BandwidthScope>) => {
|
|
// Refresh observations before taking the short SQL lease. The gate
|
|
// cannot renew the original actor/peer proof, binding or source pin.
|
|
await observePhase()
|
|
if (!originalBinding) refuse()
|
|
const gate = createBandwidthNativeDispatchSqlGate({ connect: core.connect, eventProofOnConnection: core.eventProof }, originalBinding,
|
|
async (fence, ownedScope) => { identityMatches(await fence.sourceIdentity()); await aliasFence(fence, ownedScope); await beforeDispatch(); live(ownedScope) })
|
|
if (!acquireRemoteFence) return gate.acquire(current)
|
|
const prepared = preparedRemote
|
|
if (!prepared) refuse()
|
|
// Mapping S was prepared BEFORE client.post acquired managed-server
|
|
// locks. This gate BORROWS it; it must never acquire another mapping
|
|
// lease under those locks. The kernel still owns its own exact scope.
|
|
return createBandwidthNativeDispatchCompositeGate([
|
|
{ acquire: async borrowedScope => {
|
|
live(borrowedScope); await prepared.verify(); live(borrowedScope)
|
|
return Object.freeze({
|
|
async verify(next: Readonly<BandwidthScope>) {
|
|
if (next.deadlineAt !== borrowedScope.deadlineAt || next.signal !== borrowedScope.signal) refuse()
|
|
live(next); await prepared.verify(); live(next)
|
|
},
|
|
close: prepared.close,
|
|
})
|
|
} }, gate,
|
|
]).acquire(current)
|
|
} }),
|
|
authorize: async (_binding, current) => { await beforeDispatch(); live(current); return { authorityProof: original.authorityProof, authorityGeneration: original.authorityGeneration, controlGeneration: originalPin.controlGeneration, expiresAt: original.expiresAt } },
|
|
endpoints: async () => { await beforeDispatch(); return { source, destination } },
|
|
keyedProof: async (purpose, value) => {
|
|
const current = purpose === "bandwidth-terminal-v1" ? { deadlineAt: Date.now() + 10000 } : preScope
|
|
const proof = await core.admissionProof(purpose, value, originalPin.sourceRecordSha256, current)
|
|
if (purpose === "bandwidth-terminal-v1") { phase="terminal-proof";if (!originalBinding) refuse(); terminal = { bindingProof: originalBinding.bindingProof, proof } }
|
|
return proof
|
|
},
|
|
send: async (_binding, body, current, permit) => {
|
|
// A send invocation is already potentially ambiguous. No later
|
|
// transport exception can fabricate private no-send evidence.
|
|
sendInvocations++
|
|
phase="native-send"
|
|
try {
|
|
preparedRemote = await prepareRemote(current)
|
|
live(current)
|
|
return await client.post("/tool/bandwidth-test", { ...body }, original.socketTimeoutMs, current.signal, undefined, permit)
|
|
} finally {
|
|
try { preparedRemote?.close() } finally { preparedRemote = undefined }
|
|
}
|
|
} })
|
|
phase="reserve-arm";const capability=await admission.reserveAndArm(executeScope)
|
|
try{await observePhase()}catch(error){await admission.cancel(capability);throw error}
|
|
const result = freeze(await admission.dispatch(capability))
|
|
completions.set(result, Object.freeze({ originalContext, intent: original }))
|
|
return result
|
|
}
|
|
try { return await Promise.race([work(), stopped]) }
|
|
catch { throw new BandwidthPeerExecutionHostError(mutationPossible?"OUTCOME_UNKNOWN":"REFUSED",phase) }
|
|
finally {
|
|
running = false; clearTimeout(timer)
|
|
try { retireRemote?.() } catch { /* Already unknown; never return a failed physical close healthy. */ }
|
|
parentSignal?.removeEventListener("abort", abort); controller.signal.removeEventListener("abort", stop); controller.abort()
|
|
}
|
|
} })
|
|
executionHosts.add(host); return host
|
|
}
|
|
|