Files
clean-architecture-frontend…/src/platform/execution/execution-context.ts
T

132 lines
4.1 KiB
TypeScript

import { remainingDeadlineMs } from "../resilience/deadline.ts";
import type { TraceContext } from "../telemetry/trace-context.ts";
import {
createTrafficRuntime,
type TrafficBudget,
type TrafficRuntime,
} from "../traffic/traffic-budget.ts";
/**
* Spec §10. One root execution context per user/application interaction.
*
* The interaction identity, absolute deadline and traffic policy are immutable.
* The only mutable state is the interaction-local traffic runtime (counters and
* leases) and the cancellation controller, both private to this interaction and
* shared by every child operation it starts.
*/
export type InteractionId = string & { readonly __brand: "InteractionId" };
const INTERACTION_ID = /^[A-Za-z0-9._:-]{1,128}$/u;
export function toInteractionId(value: string): InteractionId {
if (!INTERACTION_ID.test(value)) {
throw new TypeError("interaction id must be 1-128 safe characters");
}
return value as InteractionId;
}
export type TrafficBudgetInput = Omit<TrafficBudget, "maxQueuedRequests"> &
Readonly<{ maxQueuedRequests?: number }>;
export interface ExecutionContext {
readonly interaction: Readonly<{
id: InteractionId;
startedAt: number;
deadlineAt: number;
}>;
readonly cancellation: Readonly<{
signal: AbortSignal;
cancel(): void;
}>;
readonly traffic: TrafficRuntime;
/**
* Spec §29. The interaction trace identity. Present only when the
* interaction opted into propagation; every child request then carries the
* same `traceparent` and correlation id.
*/
readonly trace?: TraceContext;
/** The monotonic clock `startedAt`/`deadlineAt` were measured against. */
readonly clock: () => number;
/** Time left before the absolute interaction deadline; never negative. */
remainingMs(): number;
}
export type ExecutionContextOptions = Readonly<{
interactionId: string;
deadlineMs: number;
traffic: TrafficBudgetInput;
/** Defaults to `clock()`. */
startedAt?: number;
/** Monotonic clock. Defaults to `performance.now`. */
clock?: () => number;
/** An owner signal (route, scope, caller) that also cancels the interaction. */
signal?: AbortSignal;
trace?: TraceContext;
}>;
/** Absolute ceiling for one interaction; matches the HTTP hard total deadline. */
export const MAX_INTERACTION_DEADLINE_MS = 60_000;
export function createExecutionContext(
options: ExecutionContextOptions,
): ExecutionContext {
const clock = options.clock ?? (() => performance.now());
if (
!Number.isSafeInteger(options.deadlineMs) ||
options.deadlineMs < 1 ||
options.deadlineMs > MAX_INTERACTION_DEADLINE_MS
) {
throw new TypeError(
`interaction deadlineMs must be 1..${MAX_INTERACTION_DEADLINE_MS}: ${options.deadlineMs}`,
);
}
const startedAt = options.startedAt ?? clock();
const traffic = createTrafficRuntime({
...options.traffic,
// A bounded default: at most one waiter per concurrent slot.
maxQueuedRequests:
options.traffic.maxQueuedRequests ?? options.traffic.maxConcurrentRequests,
});
const interaction = Object.freeze({
id: toInteractionId(options.interactionId),
startedAt,
deadlineAt: startedAt + options.deadlineMs,
});
const controller = new AbortController();
const parent = options.signal;
if (parent) {
if (parent.aborted) controller.abort();
else {
const forward = () => controller.abort();
parent.addEventListener("abort", forward, { once: true });
// The interaction must not keep the parent's listener alive after it ends.
controller.signal.addEventListener(
"abort",
() => parent.removeEventListener("abort", forward),
{ once: true },
);
}
}
return Object.freeze({
interaction,
cancellation: Object.freeze({
signal: controller.signal,
cancel() {
controller.abort();
},
}),
traffic,
...(options.trace === undefined ? {} : { trace: options.trace }),
clock,
remainingMs() {
try {
return remainingDeadlineMs(interaction.deadlineAt, clock());
} catch {
return 0;
}
},
});
}