refactor: 도메인이 100개 1000개씩 늘어나도 유지보수 쉬운 구조로 변경

This commit is contained in:
donghyeon-ka
2026-09-24 00:42:21 +09:00
parent 91ae42a2a7
commit 6f6c48ebb7
1274 changed files with 290812 additions and 0 deletions
@@ -0,0 +1,29 @@
export class CardinalityBudgetExceededError extends RangeError {
readonly scope: string;
readonly actual: number;
readonly maximum: number;
constructor(scope: string, actual: number, maximum: number) {
super(`${scope} cardinality ${actual} exceeds budget ${maximum}`);
this.name = "CardinalityBudgetExceededError";
this.scope = scope;
this.actual = actual;
this.maximum = maximum;
}
}
export function assertWithinCardinalityBudget(
scope: string,
actual: number,
maximum: number,
): void {
if (!Number.isSafeInteger(actual) || actual < 0) {
throw new TypeError(`Invalid cardinality for ${scope}: ${actual}`);
}
if (!Number.isSafeInteger(maximum) || maximum < 0) {
throw new TypeError(`Invalid cardinality budget for ${scope}: ${maximum}`);
}
if (actual > maximum) {
throw new CardinalityBudgetExceededError(scope, actual, maximum);
}
}
@@ -0,0 +1,23 @@
type UnionToIntersection<Union> = (
Union extends unknown ? (value: Union) => void : never
) extends (value: infer Intersection) => void
? Intersection
: never;
type ComposedRecord<Records extends readonly Readonly<Record<string, unknown>>[]> =
Readonly<UnionToIntersection<Records[number]>>;
export function composeUniqueRecord<
const Records extends readonly Readonly<Record<string, unknown>>[],
>(records: Records, describeScope: () => string): ComposedRecord<Records> {
const result: Record<string, unknown> = {};
for (const record of records) {
for (const [key, value] of Object.entries(record)) {
if (Object.hasOwn(result, key)) {
throw new TypeError(`Duplicate ${describeScope()} key: ${key}`);
}
result[key] = value;
}
}
return Object.freeze(result) as ComposedRecord<Records>;
}
@@ -0,0 +1,87 @@
/**
* Spec §36 / §39 / §49. Growth-shape regression detector.
*
* This is a regression detector, not a Big-O proof. It estimates the local
* growth exponent between consecutive measurements on a log-log scale
* (cost ~ n^k) and fails when any segment grows faster than `maxExponent`.
* A quadratic implementation (k ~ 2) therefore fails even while its absolute
* times are still small, and a linear one (k ~ 1) passes even when absolute
* times are large.
*
* Costs below `noiseFloor` are clamped to it, so scheduler noise on tiny
* measurements cannot fabricate a steep segment; a real super-linear cost
* still shows up in the segments measured above the floor.
*/
export type GrowthSample = Readonly<{ n: number; cost: number }>;
export type GrowthOptions = Readonly<{
/** Largest tolerated per-segment exponent. Default 1.5 (between n and n^2). */
maxExponent?: number;
/** Measurements below this cost are treated as this cost. Default 0. */
noiseFloor?: number;
}>;
export class GrowthRegressionError extends Error {
readonly exponent: number;
readonly from: GrowthSample;
readonly to: GrowthSample;
constructor(exponent: number, from: GrowthSample, to: GrowthSample) {
super(
`super-linear growth: exponent ${exponent.toFixed(2)} between n=${from.n} (cost ${from.cost}) and n=${to.n} (cost ${to.cost})`,
);
this.name = "GrowthRegressionError";
this.exponent = exponent;
this.from = from;
this.to = to;
}
}
export function growthExponents(
samples: readonly GrowthSample[],
noiseFloor = 0,
): readonly number[] {
const sorted = [...samples].sort((left, right) => left.n - right.n);
const exponents: number[] = [];
for (let index = 1; index < sorted.length; index += 1) {
const from = sorted[index - 1] as GrowthSample;
const to = sorted[index] as GrowthSample;
const fromCost = Math.max(from.cost, noiseFloor, Number.MIN_VALUE);
const toCost = Math.max(to.cost, noiseFloor, Number.MIN_VALUE);
exponents.push(Math.log(toCost / fromCost) / Math.log(to.n / from.n));
}
return exponents;
}
export function assertLinearOrBetter(
samples: readonly GrowthSample[],
options: GrowthOptions = {},
): void {
const maxExponent = options.maxExponent ?? 1.5;
const noiseFloor = options.noiseFloor ?? 0;
if (samples.length < 2) {
throw new TypeError("growth check needs at least two measurements");
}
for (const sample of samples) {
if (!Number.isFinite(sample.n) || sample.n <= 0) {
throw new TypeError(`growth sample n must be positive: ${sample.n}`);
}
if (!Number.isFinite(sample.cost) || sample.cost < 0) {
throw new TypeError(`growth sample cost must be finite: ${sample.cost}`);
}
}
const sorted = [...samples].sort((left, right) => left.n - right.n);
if (new Set(sorted.map((sample) => sample.n)).size !== sorted.length) {
throw new TypeError("growth samples need distinct n values");
}
const exponents = growthExponents(sorted, noiseFloor);
exponents.forEach((exponent, index) => {
if (exponent > maxExponent) {
throw new GrowthRegressionError(
exponent,
sorted[index] as GrowthSample,
sorted[index + 1] as GrowthSample,
);
}
});
}
@@ -0,0 +1,71 @@
export type TopologyCapacityInput = Readonly<{
featureCount: number;
maxFeaturesPerContext: number;
maxContextsPerApp: number;
}>;
export type TopologyCapacityPlan = Readonly<{
featureCount: number;
contextCount: number;
appCount: number;
maxFeaturesInAnyContext: number;
maxContextsInAnyApp: number;
totalFeatureCapacity: number;
}>;
function assertSafeCount(name: string, value: number, allowZero: boolean): void {
const minimum = allowZero ? 0 : 1;
if (!Number.isSafeInteger(value) || value < minimum) {
throw new TypeError(`${name} must be a safe integer >= ${minimum}: ${value}`);
}
}
function multiplySafe(name: string, left: number, right: number): number {
if (left !== 0 && right > Number.MAX_SAFE_INTEGER / left) {
throw new RangeError(`${name} exceeds Number.MAX_SAFE_INTEGER`);
}
return left * right;
}
/**
* Computes the minimum hierarchy needed to keep direct-child cardinality
* bounded. It deliberately works from counts instead of materializing every
* feature descriptor, so million-feature CI fixtures do not become memory
* benchmarks themselves.
*/
export function planTopologyCapacity(
input: TopologyCapacityInput,
): TopologyCapacityPlan {
assertSafeCount("featureCount", input.featureCount, true);
assertSafeCount("maxFeaturesPerContext", input.maxFeaturesPerContext, false);
assertSafeCount("maxContextsPerApp", input.maxContextsPerApp, false);
const contextCount = Math.ceil(
input.featureCount / input.maxFeaturesPerContext,
);
const appCount =
contextCount === 0 ? 1 : Math.ceil(contextCount / input.maxContextsPerApp);
const capacityPerApp = multiplySafe(
"capacityPerApp",
input.maxFeaturesPerContext,
input.maxContextsPerApp,
);
const totalFeatureCapacity = multiplySafe(
"totalFeatureCapacity",
appCount,
capacityPerApp,
);
return Object.freeze({
featureCount: input.featureCount,
contextCount,
appCount,
maxFeaturesInAnyContext:
input.featureCount === 0
? 0
: Math.min(input.featureCount, input.maxFeaturesPerContext),
maxContextsInAnyApp:
contextCount === 0 ? 0 : Math.min(contextCount, input.maxContextsPerApp),
totalFeatureCapacity,
});
}
+83
View File
@@ -0,0 +1,83 @@
/**
* Spec §17–§18. The platform error envelope.
*
* The platform owns only the generic shape and its closed classification
* axes. Concrete `kind` literals belong to the feature (or platform module)
* that raises them; there is deliberately no union enumerating every feature
* error, so a new feature never edits a central error type.
*/
export type ErrorCategory =
| "transport"
| "contract"
| "validation"
| "domain"
| "application"
| "platform";
export type ErrorSeverity = "info" | "warning" | "error" | "critical";
export type Retryability = "never" | "safe" | "policy";
export interface AppError {
/** Stable machine-readable `owner.reason` kind, e.g. `payment.declined`. */
readonly kind: string;
readonly category: ErrorCategory;
readonly severity: ErrorSeverity;
readonly retryability: Retryability;
}
export const ERROR_CATEGORIES: ReadonlySet<ErrorCategory> = new Set([
"transport",
"contract",
"validation",
"domain",
"application",
"platform",
]);
export const ERROR_SEVERITIES: ReadonlySet<ErrorSeverity> = new Set([
"info",
"warning",
"error",
"critical",
]);
const RETRYABILITIES: ReadonlySet<Retryability> = new Set([
"never",
"safe",
"policy",
]);
/** Bounded, low-cardinality `owner.reason` identifier. */
const ERROR_KIND = /^[a-z][a-z0-9-]{0,39}(?:\.[a-z][a-z0-9-]{0,39}){1,3}$/u;
export function isErrorKind(value: unknown): value is string {
return typeof value === "string" && ERROR_KIND.test(value);
}
/**
* Structural recognition only: reads four own data fields and never invokes
* accessors, so an untrusted object cannot run code while being classified.
*/
export function isAppError(value: unknown): value is AppError {
if (value === null || typeof value !== "object") return false;
const read = (key: string): unknown => {
const descriptor = Object.getOwnPropertyDescriptor(value, key);
return descriptor && "value" in descriptor ? descriptor.value : undefined;
};
return (
isErrorKind(read("kind")) &&
ERROR_CATEGORIES.has(read("category") as ErrorCategory) &&
ERROR_SEVERITIES.has(read("severity") as ErrorSeverity) &&
RETRYABILITIES.has(read("retryability") as Retryability)
);
}
export function defineAppError<const Envelope extends AppError>(
error: Envelope,
): Readonly<Envelope> {
if (!isAppError(error)) {
throw new TypeError("Invalid AppError envelope");
}
return Object.freeze({ ...error });
}
@@ -0,0 +1,33 @@
import type { ReactNode } from "react";
import {
ScopedErrorBoundary,
type ScopedErrorBoundaryProps,
} from "./scoped-error-boundary.tsx";
/**
* Spec §30. Contains a bounded context's render failure so the app shell and
* every other context keep working. It is the escalation target for a feature
* failure that its own feature boundary did not contain.
*/
export function ContextErrorBoundary(
props: Readonly<{
contextId?: string;
children: ReactNode;
fallback?: ReactNode;
resetKey?: string;
onError?: ScopedErrorBoundaryProps["onError"];
}>,
) {
return (
<ScopedErrorBoundary
scope="context"
ownerId={props.contextId ?? "context"}
{...(props.fallback === undefined ? {} : { fallback: props.fallback })}
{...(props.resetKey === undefined ? {} : { resetKey: props.resetKey })}
{...(props.onError === undefined ? {} : { onError: props.onError })}
>
{props.children}
</ScopedErrorBoundary>
);
}
@@ -0,0 +1,32 @@
import type { ReactNode } from "react";
import {
ScopedErrorBoundary,
type ScopedErrorBoundaryProps,
} from "./scoped-error-boundary.tsx";
/**
* Spec §30. Contains a feature-local render failure inside the feature's own
* subtree. The enclosing context boundary is the next escalation.
*/
export function FeatureErrorBoundary(
props: Readonly<{
featureId: string;
children: ReactNode;
fallback?: ReactNode;
resetKey?: string;
onError?: ScopedErrorBoundaryProps["onError"];
}>,
) {
return (
<ScopedErrorBoundary
scope="feature"
ownerId={props.featureId}
{...(props.fallback === undefined ? {} : { fallback: props.fallback })}
{...(props.resetKey === undefined ? {} : { resetKey: props.resetKey })}
{...(props.onError === undefined ? {} : { onError: props.onError })}
>
{props.children}
</ScopedErrorBoundary>
);
}
+90
View File
@@ -0,0 +1,90 @@
import { defineAppError, type AppError } from "./app-error.ts";
/**
* Spec §17. Stable machine-readable platform error kinds for failures that no
* feature owns: the network, the deadline, cancellation, response bounds and
* the interaction traffic budget.
*/
export const PLATFORM_ERRORS = Object.freeze({
NETWORK_UNAVAILABLE: defineAppError({
kind: "network.unavailable",
category: "transport",
severity: "warning",
retryability: "policy",
}),
REQUEST_TIMEOUT: defineAppError({
kind: "request.timeout",
category: "transport",
severity: "warning",
retryability: "policy",
}),
REQUEST_CANCELLED: defineAppError({
kind: "request.cancelled",
category: "transport",
severity: "info",
retryability: "never",
}),
RESPONSE_TOO_LARGE: defineAppError({
kind: "response.too-large",
category: "contract",
severity: "error",
retryability: "never",
}),
RESPONSE_INVALID: defineAppError({
kind: "response.invalid",
category: "contract",
severity: "error",
retryability: "never",
}),
TRAFFIC_BUDGET_EXCEEDED: defineAppError({
kind: "traffic.budget-exceeded",
category: "platform",
severity: "warning",
retryability: "never",
}),
});
export type PlatformError =
(typeof PLATFORM_ERRORS)[keyof typeof PLATFORM_ERRORS];
export type PlatformErrorKind = PlatformError["kind"];
function errorName(error: unknown): string | undefined {
if (error === null || typeof error !== "object") return undefined;
const descriptor = Object.getOwnPropertyDescriptor(error, "name");
if (descriptor && "value" in descriptor) {
return typeof descriptor.value === "string" ? descriptor.value : undefined;
}
// `name` normally lives on the prototype of Error subclasses.
return error instanceof Error ? error.name : undefined;
}
/**
* Maps a raw failure thrown by a transport (fetch, a lease wait, a budget
* check) to a platform error. An abort is a timeout only when the caller
* states that the deadline, not an owner, caused it.
*/
export function mapTransportFailure(
error: unknown,
context: Readonly<{ deadlineExpired: boolean }>,
): AppError {
const name = errorName(error);
if (name === "AbortError" || name === "TimeoutError") {
return context.deadlineExpired || name === "TimeoutError"
? PLATFORM_ERRORS.REQUEST_TIMEOUT
: PLATFORM_ERRORS.REQUEST_CANCELLED;
}
if (name === "DeadlineExceededError") return PLATFORM_ERRORS.REQUEST_TIMEOUT;
if (
name === "RequestBudgetExceededError" ||
name === "ConcurrencyQueueFullError" ||
name === "RequestFanoutExceededError"
) {
return PLATFORM_ERRORS.TRAFFIC_BUDGET_EXCEEDED;
}
if (name === "JsonBudgetExceededError") {
return PLATFORM_ERRORS.RESPONSE_TOO_LARGE;
}
if (name === "SyntaxError") return PLATFORM_ERRORS.RESPONSE_INVALID;
return PLATFORM_ERRORS.NETWORK_UNAVAILABLE;
}
@@ -0,0 +1,63 @@
import { Component, type ReactNode } from "react";
/**
* Spec §30. Render-failure containment aligned with ownership boundaries.
*
* A boundary exists per owner scope (context, feature), never per leaf
* component. A caught failure replaces only the owning scope with its fallback;
* siblings outside the scope keep rendering. Reporting is best-effort and can
* never recurse into another render failure.
*/
export type ErrorBoundaryScope = "context" | "feature";
export type ScopedErrorBoundaryProps = Readonly<{
scope: ErrorBoundaryScope;
ownerId: string;
children: ReactNode;
fallback?: ReactNode;
/** Changing the key clears a caught failure (e.g. on navigation). */
resetKey?: string;
onError?: (report: Readonly<{ scope: ErrorBoundaryScope; ownerId: string }>) => void;
}>;
type ScopedErrorBoundaryState = Readonly<{ failed: boolean }>;
export class ScopedErrorBoundary extends Component<
ScopedErrorBoundaryProps,
ScopedErrorBoundaryState
> {
state: ScopedErrorBoundaryState = { failed: false };
static getDerivedStateFromError(): ScopedErrorBoundaryState {
return { failed: true };
}
componentDidCatch(): void {
try {
this.props.onError?.(
Object.freeze({ scope: this.props.scope, ownerId: this.props.ownerId }),
);
} catch {
// Observability is outside the render authority.
}
}
componentDidUpdate(previous: Readonly<ScopedErrorBoundaryProps>): void {
if (this.state.failed && previous.resetKey !== this.props.resetKey) {
this.setState({ failed: false });
}
}
render(): ReactNode {
if (!this.state.failed) return this.props.children;
return (
<div
role="alert"
data-boundary={this.props.scope}
data-testid={`${this.props.scope}-fallback-${this.props.ownerId}`}
>
{this.props.fallback ?? null}
</div>
);
}
}
+131
View File
@@ -0,0 +1,131 @@
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;
}
},
});
}
+104
View File
@@ -0,0 +1,104 @@
/**
* Spec §45–§46. One pure, fail-closed release-coherence validator.
*
* Horizontally scaled stateless replicas are safe without sticky sessions only
* when every boot observes one coherent release tuple: the HTML/JS build, the
* runtime config and the release manifest. Every boot-critical identity field
* that two sources both carry must agree; a single disagreement is a release
* mismatch and there is no partial-success state.
*/
export type ReleaseIdentity = Readonly<{
buildId?: string;
releaseId?: string;
configSchemaVersion?: string;
assetManifestHash?: string;
}>;
export type ReleaseIdentityField = keyof ReleaseIdentity;
export type ReleaseIdentitySource = "html" | "config" | "manifest";
/** The precedence the boot loaders have always reported mismatches in. */
export const RELEASE_IDENTITY_FIELDS: readonly ReleaseIdentityField[] = Object.freeze([
"buildId",
"configSchemaVersion",
"releaseId",
"assetManifestHash",
]);
export type ReleaseCoherenceResult =
| Readonly<{ coherent: true }>
| Readonly<{
coherent: false;
field: ReleaseIdentityField;
sources: readonly [ReleaseIdentitySource, ReleaseIdentitySource];
}>;
export class ReleaseMismatchError extends Error {
readonly field: ReleaseIdentityField;
readonly sources: readonly [ReleaseIdentitySource, ReleaseIdentitySource];
constructor(
field: ReleaseIdentityField,
sources: readonly [ReleaseIdentitySource, ReleaseIdentitySource],
) {
super(`release identity mismatch: ${field} differs between ${sources[0]} and ${sources[1]}`);
this.name = "ReleaseMismatchError";
this.field = field;
this.sources = sources;
}
}
function present(value: string | undefined): value is string {
return typeof value === "string" && value.length > 0;
}
export function checkReleaseCoherence(
identities: Readonly<Partial<Record<ReleaseIdentitySource, ReleaseIdentity>>>,
fields: readonly ReleaseIdentityField[] = RELEASE_IDENTITY_FIELDS,
): ReleaseCoherenceResult {
const sources: readonly ReleaseIdentitySource[] = ["html", "config", "manifest"];
for (const field of fields) {
let reference: Readonly<{ source: ReleaseIdentitySource; value: string }> | null = null;
for (const source of sources) {
const value = identities[source]?.[field];
if (!present(value)) continue;
if (reference === null) {
reference = { source, value };
continue;
}
if (value !== reference.value) {
return Object.freeze({
coherent: false as const,
field,
sources: Object.freeze([reference.source, source] as const),
});
}
}
}
return Object.freeze({ coherent: true as const });
}
/**
* Throws `ReleaseMismatchError` (message contains "release ... mismatch") on
* the first incoherent field. The HTML and manifest build identities are
* mandatory: a boot that cannot name its own build is never coherent.
*/
export function assertReleaseCoherent(
htmlIdentity: ReleaseIdentity,
configIdentity: ReleaseIdentity,
manifestIdentity: ReleaseIdentity,
): void {
if (!present(htmlIdentity.buildId)) {
throw new ReleaseMismatchError("buildId", ["html", "manifest"]);
}
if (!present(manifestIdentity.buildId)) {
throw new ReleaseMismatchError("buildId", ["manifest", "html"]);
}
const result = checkReleaseCoherence({
html: htmlIdentity,
config: configIdentity,
manifest: manifestIdentity,
});
if (!result.coherent) throw new ReleaseMismatchError(result.field, result.sources);
}
@@ -0,0 +1,79 @@
/**
* Spec §45 / §46. Bounded recovery from a boot-time release mismatch.
*
* During a rolling release a browser can hold HTML from one release while a
* replica answers config/manifest from another. One fresh navigation usually
* lands on a coherent tuple, so exactly one automatic reload is allowed per
* stable mismatch key. A second occurrence of the same key shows the failure;
* it never reloads again, so a persistently mixed deployment cannot loop.
*
* The marker is a single bounded value. It clears after a coherent boot and
* expires after `ttlMs`, so an old marker cannot suppress recovery forever.
*/
/**
* The single persisted marker, kept by whatever session-scoped store the host
* composes (the approved browser storage adapter in production). `write` must
* throw when the marker was not persisted.
*/
export type RecoveryMarkerStore = Readonly<{
read(): string | null;
write(value: string): void;
clear(): void;
}>;
export type ReleaseMismatchDecision = "reload-once" | "show-failure";
export interface ReleaseMismatchRecovery {
decide(mismatchKey: string): ReleaseMismatchDecision;
markCoherentBoot(): void;
}
const MAX_KEY_LENGTH = 256;
export function createReleaseMismatchRecovery(
store: RecoveryMarkerStore | null,
options: Readonly<{
now?: () => number;
ttlMs?: number;
}> = {},
): ReleaseMismatchRecovery {
const now = options.now ?? (() => Date.now());
const ttlMs = options.ttlMs ?? 10 * 60_000;
function read(): Readonly<{ key: string; at: number }> | null {
const raw = store?.read() ?? null;
if (raw === null) return null;
const separator = raw.lastIndexOf("@");
const at = Number(raw.slice(separator + 1));
if (separator <= 0 || !Number.isFinite(at)) return null;
return { key: raw.slice(0, separator), at };
}
return Object.freeze({
decide(mismatchKey: string): ReleaseMismatchDecision {
const key = mismatchKey.slice(0, MAX_KEY_LENGTH);
try {
if (!store) return "show-failure";
const previous = read();
const current = now();
if (previous && previous.key === key && current - previous.at < ttlMs) {
return "show-failure";
}
store.write(`${key}@${current}`);
// Only a marker that is really persisted may authorize a reload;
// otherwise the next boot could not know it already reloaded.
return read()?.key === key ? "reload-once" : "show-failure";
} catch {
// Fail closed: without a working marker, never reload automatically.
return "show-failure";
}
},
markCoherentBoot(): void {
try {
store?.clear();
} catch {
// A stale marker only means the next mismatch shows the failure.
}
},
});
}
+28
View File
@@ -0,0 +1,28 @@
/**
* Spec §15. One absolute deadline per interaction.
*
* A retry started late only receives what is left of the original deadline; it
* never restarts an independent timeout. The helper never reads a clock itself:
* the caller supplies `now` from the same monotonic (or fake) clock that
* produced `deadlineAt`.
*/
export class DeadlineExceededError extends Error {
readonly deadlineAt: number;
readonly now: number;
constructor(deadlineAt: number, now: number) {
super(`request.timeout: interaction deadline exceeded by ${now - deadlineAt}ms`);
this.name = "DeadlineExceededError";
this.deadlineAt = deadlineAt;
this.now = now;
}
}
export function remainingDeadlineMs(deadlineAt: number, now: number): number {
if (!Number.isFinite(deadlineAt) || !Number.isFinite(now)) {
throw new TypeError("deadline and clock values must be finite");
}
const remaining = deadlineAt - now;
if (remaining < 0) throw new DeadlineExceededError(deadlineAt, now);
return remaining;
}
+34
View File
@@ -0,0 +1,34 @@
import { assertFiniteBudget } from "../traffic/request-budget.ts";
/**
* Spec §13. Retry capacity is interaction-scoped, not request-scoped.
*
* Two independent requests that fail inside the same interaction compete for
* the same retries; the budget is never reset per request, so N parallel
* requests cannot each claim their own full retry allowance during an outage.
*/
export interface RetryBudget {
readonly maximum: number;
readonly consumed: number;
/**
* `requestId` is a bounded diagnostic label only. It never partitions the
* budget; recording it per request would recreate a request-scoped budget.
*/
tryConsume(requestId: string): boolean;
}
export function createRetryBudget(maxRetries: number): RetryBudget {
assertFiniteBudget("maxRetries", maxRetries, 0);
let consumed = 0;
return Object.freeze({
maximum: maxRetries,
get consumed() {
return consumed;
},
tryConsume(_requestId: string) {
if (consumed >= maxRetries) return false;
consumed += 1;
return true;
},
});
}
@@ -0,0 +1,54 @@
import type { RouteObject } from "react-router-dom";
import type { DeployableAppModule } from "../../apps/deployable-app-module.ts";
export type ContextRouteModule = Readonly<{
id: string;
path: string;
loadRoutes(): Promise<readonly RouteObject[]>;
}>;
function createCachedContextRouteLoader(
loadRoutes: () => Promise<readonly RouteObject[]>,
): () => Promise<readonly RouteObject[]> {
let loadedRoutes: readonly RouteObject[] | undefined;
let pendingLoad: Promise<readonly RouteObject[]> | undefined;
return () => {
if (loadedRoutes) return Promise.resolve(loadedRoutes);
if (pendingLoad) return pendingLoad;
pendingLoad = Promise.resolve()
.then(loadRoutes)
.then(
(routes) => {
loadedRoutes = Object.freeze([...routes]);
return loadedRoutes;
},
(error: unknown) => {
pendingLoad = undefined;
throw error;
},
);
return pendingLoad;
};
}
export function createAppRouteModules(
app: DeployableAppModule,
): readonly ContextRouteModule[] {
return Object.freeze(
app.contexts.flatMap((context) =>
context.route
? [
Object.freeze({
id: context.id,
path: context.route.path,
loadRoutes: createCachedContextRouteLoader(
context.route.loadRoutes,
),
}),
]
: [],
),
);
}
+144
View File
@@ -0,0 +1,144 @@
/**
* Spec §28. Redaction before buffering.
*
* The sanitizer copies only plain own data into fresh objects/arrays: it never
* preserves prototypes and never invokes getters or `toJSON` on untrusted
* payloads. Traversal is iterative and capped by a structural budget, so an
* adversarial payload cannot make telemetry itself unbounded.
*/
export type TelemetryPayloadBudget = Readonly<{
maxDepth: number;
maxKeys: number;
maxArrayItems: number;
maxStringLength: number;
}>;
export const DEFAULT_TELEMETRY_PAYLOAD_BUDGET: TelemetryPayloadBudget =
Object.freeze({
maxDepth: 6,
maxKeys: 64,
maxArrayItems: 32,
maxStringLength: 256,
});
export const REDACTED = "[redacted]";
export const TRUNCATED = "[truncated]";
/**
* Case/separator-insensitive secret key detection. `accessToken`,
* `access_token` and `ACCESS-TOKEN` all normalize to `accesstoken`.
*/
const SECRET_KEY_FRAGMENTS = Object.freeze([
"password",
"passwd",
"secret",
"authorization",
"cookie",
"token",
"apikey",
"credential",
"session",
"privatekey",
"signature",
]);
export function isSecretTelemetryKey(key: string): boolean {
const normalized = key.toLowerCase().replace(/[^a-z0-9]/gu, "");
return SECRET_KEY_FRAGMENTS.some((fragment) => normalized.includes(fragment));
}
/** Values that look like bearer credentials are redacted wherever they occur. */
const SECRET_VALUE = /^(?:bearer|basic)\s+\S+|^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\./iu;
function readOwnData(
source: object,
key: string,
): Readonly<{ ok: true; value: unknown }> | Readonly<{ ok: false }> {
const descriptor = Object.getOwnPropertyDescriptor(source, key);
if (!descriptor || !("value" in descriptor)) return { ok: false };
return { ok: true, value: descriptor.value };
}
function sanitizeLeaf(value: unknown, budget: TelemetryPayloadBudget): unknown {
switch (typeof value) {
case "string":
if (SECRET_VALUE.test(value)) return REDACTED;
return value.length > budget.maxStringLength
? `${value.slice(0, budget.maxStringLength)}${TRUNCATED}`
: value;
case "number":
return Number.isFinite(value) ? value : null;
case "boolean":
return value;
default:
return null;
}
}
type Pending = Readonly<{
source: unknown;
depth: number;
assign: (value: unknown) => void;
}>;
export function redactTelemetryPayload(
payload: unknown,
budget: TelemetryPayloadBudget = DEFAULT_TELEMETRY_PAYLOAD_BUDGET,
): unknown {
let result: unknown = null;
const stack: Pending[] = [
{
source: payload,
depth: 0,
assign: (value) => {
result = value;
},
},
];
while (stack.length > 0) {
const { source, depth, assign } = stack.pop() as Pending;
if (source === null || typeof source !== "object") {
assign(source === undefined ? null : sanitizeLeaf(source, budget));
continue;
}
if (depth >= budget.maxDepth) {
assign(TRUNCATED);
continue;
}
if (Array.isArray(source)) {
const length = Math.min(source.length, budget.maxArrayItems);
const copy: unknown[] = new Array<unknown>(length).fill(null);
assign(copy);
for (let index = 0; index < length; index += 1) {
const item = readOwnData(source, String(index));
if (!item.ok) continue;
stack.push({
source: item.value,
depth: depth + 1,
assign: (value) => {
copy[index] = value;
},
});
}
continue;
}
const copy: Record<string, unknown> = {};
assign(copy);
for (const key of Object.keys(source).slice(0, budget.maxKeys)) {
if (key === "__proto__" || key === "constructor" || key === "prototype") {
continue;
}
if (isSecretTelemetryKey(key)) continue;
const entry = readOwnData(source, key);
if (!entry.ok) continue;
stack.push({
source: entry.value,
depth: depth + 1,
assign: (value) => {
copy[key] = value;
},
});
}
}
return result;
}
+125
View File
@@ -0,0 +1,125 @@
import {
TELEMETRY_SEVERITY_RANK,
type TelemetryEvent,
} from "./telemetry-event.ts";
/**
* Spec §25 / §27. Bounded, severity-aware telemetry buffer.
*
* The buffer never exceeds `maxEvents` or `maxBytes`. When full, the lowest
* severity (oldest first) event is evicted; an incoming event that is not more
* important than everything buffered is dropped instead. Buffer growth is
* never used as backpressure.
*/
export type BufferedTelemetryEvent = Readonly<{
event: TelemetryEvent<unknown>;
bytes: number;
/** Deduplication key assigned by the pipeline, when there is one. */
fingerprint?: string;
}>;
export interface TelemetryBuffer {
readonly size: number;
readonly bytes: number;
readonly dropped: number;
readonly items: readonly TelemetryEvent<unknown>[];
push(
event: TelemetryEvent<unknown>,
bytes?: number,
fingerprint?: string,
): boolean;
take(maxEvents: number): readonly BufferedTelemetryEvent[];
clear(): void;
}
const UTF8 = new TextEncoder();
export function estimateTelemetryBytes(event: TelemetryEvent<unknown>): number {
try {
return UTF8.encode(JSON.stringify(event)).byteLength;
} catch {
return Number.POSITIVE_INFINITY;
}
}
export function createTelemetryBuffer(
options: Readonly<{ maxEvents: number; maxBytes: number }>,
): TelemetryBuffer {
const { maxEvents, maxBytes } = options;
if (!Number.isSafeInteger(maxEvents) || maxEvents < 1) {
throw new TypeError(`telemetry buffer maxEvents must be positive: ${maxEvents}`);
}
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) {
throw new TypeError(`telemetry buffer maxBytes must be positive: ${maxBytes}`);
}
const entries: BufferedTelemetryEvent[] = [];
let bytes = 0;
let dropped = 0;
function lowestIndex(): number {
let index = -1;
let rank = Number.POSITIVE_INFINITY;
for (let i = 0; i < entries.length; i += 1) {
const candidate = TELEMETRY_SEVERITY_RANK[(entries[i] as BufferedTelemetryEvent).event.severity];
if (candidate < rank) {
rank = candidate;
index = i;
}
}
return index;
}
return {
get size() {
return entries.length;
},
get bytes() {
return bytes;
},
get dropped() {
return dropped;
},
get items() {
return entries.map((entry) => entry.event);
},
push(event, size = estimateTelemetryBytes(event), fingerprint) {
if (!Number.isFinite(size) || size > maxBytes) {
dropped += 1;
return false;
}
const incomingRank = TELEMETRY_SEVERITY_RANK[event.severity];
while (entries.length >= maxEvents || bytes + size > maxBytes) {
const victim = lowestIndex();
const victimEntry = entries[victim];
if (
!victimEntry ||
TELEMETRY_SEVERITY_RANK[victimEntry.event.severity] > incomingRank
) {
dropped += 1;
return false;
}
entries.splice(victim, 1);
bytes -= victimEntry.bytes;
dropped += 1;
}
entries.push(
Object.freeze(
fingerprint === undefined
? { event, bytes: size }
: { event, bytes: size, fingerprint },
),
);
bytes += size;
return true;
},
take(count) {
const batch = entries.splice(0, Math.max(0, count));
for (const entry of batch) bytes -= entry.bytes;
return batch;
},
clear() {
entries.length = 0;
bytes = 0;
},
};
}
@@ -0,0 +1,73 @@
/**
* Spec §27. Bounded fingerprint deduplication.
*
* Each fingerprint is admitted once per window; later occurrences inside the
* window only increment a counter. The table never holds more than
* `maxEntries` fingerprints: expired entries are evicted first, then the
* least recently seen one (Map insertion order is maintained as LRU order).
*/
export type TelemetryDeduplicatorOptions = Readonly<{
maxEntries: number;
windowMs: number;
}>;
type Entry = { firstSeenAt: number; count: number };
export class TelemetryDeduplicator {
readonly maxEntries: number;
readonly windowMs: number;
readonly #entries = new Map<string, Entry>();
constructor(options: TelemetryDeduplicatorOptions) {
if (!Number.isSafeInteger(options.maxEntries) || options.maxEntries < 1) {
throw new TypeError(`dedup maxEntries must be a positive safe integer: ${options.maxEntries}`);
}
if (!Number.isSafeInteger(options.windowMs) || options.windowMs < 1) {
throw new TypeError(`dedup windowMs must be a positive safe integer: ${options.windowMs}`);
}
this.maxEntries = options.maxEntries;
this.windowMs = options.windowMs;
}
get size(): number {
return this.#entries.size;
}
/**
* Records one occurrence. Returns `true` when this is the first occurrence
* in the current window (the event should continue down the pipeline) and
* `false` when it is a duplicate.
*/
record(fingerprint: string, now: number): boolean {
const existing = this.#entries.get(fingerprint);
if (existing && now - existing.firstSeenAt < this.windowMs) {
existing.count += 1;
// Refresh LRU position.
this.#entries.delete(fingerprint);
this.#entries.set(fingerprint, existing);
return false;
}
if (existing) this.#entries.delete(fingerprint);
this.#evict(now);
this.#entries.set(fingerprint, { firstSeenAt: now, count: 1 });
return true;
}
count(fingerprint: string): number {
return this.#entries.get(fingerprint)?.count ?? 0;
}
#evict(now: number): void {
if (this.#entries.size < this.maxEntries) return;
for (const [fingerprint, entry] of this.#entries) {
if (now - entry.firstSeenAt >= this.windowMs) {
this.#entries.delete(fingerprint);
}
}
while (this.#entries.size >= this.maxEntries) {
const oldest = this.#entries.keys().next();
if (oldest.done) break;
this.#entries.delete(oldest.value);
}
}
}
+52
View File
@@ -0,0 +1,52 @@
import type { ErrorSeverity } from "../errors/app-error.ts";
/**
* Spec §23–§24. The provider-neutral telemetry envelope.
*
* The platform owns the envelope and its bounded dimensions. The concrete
* `kind` and `payload` belong to the emitting feature; there is no global
* union of every feature's telemetry payload.
*/
export type TelemetrySeverity = ErrorSeverity;
export interface TelemetryEvent<TPayload = unknown> {
/** Stable low-cardinality `owner.event` identifier. */
readonly kind: string;
readonly severity: TelemetrySeverity;
readonly contextId?: string;
readonly featureId?: string;
/**
* Request-cardinality correlation. Used as the deterministic sampling key
* and never as a fingerprint dimension.
*/
readonly interactionId?: string;
readonly traceId?: string;
readonly payload?: TPayload;
}
export const TELEMETRY_SEVERITY_RANK: Readonly<Record<TelemetrySeverity, number>> =
Object.freeze({
info: 0,
warning: 1,
error: 2,
critical: 3,
});
const TELEMETRY_KIND = /^[a-z][a-z0-9-]{0,39}(?:\.[a-z][a-z0-9-]{0,39}){1,4}$/u;
const TELEMETRY_OWNER_ID = /^[a-z][a-z0-9-]{0,63}$/u;
const TELEMETRY_CORRELATION = /^[A-Za-z0-9._:-]{1,128}$/u;
/** Envelope-level admission: bounded identifiers only, payload checked later. */
export function isTelemetryEnvelopeValid(event: TelemetryEvent<unknown>): boolean {
return (
typeof event === "object" &&
event !== null &&
TELEMETRY_KIND.test(event.kind) &&
Object.hasOwn(TELEMETRY_SEVERITY_RANK, event.severity) &&
(event.contextId === undefined || TELEMETRY_OWNER_ID.test(event.contextId)) &&
(event.featureId === undefined || TELEMETRY_OWNER_ID.test(event.featureId)) &&
(event.interactionId === undefined ||
TELEMETRY_CORRELATION.test(event.interactionId)) &&
(event.traceId === undefined || /^[0-9a-f]{32}$/u.test(event.traceId))
);
}
@@ -0,0 +1,89 @@
import type { TelemetryEvent } from "./telemetry-event.ts";
/**
* Spec §27. Deterministic fingerprint over the bounded dimensions of an event.
*
* Request-cardinality fields (`interactionId`, `traceId`) are excluded on
* purpose: the same failure hitting ten thousand interactions must collapse to
* one fingerprint. The payload contributes through a stable key-sorted
* serialization of its (already redacted) value.
*/
/** Structural punctuation, kept distinct from any payload string. */
class Token {
readonly text: string;
constructor(text: string) {
this.text = text;
}
}
const CLOSE_ARRAY = new Token("]");
const CLOSE_OBJECT = new Token("}");
const COMMA = new Token(",");
export function stableSerialize(value: unknown): string {
const parts: string[] = [];
const stack: unknown[] = [value];
while (stack.length > 0) {
const current = stack.pop();
if (current instanceof Token) {
parts.push(current.text);
continue;
}
if (current === null || typeof current !== "object") {
parts.push(JSON.stringify(current ?? null) ?? "null");
continue;
}
if (Array.isArray(current)) {
parts.push("[");
stack.push(CLOSE_ARRAY);
for (let index = current.length - 1; index >= 0; index -= 1) {
stack.push(current[index]);
if (index > 0) stack.push(COMMA);
}
continue;
}
parts.push("{");
stack.push(CLOSE_OBJECT);
const keys = Object.keys(current).sort();
for (let index = keys.length - 1; index >= 0; index -= 1) {
const key = keys[index] as string;
stack.push((current as Record<string, unknown>)[key]);
stack.push(new Token(`${index > 0 ? "," : ""}${JSON.stringify(key)}:`));
}
}
return parts.join("");
}
function fnv1a32(text: string, seed: number): number {
let hash = seed >>> 0;
for (let index = 0; index < text.length; index += 1) {
hash ^= text.charCodeAt(index);
hash = Math.imul(hash, 0x01000193) >>> 0;
}
return hash >>> 0;
}
/**
* Two independently seeded 32-bit FNV-1a hashes rendered as 16 hex
* characters. Not cryptographic; collision resistance only needs to keep
* distinct low-cardinality failures apart.
*/
export function stableHash64(text: string): string {
return (
fnv1a32(text, 0x811c9dc5).toString(16).padStart(8, "0") +
fnv1a32(text, 0x01000193 ^ 0x9e3779b9).toString(16).padStart(8, "0")
);
}
export function fingerprintTelemetryEvent(event: TelemetryEvent<unknown>): string {
return stableHash64(
stableSerialize({
kind: event.kind,
severity: event.severity,
contextId: event.contextId ?? null,
featureId: event.featureId ?? null,
payload: event.payload ?? null,
}),
);
}
@@ -0,0 +1,283 @@
import {
createTelemetryBuffer,
estimateTelemetryBytes,
} from "./telemetry-buffer.ts";
import { TelemetryDeduplicator } from "./telemetry-deduplicator.ts";
import {
isTelemetryEnvelopeValid,
TELEMETRY_SEVERITY_RANK,
type TelemetryEvent,
} from "./telemetry-event.ts";
import { fingerprintTelemetryEvent } from "./telemetry-fingerprint.ts";
import type { TelemetryPort } from "./telemetry-port.ts";
import {
DEFAULT_TELEMETRY_PAYLOAD_BUDGET,
redactTelemetryPayload,
type TelemetryPayloadBudget,
} from "./redact-telemetry.ts";
import { createDeterministicSampler } from "./telemetry-sampler.ts";
/**
* Spec §25–§28. The bounded, fail-open telemetry pipeline:
*
* redact -> fingerprint -> deduplicate -> sample -> buffer
* -> rate limit -> batch -> transport
*
* Every stage has an explicit ceiling, and no stage can throw or reject into
* the business caller: internal failures become dropped-event counters.
*/
export type TelemetryBatchItem = Readonly<{
event: TelemetryEvent<unknown>;
fingerprint: string;
/** Occurrences collapsed into this fingerprint in the current window. */
occurrences: number;
}>;
export interface TelemetryTransport {
send(batch: readonly TelemetryBatchItem[]): void | Promise<void>;
}
export interface TelemetryPipelineBudget {
readonly maxBufferedEvents: number;
readonly maxBufferedBytes: number;
readonly maxBatchEvents: number;
readonly maxSendsPerMinute: number;
readonly dedupWindowMs: number;
readonly maxFingerprints: number;
/** Sampling rate for `info`/`warning`; `error`/`critical` are never sampled out. */
readonly sampleRate: number;
readonly payload?: TelemetryPayloadBudget;
}
export const DEFAULT_TELEMETRY_PIPELINE_BUDGET: TelemetryPipelineBudget =
Object.freeze({
maxBufferedEvents: 200,
maxBufferedBytes: 256 * 1024,
maxBatchEvents: 50,
maxSendsPerMinute: 20,
dedupWindowMs: 60_000,
maxFingerprints: 500,
sampleRate: 1,
});
export type TelemetryPipelineStats = Readonly<{
accepted: number;
invalid: number;
deduplicated: number;
sampledOut: number;
dropped: number;
sends: number;
failedSends: number;
buffered: number;
bufferedBytes: number;
peakBuffered: number;
fingerprints: number;
}>;
export interface TelemetryPipeline extends TelemetryPort {
emit(event: TelemetryEvent<unknown>): Promise<void>;
flush(): Promise<void>;
stats(): TelemetryPipelineStats;
dispose(): void;
}
const RATE_WINDOW_MS = 60_000;
function assertPositive(name: string, value: number): void {
if (!Number.isSafeInteger(value) || value < 1) {
throw new TypeError(`telemetry budget ${name} must be a positive safe integer: ${value}`);
}
}
export function createTelemetryPipeline(
options: Readonly<{
transport: TelemetryTransport;
budget?: TelemetryPipelineBudget;
/** Monotonic clock. */
now?: () => number;
/** Schedules a flush soon (default: microtask). */
schedule?: (callback: () => void) => void;
/** Schedules a flush after a rate window reopens (default: setTimeout). */
setTimer?: (callback: () => void, ms: number) => unknown;
clearTimer?: (handle: unknown) => void;
}>,
): TelemetryPipeline {
const budget = options.budget ?? DEFAULT_TELEMETRY_PIPELINE_BUDGET;
assertPositive("maxBufferedEvents", budget.maxBufferedEvents);
assertPositive("maxBufferedBytes", budget.maxBufferedBytes);
assertPositive("maxBatchEvents", budget.maxBatchEvents);
assertPositive("maxSendsPerMinute", budget.maxSendsPerMinute);
const payloadBudget = budget.payload ?? DEFAULT_TELEMETRY_PAYLOAD_BUDGET;
const now = options.now ?? (() => performance.now());
const schedule = options.schedule ?? queueMicrotask;
const setTimer =
options.setTimer ??
((callback: () => void, ms: number) => setTimeout(callback, ms));
const clearTimer =
options.clearTimer ??
((handle: unknown) => clearTimeout(handle as ReturnType<typeof setTimeout>));
const dedup = new TelemetryDeduplicator({
maxEntries: budget.maxFingerprints,
windowMs: budget.dedupWindowMs,
});
const sampler = createDeterministicSampler({ rate: budget.sampleRate });
const buffer = createTelemetryBuffer({
maxEvents: budget.maxBufferedEvents,
maxBytes: budget.maxBufferedBytes,
});
/** Send timestamps inside the current rate window; never above the limit. */
const sendTimes: number[] = [];
let disposed = false;
let flushScheduled = false;
let rateTimer: unknown = null;
let activeFlush: Promise<void> | null = null;
const counters = {
accepted: 0,
invalid: 0,
deduplicated: 0,
sampledOut: 0,
sends: 0,
failedSends: 0,
peakBuffered: 0,
};
function rateAllows(at: number): boolean {
while (sendTimes.length > 0 && at - (sendTimes[0] as number) >= RATE_WINDOW_MS) {
sendTimes.shift();
}
return sendTimes.length < budget.maxSendsPerMinute;
}
function armRateTimer(at: number): void {
if (rateTimer !== null || disposed) return;
const reopenIn = Math.max(1, (sendTimes[0] ?? at) + RATE_WINDOW_MS - at);
rateTimer = setTimer(() => {
rateTimer = null;
void flush();
}, reopenIn);
}
function scheduleFlush(): void {
if (flushScheduled || disposed) return;
flushScheduled = true;
schedule(() => {
flushScheduled = false;
void flush();
});
}
async function drain(): Promise<void> {
while (!disposed && buffer.size > 0) {
const at = now();
if (!rateAllows(at)) {
armRateTimer(at);
return;
}
const batch = buffer.take(budget.maxBatchEvents).map((entry) =>
Object.freeze({
event: entry.event,
fingerprint: entry.fingerprint ?? "",
occurrences: Math.max(1, dedup.count(entry.fingerprint ?? "")),
}),
);
sendTimes.push(at);
counters.sends += 1;
try {
await options.transport.send(batch);
} catch {
// Best effort: a failed batch is counted, never retried unboundedly.
counters.failedSends += batch.length;
}
}
}
function flush(): Promise<void> {
if (activeFlush) return activeFlush;
if (disposed || buffer.size === 0) return Promise.resolve();
activeFlush = drain()
.catch(() => undefined)
.finally(() => {
activeFlush = null;
});
return activeFlush;
}
function admit(event: TelemetryEvent<unknown>): void {
if (disposed) return;
if (!isTelemetryEnvelopeValid(event)) {
counters.invalid += 1;
return;
}
// 1. redact (before anything is retained)
const redacted: TelemetryEvent<unknown> = Object.freeze({
kind: event.kind,
severity: event.severity,
...(event.contextId === undefined ? {} : { contextId: event.contextId }),
...(event.featureId === undefined ? {} : { featureId: event.featureId }),
...(event.interactionId === undefined
? {}
: { interactionId: event.interactionId }),
...(event.traceId === undefined ? {} : { traceId: event.traceId }),
...(event.payload === undefined
? {}
: { payload: redactTelemetryPayload(event.payload, payloadBudget) }),
});
// 2. fingerprint 3. deduplicate
const fingerprint = fingerprintTelemetryEvent(redacted);
if (!dedup.record(fingerprint, now())) {
counters.deduplicated += 1;
return;
}
// 4. sample (deterministic by interaction; severe events always kept)
if (
TELEMETRY_SEVERITY_RANK[redacted.severity] < TELEMETRY_SEVERITY_RANK.error &&
!sampler.keep(redacted.interactionId ?? fingerprint)
) {
counters.sampledOut += 1;
return;
}
// 5. buffer
if (buffer.push(redacted, estimateTelemetryBytes(redacted), fingerprint)) {
counters.accepted += 1;
counters.peakBuffered = Math.max(counters.peakBuffered, buffer.size);
}
// 6-8. rate limit, batch and transport happen on flush.
scheduleFlush();
}
return Object.freeze({
emit(event: TelemetryEvent<unknown>): Promise<void> {
try {
admit(event);
} catch {
counters.invalid += 1;
}
return Promise.resolve();
},
flush,
stats(): TelemetryPipelineStats {
return Object.freeze({
accepted: counters.accepted,
invalid: counters.invalid,
deduplicated: counters.deduplicated,
sampledOut: counters.sampledOut,
dropped: buffer.dropped + counters.failedSends + counters.invalid,
sends: counters.sends,
failedSends: counters.failedSends,
buffered: buffer.size,
bufferedBytes: buffer.bytes,
peakBuffered: counters.peakBuffered,
fingerprints: dedup.size,
});
},
dispose(): void {
if (disposed) return;
disposed = true;
if (rateTimer !== null) clearTimer(rateTimer);
rateTimer = null;
buffer.clear();
},
});
}
+35
View File
@@ -0,0 +1,35 @@
import type { TelemetryEvent } from "./telemetry-event.ts";
/**
* Spec §24. The only observability surface feature code may use.
*
* `emit` is best-effort: an implementation must never throw or reject into
* business behavior. Vendor SDKs live behind an adapter-side transport, never
* in feature code.
*/
export interface TelemetryPort {
emit(event: TelemetryEvent<unknown>): void | Promise<void>;
}
export const NO_OP_TELEMETRY_PORT: TelemetryPort = Object.freeze({
emit() {},
});
/**
* Wraps any port so that a synchronous throw or an asynchronous rejection is
* contained at the call site (spec §26).
*/
export function failOpenTelemetryPort(port: TelemetryPort): TelemetryPort {
return Object.freeze({
emit(event: TelemetryEvent<unknown>): Promise<void> {
try {
return Promise.resolve(port.emit(event)).then(
() => undefined,
() => undefined,
);
} catch {
return Promise.resolve();
}
},
});
}
@@ -0,0 +1,32 @@
import { stableHash64 } from "./telemetry-fingerprint.ts";
/**
* Spec §25. Deterministic sampling by a stable key (interaction or trace id).
*
* The same key always yields the same decision, so one interaction's events
* are kept or dropped together instead of producing partial traces.
*/
export interface TelemetrySampler {
readonly rate: number;
keep(key: string): boolean;
}
export function createDeterministicSampler(
options: Readonly<{ rate: number }>,
): TelemetrySampler {
const { rate } = options;
if (!Number.isFinite(rate) || rate < 0 || rate > 1) {
throw new TypeError(`sampling rate must be within [0, 1]: ${rate}`);
}
// 32-bit bucket from the stable hash; exact at the 0 and 1 edges.
const threshold = Math.floor(rate * 0x1_0000_0000);
return Object.freeze({
rate,
keep(key: string): boolean {
if (rate >= 1) return true;
if (rate <= 0) return false;
const bucket = Number.parseInt(stableHash64(key).slice(0, 8), 16);
return bucket < threshold;
},
});
}
+103
View File
@@ -0,0 +1,103 @@
/**
* Spec §29. One interaction trace identity propagated to every child request.
*
* The header names follow the conventions already in the repository: the W3C
* `traceparent` (validated by `safeTraceparent` in the telemetry adapter) and
* the `x-correlation-id` the HTTP runtime already reads back from responses.
* No second, competing correlation header is introduced.
*/
export const TRACEPARENT_HEADER = "traceparent";
export const CORRELATION_ID_HEADER = "x-correlation-id";
export type TraceContext = Readonly<{
traceId: string;
spanId: string;
sampled: boolean;
traceparent: string;
}>;
const TRACE_ID = /^[0-9a-f]{32}$/u;
const SPAN_ID = /^[0-9a-f]{16}$/u;
const CORRELATION_ID = /^[A-Za-z0-9._:-]{1,128}$/u;
export function isValidTraceId(value: string): boolean {
return TRACE_ID.test(value) && !/^0+$/u.test(value);
}
export function isValidSpanId(value: string): boolean {
return SPAN_ID.test(value) && !/^0+$/u.test(value);
}
function randomHex(bytes: number, random: () => number): string {
let out = "";
for (let index = 0; index < bytes; index += 1) {
out += Math.floor(random() * 256)
.toString(16)
.padStart(2, "0");
}
return out;
}
function secureRandomHex(bytes: number): string {
const buffer = new Uint8Array(bytes);
globalThis.crypto.getRandomValues(buffer);
return Array.from(buffer, (byte) => byte.toString(16).padStart(2, "0")).join("");
}
export function createTraceContext(
options: Readonly<{
traceId?: string;
spanId?: string;
sampled?: boolean;
/** Test seam; production uses `crypto.getRandomValues`. */
random?: () => number;
}> = {},
): TraceContext {
const generate = (bytes: number) =>
options.random ? randomHex(bytes, options.random) : secureRandomHex(bytes);
let traceId = options.traceId ?? generate(16);
let spanId = options.spanId ?? generate(8);
if (!isValidTraceId(traceId)) {
if (options.traceId !== undefined) {
throw new TypeError("traceId must be 32 lowercase hex characters, not all zero");
}
traceId = `${traceId.slice(0, 31)}1`;
}
if (!isValidSpanId(spanId)) {
if (options.spanId !== undefined) {
throw new TypeError("spanId must be 16 lowercase hex characters, not all zero");
}
spanId = `${spanId.slice(0, 15)}1`;
}
const sampled = options.sampled ?? true;
return Object.freeze({
traceId,
spanId,
sampled,
traceparent: `00-${traceId}-${spanId}-${sampled ? "01" : "00"}`,
});
}
/**
* The trace/correlation headers for one physical request. Every child request
* of the same interaction carries the same `traceparent` and correlation id.
*/
export function buildTraceHeaders(
context: Readonly<{
interaction: Readonly<{ id: string }>;
trace?: TraceContext;
}>,
): Readonly<Record<string, string>> {
const headers: Record<string, string> = {};
if (CORRELATION_ID.test(context.interaction.id)) {
headers[CORRELATION_ID_HEADER] = context.interaction.id;
}
if (context.trace) headers[TRACEPARENT_HEADER] = context.trace.traceparent;
return Object.freeze(headers);
}
export function buildRequestHeaders(
context: Parameters<typeof buildTraceHeaders>[0],
): Headers {
return new Headers(buildTraceHeaders(context));
}
+114
View File
@@ -0,0 +1,114 @@
import { assertFiniteBudget } from "./request-budget.ts";
/**
* Spec §14. Cancellable concurrency leases with a bounded FIFO waiting queue.
*
* - No more than `maximum` leases are ever active at once.
* - No more than `maxQueued` callers ever wait; the next caller is rejected
* immediately instead of growing the queue (queue growth is not
* backpressure).
* - An aborted waiter leaves the queue at once and never receives a lease.
* - A lease is idempotently releasable, so a double release cannot inflate
* capacity.
*/
export class ConcurrencyQueueFullError extends RangeError {
readonly maxQueued: number;
constructor(maxQueued: number) {
super(`traffic.budget-exceeded: concurrency queue full (${maxQueued})`);
this.name = "ConcurrencyQueueFullError";
this.maxQueued = maxQueued;
}
}
export interface ConcurrencyLease {
release(): void;
}
export interface ConcurrencyBudget {
readonly maximum: number;
readonly maxQueued: number;
readonly active: number;
readonly queued: number;
acquire(signal: AbortSignal): Promise<ConcurrencyLease>;
}
type Waiter = {
grant(lease: ConcurrencyLease): void;
settled: boolean;
};
function abortError(): DOMException {
return new DOMException("concurrency wait aborted", "AbortError");
}
export function createConcurrencyBudget(
options: Readonly<{ maximum: number; maxQueued: number }>,
): ConcurrencyBudget {
assertFiniteBudget("maxConcurrentRequests", options.maximum, 1);
assertFiniteBudget("maxQueuedRequests", options.maxQueued, 0);
const { maximum, maxQueued } = options;
let active = 0;
const waiters: Waiter[] = [];
function createLease(): ConcurrencyLease {
let released = false;
return Object.freeze({
release() {
if (released) return;
released = true;
active -= 1;
drain();
},
});
}
function drain(): void {
while (active < maximum && waiters.length > 0) {
const next = waiters.shift();
if (!next || next.settled) continue;
active += 1;
next.grant(createLease());
}
}
return Object.freeze({
maximum,
maxQueued,
get active() {
return active;
},
get queued() {
return waiters.length;
},
acquire(signal: AbortSignal): Promise<ConcurrencyLease> {
if (signal.aborted) return Promise.reject(abortError());
if (active < maximum && waiters.length === 0) {
active += 1;
return Promise.resolve(createLease());
}
if (waiters.length >= maxQueued) {
return Promise.reject(new ConcurrencyQueueFullError(maxQueued));
}
return new Promise<ConcurrencyLease>((resolve, reject) => {
const onAbort = () => {
if (waiter.settled) return;
waiter.settled = true;
const index = waiters.indexOf(waiter);
if (index >= 0) waiters.splice(index, 1);
reject(abortError());
};
const waiter: Waiter = {
settled: false,
grant(lease) {
waiter.settled = true;
signal.removeEventListener("abort", onAbort);
resolve(lease);
},
};
waiters.push(waiter);
signal.addEventListener("abort", onAbort, { once: true });
});
},
});
}
+54
View File
@@ -0,0 +1,54 @@
/**
* Spec §11. The number of physical requests one interaction may dispatch.
*
* Consumption is monotonic: a budget never refills inside the interaction that
* owns it, so a retry storm cannot turn one user action into an unbounded
* number of dispatches.
*/
export class RequestBudgetExceededError extends RangeError {
readonly maximum: number;
constructor(maximum: number) {
super(`traffic.budget-exceeded: physical request budget ${maximum} exhausted`);
this.name = "RequestBudgetExceededError";
this.maximum = maximum;
}
}
export interface RequestBudget {
readonly maximum: number;
readonly consumed: number;
readonly remaining: number;
tryConsume(): boolean;
}
export function assertFiniteBudget(
name: string,
value: number,
minimum: number,
): void {
if (!Number.isSafeInteger(value) || value < minimum) {
throw new TypeError(
`traffic budget ${name} must be a finite safe integer >= ${minimum}: ${value}`,
);
}
}
export function createRequestBudget(maxPhysicalRequests: number): RequestBudget {
assertFiniteBudget("maxPhysicalRequests", maxPhysicalRequests, 1);
let consumed = 0;
return Object.freeze({
maximum: maxPhysicalRequests,
get consumed() {
return consumed;
},
get remaining() {
return maxPhysicalRequests - consumed;
},
tryConsume() {
if (consumed >= maxPhysicalRequests) return false;
consumed += 1;
return true;
},
});
}
+31
View File
@@ -0,0 +1,31 @@
/**
* Spec §12 / §41. Collection cardinality must not become physical request
* cardinality. Loading N rows costs a bounded number of requests (one page or
* one bulk/read-model call), never one request per row.
*/
export class RequestFanoutExceededError extends RangeError {
readonly physicalRequests: number;
readonly maximum: number;
constructor(physicalRequests: number, maximum: number) {
super(`Request fan-out ${physicalRequests} exceeds ${maximum}`);
this.name = "RequestFanoutExceededError";
this.physicalRequests = physicalRequests;
this.maximum = maximum;
}
}
export function assertRequestFanoutWithinBudget(
physicalRequests: number,
maximum: number,
): void {
if (!Number.isSafeInteger(maximum) || maximum < 1) {
throw new TypeError(`Invalid request fan-out budget: ${maximum}`);
}
if (!Number.isSafeInteger(physicalRequests) || physicalRequests < 0) {
throw new TypeError(`Invalid physical request count: ${physicalRequests}`);
}
if (physicalRequests > maximum) {
throw new RequestFanoutExceededError(physicalRequests, maximum);
}
}
+88
View File
@@ -0,0 +1,88 @@
import {
createRetryBudget,
type RetryBudget,
} from "../resilience/retry-budget.ts";
import {
createConcurrencyBudget,
type ConcurrencyBudget,
} from "./concurrency-budget.ts";
import {
assertFiniteBudget,
createRequestBudget,
type RequestBudget,
} from "./request-budget.ts";
/**
* Spec §11. Immutable traffic policy. Every field is a finite safe integer;
* there is no "unlimited" sentinel.
*/
export interface TrafficBudget {
readonly maxPhysicalRequests: number;
readonly maxRetries: number;
readonly maxConcurrentRequests: number;
readonly maxQueuedRequests: number;
}
/**
* The mutable, interaction-local counters derived from one `TrafficBudget`.
* One runtime is created per interaction and shared by every child operation.
*/
export interface TrafficRuntime {
readonly policy: TrafficBudget;
readonly requests: RequestBudget;
readonly retries: RetryBudget;
readonly concurrency: ConcurrencyBudget;
}
export const TRAFFIC_BUDGET_KEYS = [
"maxPhysicalRequests",
"maxRetries",
"maxConcurrentRequests",
"maxQueuedRequests",
] as const satisfies readonly (keyof TrafficBudget)[];
/** Hard ceilings a policy may lower but never raise. */
export const TRAFFIC_BUDGET_CEILINGS = Object.freeze({
maxPhysicalRequests: 64,
maxRetries: 16,
maxConcurrentRequests: 16,
maxQueuedRequests: 256,
});
export function defineTrafficBudget(policy: TrafficBudget): TrafficBudget {
if (policy === null || typeof policy !== "object") {
throw new TypeError("traffic budget must be an object");
}
assertFiniteBudget("maxPhysicalRequests", policy.maxPhysicalRequests, 1);
assertFiniteBudget("maxRetries", policy.maxRetries, 0);
assertFiniteBudget("maxConcurrentRequests", policy.maxConcurrentRequests, 1);
assertFiniteBudget("maxQueuedRequests", policy.maxQueuedRequests, 0);
for (const key of TRAFFIC_BUDGET_KEYS) {
if (policy[key] > TRAFFIC_BUDGET_CEILINGS[key]) {
throw new RangeError(
`traffic budget ${key} ${policy[key]} exceeds ceiling ${TRAFFIC_BUDGET_CEILINGS[key]}`,
);
}
}
// Every retry is also a physical request, so the effective retry count is
// min(maxRetries, maxPhysicalRequests - 1); both budgets are enforced.
return Object.freeze({
maxPhysicalRequests: policy.maxPhysicalRequests,
maxRetries: policy.maxRetries,
maxConcurrentRequests: policy.maxConcurrentRequests,
maxQueuedRequests: policy.maxQueuedRequests,
});
}
export function createTrafficRuntime(policy: TrafficBudget): TrafficRuntime {
const budget = defineTrafficBudget(policy);
return Object.freeze({
policy: budget,
requests: createRequestBudget(budget.maxPhysicalRequests),
retries: createRetryBudget(budget.maxRetries),
concurrency: createConcurrencyBudget({
maximum: budget.maxConcurrentRequests,
maxQueued: budget.maxQueuedRequests,
}),
});
}
+117
View File
@@ -0,0 +1,117 @@
import type { ValidationBudget } from "./validation-budget.ts";
/**
* Spec §20–§22. Size before parse, structure before mapping.
*
* `parseBoundedJson` rejects oversized text before `JSON.parse` runs, then
* walks the parsed value with an explicit stack (never recursion) so an
* adversarially nested payload cannot overflow the call stack or make the
* mapper/validator do unbounded work.
*/
export type JsonBudgetViolation =
| "too-large"
| "too-many-items"
| "too-deep"
| "string-too-long"
| "invalid-json";
export class JsonBudgetExceededError extends RangeError {
readonly violation: JsonBudgetViolation;
constructor(violation: JsonBudgetViolation, detail: string) {
super(`response.${violation}: ${detail}`);
this.name = "JsonBudgetExceededError";
this.violation = violation;
}
}
const UTF8 = new TextEncoder();
function utf8Length(text: string, ceiling: number): number {
// Each UTF-16 unit encodes to at most 3 UTF-8 bytes, so only text that could
// exceed the ceiling pays for an exact encode.
if (text.length * 3 <= ceiling) return text.length;
return UTF8.encode(text).byteLength;
}
export function parseBoundedJson(text: string, budget: ValidationBudget): unknown {
if (text.length > budget.maxBytes || utf8Length(text, budget.maxBytes) > budget.maxBytes) {
throw new JsonBudgetExceededError(
"too-large",
`payload exceeds ${budget.maxBytes} bytes`,
);
}
let value: unknown;
try {
value = JSON.parse(text);
} catch {
throw new JsonBudgetExceededError("invalid-json", "payload is not JSON");
}
validateJsonStructure(value, budget);
return value;
}
export type JsonStructureResult =
| Readonly<{ ok: true; nodes: number }>
| Readonly<{ ok: false; violation: JsonBudgetViolation; detail: string }>;
/**
* Non-throwing structural check over an already-parsed JSON value. Plain data
* only: prototypes and accessors are never consulted.
*/
export function checkJsonStructure(
value: unknown,
budget: ValidationBudget,
): JsonStructureResult {
const stack: Array<readonly [unknown, number]> = [[value, 1]];
let nodes = 0;
while (stack.length > 0) {
const [current, depth] = stack.pop() as readonly [unknown, number];
nodes += 1;
if (nodes > budget.maxItems) {
return fail("too-many-items", `more than ${budget.maxItems} nodes`);
}
if (typeof current === "string") {
if (current.length > budget.maxStringLength) {
return fail(
"string-too-long",
`string longer than ${budget.maxStringLength}`,
);
}
continue;
}
if (current === null || typeof current !== "object") continue;
if (depth > budget.maxDepth) {
return fail("too-deep", `nesting deeper than ${budget.maxDepth}`);
}
if (Array.isArray(current)) {
if (current.length > budget.maxItems) {
return fail("too-many-items", `array longer than ${budget.maxItems}`);
}
for (let index = current.length - 1; index >= 0; index -= 1) {
stack.push([current[index], depth + 1]);
}
continue;
}
const keys = Object.keys(current);
if (keys.length > budget.maxItems) {
return fail("too-many-items", `object wider than ${budget.maxItems}`);
}
for (const key of keys) {
if (key.length > budget.maxStringLength) {
return fail("string-too-long", "object key too long");
}
stack.push([(current as Record<string, unknown>)[key], depth + 1]);
}
}
return Object.freeze({ ok: true as const, nodes });
}
export function validateJsonStructure(value: unknown, budget: ValidationBudget): void {
const result = checkJsonStructure(value, budget);
if (!result.ok) throw new JsonBudgetExceededError(result.violation, result.detail);
}
function fail(violation: JsonBudgetViolation, detail: string): JsonStructureResult {
return Object.freeze({ ok: false as const, violation, detail });
}
@@ -0,0 +1,51 @@
/**
* Spec §22. Structural limits for data that crosses a trust boundary.
*
* Every value is a finite positive safe integer: there is no "unbounded"
* validation configuration. These limits protect local CPU/memory cost; they
* never replace backend validation.
*/
export interface ValidationBudget {
readonly maxBytes: number;
readonly maxItems: number;
readonly maxDepth: number;
readonly maxStringLength: number;
}
const VALIDATION_BUDGET_KEYS = [
"maxBytes",
"maxItems",
"maxDepth",
"maxStringLength",
] as const satisfies readonly (keyof ValidationBudget)[];
export function defineValidationBudget(budget: ValidationBudget): ValidationBudget {
for (const key of VALIDATION_BUDGET_KEYS) {
const value = budget[key];
if (!Number.isSafeInteger(value) || value < 1) {
throw new TypeError(
`validation budget ${key} must be a finite positive safe integer: ${value}`,
);
}
}
return Object.freeze({
maxBytes: budget.maxBytes,
maxItems: budget.maxItems,
maxDepth: budget.maxDepth,
maxStringLength: budget.maxStringLength,
});
}
/**
* The structure budget applied to an HTTP response already bounded by its
* operation's `responseByteLimit`. `maxItems` bounds every array/object
* member count and the total node count; `maxDepth` bounds nesting.
*/
export function responseValidationBudget(responseByteLimit: number): ValidationBudget {
return defineValidationBudget({
maxBytes: responseByteLimit,
maxItems: 100_000,
maxDepth: 64,
maxStringLength: responseByteLimit,
});
}