Files
clean-architecture-frontend…/src/platform/execution/execution-context.ts
T
DongHyeonkaandClaude Opus 5.5 911561985b fix(platform): let an interaction detach from its owner signal on completion (Q-6.9-7)
createExecutionContext forwarded an owner signal's abort and removed
that listener only when the interaction itself aborted. An interaction
that finished normally under a long-lived owner signal left its listener
and AbortController on the owner. ExecutionContext gains complete():
idempotent, detaches from the owner without aborting the interaction.
No caller passes an owner signal today, so this closes a latent leak.

Verified: new test in tests/platform/execution/execution-context.test.ts
(RED before: complete is not a function); all gates pass except the
known tests/unit/removal-fixture.test.ts (artifacts/ absent).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 13:58:35 +09:00

145 lines
4.5 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;
/**
* Q-6.9-7. Ends the interaction normally: it detaches from the owner
* `signal` without aborting its own. Idempotent. Without it, every
* interaction under a long-lived owner signal left one abort listener (and
* its controller) on that owner until the owner itself aborted.
*/
complete(): void;
}
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;
let detachFromParent = () => {};
if (parent) {
if (parent.aborted) controller.abort();
else {
const forward = () => controller.abort();
parent.addEventListener("abort", forward, { once: true });
detachFromParent = () => {
detachFromParent = () => {};
parent.removeEventListener("abort", forward);
};
// The interaction must not keep the parent's listener alive after it ends.
controller.signal.addEventListener("abort", () => detachFromParent(), {
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;
}
},
complete() {
detachFromParent();
},
});
}