chore: sync the frontend template from ebea300 to af3d8e6
Carries 359 template commits, tag v0.2.0 plus one documentation commit: the generator-built feature index with its app, bounded-context and feature declarations, the src/platform kernel and scale tooling, the 2026-09-24 src review fixes, and the 2026-09-25 maturity review round with its CHANGELOG [보안]/[계약] rows. 691 of the 824 template paths are applied, 85 of them merged with product changes; 127 are not carried. Product identity is unchanged: name, version 0.1.0, routes, design and the TechLog domain. Three decisions worth naming. TechLog stays composed directly, as the last two syncs recorded; its directory carries a NOT_INSTALLED marker that says so, and every installed-* composer takes the template's projection with TechLog added on top. The reference sample is no longer installed: the template now installs a feature only through feature-module.ts and context-routes.ts, which load the screens this product deleted, so its three operations, six schemas and one topic leave the registries, recorded as registry change evidence. And AppRouter mounts the platform and TechLog routes only; the template's bounded-context route gateway waits for a generator-installed feature. Required fixes: readSubject on the BFF session owner (without it every HTTP Studio session would close as integration-failed), zod through the facade in nine TechLog files, noUnusedLocals, and public/config.json written out to match the local profile. Derived baselines were recomputed after reproducing both sides' values: CI contract 101 commands / 106 references / 141 artifacts, gate shape c9adcf85; registry approval 2dc6c3a3; the runtime config schema baseline equals the schema at8210d48. Verified here: types, lint, architecture, adapter inventory, CI contract, i18n, design system, diagnostics, browser security, dev release manifest, TechLog contract and build pass; 220 component, 155 integration, 15 contract, 418 TechLog, 43 reference-feature, 18 recipe and 46 release-coherence tests pass, and 2381 of 2383 unit tests. Reproduced at8210d48first and unchanged: check:registries (byte-identical), test:runtime-schema, verify:documentation. Brought by the template and escalated rather than suppressed: check:request-fanout on TechLog's cursor pagination, check:remediation-ledger (fails upstream too), the shared-chunk hash test, and the registry-dependent sample removal and second-feature tests. Playwright suites were not run. Full record, the five open questions and the follow-ups in docs/operations/template-sync-2026-09-29.md. (cherry picked from commit b2170cf265dea45dc9cc05d3c61e627e97f31cdb)
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { CardinalityBudgetExceededError, assertWithinCardinalityBudget } from "../../../src/platform/cardinality/cardinality-budget.ts";
|
||||
describe("assertWithinCardinalityBudget", () => {
|
||||
it("accepts the exact ceiling", () => expect(() => assertWithinCardinalityBudget("commerce.features", 200, 200)).not.toThrow());
|
||||
it("rejects values above the ceiling", () => expect(() => assertWithinCardinalityBudget("commerce.features", 201, 200)).toThrow(CardinalityBudgetExceededError));
|
||||
it("rejects invalid ceilings", () => expect(() => assertWithinCardinalityBudget("x", 0, Infinity)).toThrow(TypeError));
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { composeUniqueRecord } from "../../../src/platform/cardinality/compose-unique-record.ts";
|
||||
describe("composeUniqueRecord", () => {
|
||||
it("composes entries", () => expect(composeUniqueRecord([{a:1},{b:2}], () => "test")).toEqual({a:1,b:2}));
|
||||
it("rejects duplicate keys", () => expect(() => composeUniqueRecord([{a:1},{a:2}], () => "routes")).toThrow(/Duplicate routes key: a/));
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import { performance } from "node:perf_hooks";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
resolveProductFeatures,
|
||||
selectCompiledProductFeatures,
|
||||
} from "../../../src/contracts/product-features.ts";
|
||||
import { composeUniqueRecord } from "../../../src/platform/cardinality/compose-unique-record.ts";
|
||||
|
||||
const SMALL_REGISTRY_SIZE = 10_000;
|
||||
const LARGE_REGISTRY_SIZE = 100_000;
|
||||
const FEATURE_SCALE_SIZE = 100_000;
|
||||
const LOOKUP_OPERATIONS = 1_000_000;
|
||||
const MEASUREMENT_RUNS = 3;
|
||||
|
||||
const MAX_COMPOSE_GROWTH_RATIO = 30;
|
||||
const MAX_LARGE_COMPOSE_MS = 3_000;
|
||||
const MAX_MEMBERSHIP_MS = 3_000;
|
||||
const MAX_LOOKUP_MS = 1_500;
|
||||
|
||||
function syntheticRecords(count: number): readonly Readonly<Record<string, number>>[] {
|
||||
return Array.from({ length: count }, (_, index) => ({ [`key-${index}`]: index }));
|
||||
}
|
||||
|
||||
function median(values: readonly number[]): number {
|
||||
const sorted = [...values].sort((left, right) => left - right);
|
||||
return sorted[Math.floor(sorted.length / 2)] ?? Number.POSITIVE_INFINITY;
|
||||
}
|
||||
|
||||
function measureMedianElapsedMs(action: () => void): number {
|
||||
action();
|
||||
const samples = Array.from({ length: MEASUREMENT_RUNS }, () => {
|
||||
const startedAt = performance.now();
|
||||
action();
|
||||
return performance.now() - startedAt;
|
||||
});
|
||||
return median(samples);
|
||||
}
|
||||
|
||||
function measureCompose(records: readonly Readonly<Record<string, number>>[]): Readonly<{
|
||||
elapsedMs: number;
|
||||
registry: Readonly<Record<string, number>>;
|
||||
}> {
|
||||
let registry: Readonly<Record<string, number>> = {};
|
||||
const elapsedMs = measureMedianElapsedMs(() => {
|
||||
registry = composeUniqueRecord(records, () => "synthetic registry");
|
||||
});
|
||||
return Object.freeze({ elapsedMs, registry });
|
||||
}
|
||||
|
||||
describe("extreme-scale registry composition", () => {
|
||||
it("keeps 10k -> 100k composition growth below a quadratic regression budget", () => {
|
||||
const smallRecords = syntheticRecords(SMALL_REGISTRY_SIZE);
|
||||
const largeRecords = syntheticRecords(LARGE_REGISTRY_SIZE);
|
||||
const small = measureCompose(smallRecords);
|
||||
const large = measureCompose(largeRecords);
|
||||
const growthRatio = large.elapsedMs / Math.max(small.elapsedMs, 1);
|
||||
|
||||
expect(Object.keys(small.registry)).toHaveLength(SMALL_REGISTRY_SIZE);
|
||||
expect(Object.keys(large.registry)).toHaveLength(LARGE_REGISTRY_SIZE);
|
||||
expect(large.elapsedMs).toBeLessThan(MAX_LARGE_COMPOSE_MS);
|
||||
expect(growthRatio).toBeLessThan(MAX_COMPOSE_GROWTH_RATIO);
|
||||
});
|
||||
|
||||
it("keeps one million lookups bounded on a 100k-entry runtime registry", () => {
|
||||
const { registry } = measureCompose(syntheticRecords(LARGE_REGISTRY_SIZE));
|
||||
let checksum = 0;
|
||||
const elapsedMs = measureMedianElapsedMs(() => {
|
||||
let currentChecksum = 0;
|
||||
for (let index = 0; index < LOOKUP_OPERATIONS; index += 1) {
|
||||
currentChecksum += registry[`key-${index % LARGE_REGISTRY_SIZE}`] ?? -1;
|
||||
}
|
||||
checksum = currentChecksum;
|
||||
});
|
||||
|
||||
expect(checksum).toBeGreaterThan(0);
|
||||
expect(elapsedMs).toBeLessThan(MAX_LOOKUP_MS);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extreme-scale product feature membership", () => {
|
||||
it("selects and resolves 100k feature ids within the membership budget", () => {
|
||||
const compiled = Array.from({ length: FEATURE_SCALE_SIZE }, (_, index) =>
|
||||
Object.freeze({ featureId: `feature-${index.toString().padStart(6, "0")}` }),
|
||||
);
|
||||
const requestedIds = compiled
|
||||
.filter((_, index) => index % 10 === 0)
|
||||
.map((feature) => feature.featureId);
|
||||
const declared = requestedIds.join(",");
|
||||
|
||||
let selected = compiled.slice(0, 0);
|
||||
const selectionElapsedMs = measureMedianElapsedMs(() => {
|
||||
selected = [...selectCompiledProductFeatures(compiled, declared)];
|
||||
});
|
||||
|
||||
let statuses = resolveProductFeatures([], []);
|
||||
const installedIds = selected.map((feature) => feature.featureId);
|
||||
const compiledIds = compiled.map((feature) => feature.featureId);
|
||||
const resolveElapsedMs = measureMedianElapsedMs(() => {
|
||||
statuses = resolveProductFeatures(compiledIds, installedIds);
|
||||
});
|
||||
|
||||
expect(selected).toHaveLength(FEATURE_SCALE_SIZE / 10);
|
||||
expect(statuses).toHaveLength(FEATURE_SCALE_SIZE);
|
||||
expect(statuses.filter((status) => status.state === "ACTIVE")).toHaveLength(
|
||||
FEATURE_SCALE_SIZE / 10,
|
||||
);
|
||||
expect(selectionElapsedMs).toBeLessThan(MAX_MEMBERSHIP_MS);
|
||||
expect(resolveElapsedMs).toBeLessThan(MAX_MEMBERSHIP_MS);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
defineAppError,
|
||||
isAppError,
|
||||
} from "../../../src/platform/errors/app-error.ts";
|
||||
|
||||
describe("AppError envelope", () => {
|
||||
it("recognizes feature-owned errors through the platform envelope", () => {
|
||||
const error = {
|
||||
kind: "payment.declined",
|
||||
category: "domain",
|
||||
severity: "warning",
|
||||
retryability: "never",
|
||||
} as const;
|
||||
|
||||
expect(isAppError(error)).toBe(true);
|
||||
});
|
||||
|
||||
it("represents an unknown feature kind without extending a central union", () => {
|
||||
const unknownFeatureError = defineAppError({
|
||||
kind: "brand-new-feature.quota-reached",
|
||||
category: "application",
|
||||
severity: "error",
|
||||
retryability: "policy",
|
||||
});
|
||||
expect(isAppError(unknownFeatureError)).toBe(true);
|
||||
expect(Object.isFrozen(unknownFeatureError)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ kind: "no-owner", category: "domain", severity: "warning", retryability: "never" }],
|
||||
[{ kind: "a.b", category: "vendor", severity: "warning", retryability: "never" }],
|
||||
[{ kind: "a.b", category: "domain", severity: "fatal", retryability: "never" }],
|
||||
[{ kind: "a.b", category: "domain", severity: "warning", retryability: "always" }],
|
||||
[{ kind: `a.${"x".repeat(80)}`, category: "domain", severity: "info", retryability: "never" }],
|
||||
[null],
|
||||
["payment.declined"],
|
||||
])("rejects a malformed envelope %#", (candidate) => {
|
||||
expect(isAppError(candidate)).toBe(false);
|
||||
});
|
||||
|
||||
it("never invokes accessors while classifying untrusted objects", () => {
|
||||
let invoked = false;
|
||||
const hostile = {
|
||||
category: "domain",
|
||||
severity: "warning",
|
||||
retryability: "never",
|
||||
get kind() {
|
||||
invoked = true;
|
||||
return "payment.declined";
|
||||
},
|
||||
};
|
||||
expect(isAppError(hostile)).toBe(false);
|
||||
expect(invoked).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ContextErrorBoundary } from "../../../src/platform/errors/context-error-boundary.tsx";
|
||||
import { FeatureErrorBoundary } from "../../../src/platform/errors/feature-error-boundary.tsx";
|
||||
|
||||
function ThrowsOnRender(): never {
|
||||
throw new Error("feature render failed");
|
||||
}
|
||||
|
||||
describe("ownership-aligned failure boundaries", () => {
|
||||
it("keeps sibling feature UI mounted when one feature throws during render", () => {
|
||||
vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
render(
|
||||
<ContextErrorBoundary>
|
||||
<FeatureErrorBoundary featureId="broken">
|
||||
<ThrowsOnRender />
|
||||
</FeatureErrorBoundary>
|
||||
<div>healthy-feature</div>
|
||||
</ContextErrorBoundary>,
|
||||
);
|
||||
|
||||
expect(screen.getByText("healthy-feature")).toBeInTheDocument();
|
||||
expect(screen.getByTestId("feature-fallback-broken")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps sibling contexts mounted when one context fails outside any feature boundary", () => {
|
||||
vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
render(
|
||||
<main>
|
||||
<ContextErrorBoundary contextId="commerce">
|
||||
<ThrowsOnRender />
|
||||
</ContextErrorBoundary>
|
||||
<ContextErrorBoundary contextId="account">
|
||||
<p>account-context</p>
|
||||
</ContextErrorBoundary>
|
||||
<nav>app-shell</nav>
|
||||
</main>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId("context-fallback-commerce")).toBeInTheDocument();
|
||||
expect(screen.getByText("account-context")).toBeInTheDocument();
|
||||
expect(screen.getByText("app-shell")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("reports once per contained failure and survives a throwing reporter", () => {
|
||||
vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const onError = vi.fn(() => {
|
||||
throw new Error("diagnostics down");
|
||||
});
|
||||
render(
|
||||
<FeatureErrorBoundary featureId="broken" onError={onError} fallback={<p>fallback</p>}>
|
||||
<ThrowsOnRender />
|
||||
</FeatureErrorBoundary>,
|
||||
);
|
||||
expect(onError).toHaveBeenCalledWith({ scope: "feature", ownerId: "broken" });
|
||||
expect(screen.getByText("fallback")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("clears a contained failure when its reset key changes", () => {
|
||||
vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
let shouldThrow = true;
|
||||
function Flaky() {
|
||||
if (shouldThrow) throw new Error("flaky");
|
||||
return <p>recovered</p>;
|
||||
}
|
||||
const view = render(
|
||||
<FeatureErrorBoundary featureId="flaky" resetKey="/a">
|
||||
<Flaky />
|
||||
</FeatureErrorBoundary>,
|
||||
);
|
||||
expect(screen.getByTestId("feature-fallback-flaky")).toBeInTheDocument();
|
||||
|
||||
shouldThrow = false;
|
||||
view.rerender(
|
||||
<FeatureErrorBoundary featureId="flaky" resetKey="/b">
|
||||
<Flaky />
|
||||
</FeatureErrorBoundary>,
|
||||
);
|
||||
expect(screen.getByText("recovered")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { platformErrorForOutcome } from "../../../src/adapters/http/platform-error-mapping.ts";
|
||||
import type { InstalledHttpContract } from "../../../src/contracts/external-contract-runtime.ts";
|
||||
import {
|
||||
mapTransportFailure,
|
||||
PLATFORM_ERRORS,
|
||||
} from "../../../src/platform/errors/platform-errors.ts";
|
||||
import { isAppError } from "../../../src/platform/errors/app-error.ts";
|
||||
import { RequestBudgetExceededError } from "../../../src/platform/traffic/request-budget.ts";
|
||||
import { ConcurrencyQueueFullError } from "../../../src/platform/traffic/concurrency-budget.ts";
|
||||
import { DeadlineExceededError } from "../../../src/platform/resilience/deadline.ts";
|
||||
import { JsonBudgetExceededError } from "../../../src/platform/validation/bounded-json.ts";
|
||||
import { TEST_LIST_HTTP_CONTRACT } from "../../helpers/external-contract-fixture.ts";
|
||||
import {
|
||||
networkFailure,
|
||||
scopeSnapshot,
|
||||
testExecutionContext,
|
||||
testExecutor,
|
||||
type Transport,
|
||||
} from "../../helpers/traffic-test-kit.ts";
|
||||
|
||||
const abortError = () => new DOMException("aborted", "AbortError");
|
||||
|
||||
describe("platform error normalization", () => {
|
||||
it("maps an abort caused by interaction cancellation to request.cancelled", () => {
|
||||
const error = mapTransportFailure(abortError(), { deadlineExpired: false });
|
||||
|
||||
expect(error).toMatchObject({
|
||||
kind: "request.cancelled",
|
||||
category: "transport",
|
||||
retryability: "never",
|
||||
});
|
||||
});
|
||||
|
||||
it("maps an abort caused by the deadline to request.timeout", () => {
|
||||
expect(mapTransportFailure(abortError(), { deadlineExpired: true }).kind).toBe(
|
||||
"request.timeout",
|
||||
);
|
||||
expect(
|
||||
mapTransportFailure(new DeadlineExceededError(10, 11), {
|
||||
deadlineExpired: false,
|
||||
}).kind,
|
||||
).toBe("request.timeout");
|
||||
});
|
||||
|
||||
it.each([
|
||||
[new TypeError("Failed to fetch"), "network.unavailable"],
|
||||
[new RequestBudgetExceededError(2), "traffic.budget-exceeded"],
|
||||
[new ConcurrencyQueueFullError(0), "traffic.budget-exceeded"],
|
||||
[new JsonBudgetExceededError("too-large", "x"), "response.too-large"],
|
||||
[new SyntaxError("Unexpected token"), "response.invalid"],
|
||||
["not even an error", "network.unavailable"],
|
||||
] as const)("maps %s to %s", (error, kind) => {
|
||||
expect(mapTransportFailure(error, { deadlineExpired: false }).kind).toBe(kind);
|
||||
});
|
||||
|
||||
it("keeps every platform error a valid, stable envelope", () => {
|
||||
for (const error of Object.values(PLATFORM_ERRORS)) {
|
||||
expect(isAppError(error)).toBe(true);
|
||||
}
|
||||
expect(Object.values(PLATFORM_ERRORS).map((error) => error.kind)).toEqual([
|
||||
"network.unavailable",
|
||||
"request.timeout",
|
||||
"request.cancelled",
|
||||
"response.too-large",
|
||||
"response.invalid",
|
||||
"traffic.budget-exceeded",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("V3 outcome normalization at the adapter boundary", () => {
|
||||
const TEST_QUERY = TEST_LIST_HTTP_CONTRACT as InstalledHttpContract<
|
||||
unknown,
|
||||
unknown,
|
||||
unknown
|
||||
>;
|
||||
|
||||
it("classifies a traffic-budget rejection as traffic.budget-exceeded", async () => {
|
||||
const transport = vi.fn<Transport>(networkFailure);
|
||||
const execution = testExecutionContext({ maxPhysicalRequests: 1, maxRetries: 0 });
|
||||
const executor = testExecutor(transport);
|
||||
const context = { routeId: "TEST_ROUTE", scope: scopeSnapshot(), execution };
|
||||
await executor.execute(TEST_QUERY, { limit: 1 }, context);
|
||||
const rejected = await executor.execute(TEST_QUERY, { limit: 1 }, context);
|
||||
|
||||
expect(platformErrorForOutcome(rejected)?.kind).toBe("traffic.budget-exceeded");
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ kind: "CANCELLED", effect: "NOT_STARTED" }, "request.cancelled"],
|
||||
[
|
||||
{ kind: "TRANSPORT_FAILURE", failure: { kind: "TIMEOUT", retryable: false }, effect: "NOT_STARTED" },
|
||||
"request.timeout",
|
||||
],
|
||||
[
|
||||
{ kind: "TRANSPORT_FAILURE", failure: { kind: "NETWORK_FAILURE", retryable: false }, effect: "NOT_STARTED" },
|
||||
"network.unavailable",
|
||||
],
|
||||
[
|
||||
{ kind: "CONTRACT_VIOLATION", violation: { kind: "RESPONSE_TOO_LARGE", operation: "RESPONSE" }, effect: "NOT_APPLICABLE" },
|
||||
"response.too-large",
|
||||
],
|
||||
[
|
||||
{ kind: "CONTRACT_VIOLATION", violation: { kind: "JSON_INVALID", operation: "RESPONSE" }, effect: "NOT_APPLICABLE" },
|
||||
"response.invalid",
|
||||
],
|
||||
] as const)("maps outcome %# to %s", (outcome, kind) => {
|
||||
expect(platformErrorForOutcome(outcome)?.kind).toBe(kind);
|
||||
});
|
||||
|
||||
it("leaves owner-interpreted outcomes to their owner", () => {
|
||||
expect(
|
||||
platformErrorForOutcome({ kind: "UNAUTHENTICATED", effect: "NOT_APPLICABLE" }),
|
||||
).toBeNull();
|
||||
expect(
|
||||
platformErrorForOutcome({
|
||||
kind: "CONTRACT_VIOLATION",
|
||||
violation: { kind: "SCOPE_FENCED", operation: "RESPONSE" },
|
||||
effect: "NOT_APPLICABLE",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createExecutionContext } from "../../../src/platform/execution/execution-context.ts";
|
||||
|
||||
const TRAFFIC = {
|
||||
maxPhysicalRequests: 4,
|
||||
maxConcurrentRequests: 2,
|
||||
maxRetries: 1,
|
||||
} as const;
|
||||
|
||||
describe("createExecutionContext", () => {
|
||||
it("creates one immutable root context with one abort signal and absolute deadline", () => {
|
||||
const now = 1_000;
|
||||
const context = createExecutionContext({
|
||||
interactionId: "interaction-1",
|
||||
startedAt: now,
|
||||
deadlineMs: 5_000,
|
||||
traffic: TRAFFIC,
|
||||
});
|
||||
|
||||
expect(context.interaction.deadlineAt).toBe(6_000);
|
||||
expect(context.cancellation.signal.aborted).toBe(false);
|
||||
expect(Object.isFrozen(context.interaction)).toBe(true);
|
||||
expect(Object.isFrozen(context)).toBe(true);
|
||||
});
|
||||
|
||||
it("derives a finite queue bound when the caller omits one", () => {
|
||||
const context = createExecutionContext({
|
||||
interactionId: "interaction-2",
|
||||
deadlineMs: 1_000,
|
||||
traffic: TRAFFIC,
|
||||
});
|
||||
|
||||
expect(context.traffic.concurrency.maxQueued).toBe(2);
|
||||
});
|
||||
|
||||
it("reports only the time left before the absolute deadline", () => {
|
||||
let now = 0;
|
||||
const context = createExecutionContext({
|
||||
interactionId: "interaction-3",
|
||||
deadlineMs: 1_000,
|
||||
traffic: TRAFFIC,
|
||||
clock: () => now,
|
||||
});
|
||||
|
||||
now = 400;
|
||||
expect(context.remainingMs()).toBe(600);
|
||||
now = 1_500;
|
||||
expect(context.remainingMs()).toBe(0);
|
||||
});
|
||||
|
||||
it("propagates an owner abort and cancel() to the interaction signal", () => {
|
||||
const owner = new AbortController();
|
||||
const linked = createExecutionContext({
|
||||
interactionId: "interaction-4",
|
||||
deadlineMs: 1_000,
|
||||
traffic: TRAFFIC,
|
||||
signal: owner.signal,
|
||||
});
|
||||
owner.abort();
|
||||
expect(linked.cancellation.signal.aborted).toBe(true);
|
||||
|
||||
const direct = createExecutionContext({
|
||||
interactionId: "interaction-5",
|
||||
deadlineMs: 1_000,
|
||||
traffic: TRAFFIC,
|
||||
});
|
||||
direct.cancellation.cancel();
|
||||
expect(direct.cancellation.signal.aborted).toBe(true);
|
||||
});
|
||||
|
||||
it("detaches from a long-lived owner signal when the interaction completes (Q-6.9-7)", () => {
|
||||
const owner = new AbortController();
|
||||
const remove = vi.spyOn(owner.signal, "removeEventListener");
|
||||
const context = createExecutionContext({
|
||||
interactionId: "interaction-7",
|
||||
deadlineMs: 1_000,
|
||||
traffic: TRAFFIC,
|
||||
signal: owner.signal,
|
||||
});
|
||||
|
||||
context.complete();
|
||||
context.complete();
|
||||
expect(remove).toHaveBeenCalledOnce();
|
||||
expect(remove).toHaveBeenCalledWith("abort", expect.any(Function));
|
||||
|
||||
// A finished interaction is not cancelled by its owner afterwards.
|
||||
owner.abort();
|
||||
expect(context.cancellation.signal.aborted).toBe(false);
|
||||
});
|
||||
|
||||
it.each([0, -1, Number.POSITIVE_INFINITY, 60_001, 1.5])(
|
||||
"rejects an unbounded or invalid deadline %s",
|
||||
(deadlineMs) => {
|
||||
expect(() =>
|
||||
createExecutionContext({
|
||||
interactionId: "interaction-6",
|
||||
deadlineMs,
|
||||
traffic: TRAFFIC,
|
||||
}),
|
||||
).toThrow(/deadline/);
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects an unsafe interaction id", () => {
|
||||
expect(() =>
|
||||
createExecutionContext({
|
||||
interactionId: "has spaces",
|
||||
deadlineMs: 1_000,
|
||||
traffic: TRAFFIC,
|
||||
}),
|
||||
).toThrow(/interaction id/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { loadRuntimeConfig } from "../../../src/bootstrap/load-runtime-config.ts";
|
||||
import { loadReleaseManifest } from "../../../src/bootstrap/load-release-manifest.ts";
|
||||
|
||||
type Surfaces = Record<string, { cacheControl?: string; path?: string; pathPattern?: string }>;
|
||||
|
||||
async function json<T>(relative: string): Promise<T> {
|
||||
return JSON.parse(await readFile(path.resolve(relative), "utf8")) as T;
|
||||
}
|
||||
|
||||
const policy = (await json<{ surfaces: Surfaces }>("config/hosting/cache-policy.json")).surfaces;
|
||||
const fixtureHeaders = (
|
||||
await json<{ responses: Record<string, Record<string, string>> }>(
|
||||
"config/hosting/response-headers.fixture.json",
|
||||
)
|
||||
).responses;
|
||||
|
||||
function directives(value: string | undefined): Set<string> {
|
||||
return new Set(
|
||||
(value ?? "")
|
||||
.split(",")
|
||||
.map((entry) => entry.trim().toLowerCase())
|
||||
.filter(Boolean),
|
||||
);
|
||||
}
|
||||
|
||||
describe("cache-policy contract for rolling releases", () => {
|
||||
it("serves hashed assets as immutable, year-long public cache entries", () => {
|
||||
expect(policy["hashedAsset"]?.cacheControl).toBe("public, max-age=31536000, immutable");
|
||||
expect(policy["hashedAsset"]?.pathPattern).toBe("/assets/*");
|
||||
expect(fixtureHeaders["hashedAsset"]?.["cache-control"]).toBe(
|
||||
"public, max-age=31536000, immutable",
|
||||
);
|
||||
});
|
||||
|
||||
it("revalidates HTML and never marks it immutable", () => {
|
||||
for (const value of [policy["index"]?.cacheControl, fixtureHeaders["index"]?.["cache-control"]]) {
|
||||
const parsed = directives(value);
|
||||
expect(parsed.has("immutable")).toBe(false);
|
||||
expect(parsed.has("no-cache") || parsed.has("no-store") || parsed.has("max-age=0")).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["runtimeConfig", "releaseManifest"])(
|
||||
"never lets %s be reused across release identity changes",
|
||||
(surface) => {
|
||||
expect(directives(policy[surface]?.cacheControl).has("no-store")).toBe(true);
|
||||
expect(directives(fixtureHeaders[surface]?.["cache-control"]).has("no-store")).toBe(true);
|
||||
expect(directives(policy[surface]?.cacheControl).has("immutable")).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it("requests runtime config and the release manifest with cache: no-store", async () => {
|
||||
const seen: RequestInit[] = [];
|
||||
const fetcher = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
|
||||
seen.push(init ?? {});
|
||||
return new Response("{}", { headers: { "content-type": "application/json" } });
|
||||
});
|
||||
const buildConfig = Object.freeze({
|
||||
buildId: "build-a",
|
||||
commitSha: "abc",
|
||||
routerBasePath: "/",
|
||||
runtimeConfigUrl: "/config.json",
|
||||
});
|
||||
await loadRuntimeConfig({ buildConfig, fetcher }).catch(() => undefined);
|
||||
await loadReleaseManifest(
|
||||
{
|
||||
build: buildConfig,
|
||||
config: {
|
||||
RELEASE_MANIFEST_URL: "/release-manifest.json",
|
||||
CONFIG_SCHEMA_VERSION: "2.0",
|
||||
} as never,
|
||||
configSchema: "V2",
|
||||
validationDurationMs: 0,
|
||||
},
|
||||
{ fetcher },
|
||||
).catch(() => undefined);
|
||||
|
||||
expect(seen).toHaveLength(2);
|
||||
expect(seen.every((init) => init.cache === "no-store")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
assertReleaseCoherent,
|
||||
checkReleaseCoherence,
|
||||
ReleaseMismatchError,
|
||||
} from "../../../src/platform/release/release-coherence.ts";
|
||||
|
||||
function identity(release: string) {
|
||||
return Object.freeze({
|
||||
buildId: `build-${release}`,
|
||||
releaseId: `release-${release}`,
|
||||
configSchemaVersion: "2.0",
|
||||
assetManifestHash: `assets-${release}`,
|
||||
});
|
||||
}
|
||||
|
||||
describe("assertReleaseCoherent", () => {
|
||||
it.each([
|
||||
["R10", "R10", "R10", true],
|
||||
["R10", "R11", "R10", false],
|
||||
["R10", "R10", "R11", false],
|
||||
["R11", "R11", "R11", true],
|
||||
["R11", "R10", "R10", false],
|
||||
["R10", "R11", "R11", false],
|
||||
])(
|
||||
"HTML %s config %s manifest %s => coherent=%s",
|
||||
(html, config, manifest, coherent) => {
|
||||
const run = () =>
|
||||
assertReleaseCoherent(
|
||||
identity(html),
|
||||
identity(config),
|
||||
identity(manifest),
|
||||
);
|
||||
|
||||
if (coherent) expect(run).not.toThrow();
|
||||
else expect(run).toThrow(/release.*mismatch/i);
|
||||
},
|
||||
);
|
||||
|
||||
it("reports the first incoherent field in the boot precedence order", () => {
|
||||
const result = checkReleaseCoherence({
|
||||
html: { buildId: "b1", assetManifestHash: "a1" },
|
||||
config: { buildId: "b1", configSchemaVersion: "2.0", releaseId: "r2" },
|
||||
manifest: {
|
||||
buildId: "b1",
|
||||
configSchemaVersion: "2.1",
|
||||
releaseId: "r1",
|
||||
assetManifestHash: "a2",
|
||||
},
|
||||
});
|
||||
expect(result).toEqual({
|
||||
coherent: false,
|
||||
field: "configSchemaVersion",
|
||||
sources: ["config", "manifest"],
|
||||
});
|
||||
});
|
||||
|
||||
it("compares only fields that two sources both carry", () => {
|
||||
expect(
|
||||
checkReleaseCoherence({
|
||||
html: { buildId: "b1" },
|
||||
config: { buildId: "b1" },
|
||||
manifest: { buildId: "b1", releaseId: "r1", assetManifestHash: "a" },
|
||||
}),
|
||||
).toEqual({ coherent: true });
|
||||
});
|
||||
|
||||
it("fails closed when HTML or manifest cannot name its build", () => {
|
||||
expect(() =>
|
||||
assertReleaseCoherent({}, identity("R10"), identity("R10")),
|
||||
).toThrow(ReleaseMismatchError);
|
||||
expect(() =>
|
||||
assertReleaseCoherent(identity("R10"), identity("R10"), { releaseId: "release-R10" }),
|
||||
).toThrow(ReleaseMismatchError);
|
||||
});
|
||||
|
||||
it("exposes which field and sources disagreed", () => {
|
||||
try {
|
||||
assertReleaseCoherent(identity("R10"), identity("R11"), identity("R10"));
|
||||
expect.unreachable();
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(ReleaseMismatchError);
|
||||
expect(error).toMatchObject({ field: "buildId", sources: ["html", "config"] });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,179 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createReleaseMismatchRecovery,
|
||||
type RecoveryMarkerStore,
|
||||
} from "../../../src/platform/release/release-mismatch-recovery.ts";
|
||||
import {
|
||||
createBootReleaseRecovery,
|
||||
decideBootFailure,
|
||||
releaseMismatchKey,
|
||||
} from "../../../src/bootstrap/boot-release-recovery.ts";
|
||||
import { ReleaseManifestError } from "../../../src/bootstrap/load-release-manifest.ts";
|
||||
import { BootConfigError } from "../../../src/bootstrap/load-runtime-config.ts";
|
||||
import { STORAGE_REGISTRY } from "../../../src/contracts/storage-keys.ts";
|
||||
|
||||
/** A Web Storage stand-in for the host's `sessionStorage`. */
|
||||
function sessionStorageLike() {
|
||||
const values = new Map<string, string>();
|
||||
return {
|
||||
values,
|
||||
getItem: (key: string) => values.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => void values.set(key, value),
|
||||
removeItem: (key: string) => void values.delete(key),
|
||||
};
|
||||
}
|
||||
|
||||
function markerStore(): RecoveryMarkerStore & { values: Map<string, string> } {
|
||||
const values = new Map<string, string>();
|
||||
return {
|
||||
values,
|
||||
read: () => values.get("marker") ?? null,
|
||||
write: (value) => void values.set("marker", value),
|
||||
clear: () => void values.delete("marker"),
|
||||
};
|
||||
}
|
||||
|
||||
describe("release mismatch recovery", () => {
|
||||
it("allows at most one automatic recovery attempt per release mismatch key", () => {
|
||||
const recovery = createReleaseMismatchRecovery(markerStore());
|
||||
|
||||
expect(recovery.decide("R10->R11")).toBe("reload-once");
|
||||
expect(recovery.decide("R10->R11")).toBe("show-failure");
|
||||
});
|
||||
|
||||
it("never reloads more than once however often the same mismatch repeats", () => {
|
||||
const recovery = createReleaseMismatchRecovery(markerStore());
|
||||
const decisions = Array.from({ length: 50 }, () => recovery.decide("R10->R11"));
|
||||
expect(decisions.filter((decision) => decision === "reload-once")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("clears the marker after a coherent boot", () => {
|
||||
const storage = markerStore();
|
||||
const recovery = createReleaseMismatchRecovery(storage);
|
||||
recovery.decide("R10->R11");
|
||||
recovery.markCoherentBoot();
|
||||
expect(storage.values.size).toBe(0);
|
||||
expect(recovery.decide("R10->R11")).toBe("reload-once");
|
||||
});
|
||||
|
||||
it("keeps a single bounded marker", () => {
|
||||
const storage = markerStore();
|
||||
const recovery = createReleaseMismatchRecovery(storage);
|
||||
expect(recovery.decide("x".repeat(10_000))).toBe("reload-once");
|
||||
expect(storage.values.size).toBe(1);
|
||||
expect([...storage.values.values()][0]?.length).toBeLessThan(300);
|
||||
});
|
||||
|
||||
it("allows one automatic reload per session within the TTL whatever the key", () => {
|
||||
const recovery = createReleaseMismatchRecovery(markerStore());
|
||||
expect(recovery.decide("A")).toBe("reload-once");
|
||||
expect(recovery.decide("B")).toBe("show-failure");
|
||||
expect(recovery.decide("A")).toBe("show-failure");
|
||||
});
|
||||
|
||||
it("cannot loop when a load balancer alternates the mismatch key", () => {
|
||||
const recovery = createReleaseMismatchRecovery(markerStore());
|
||||
const decisions = Array.from({ length: 20 }, (_, boot) =>
|
||||
recovery.decide(boot % 2 === 0 ? "build-R10:X:R11" : "build-R11:X:R10"),
|
||||
);
|
||||
expect(decisions.filter((decision) => decision === "reload-once")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("lets an expired marker recover again instead of blocking forever", () => {
|
||||
let now = 0;
|
||||
const recovery = createReleaseMismatchRecovery(markerStore(), {
|
||||
now: () => now,
|
||||
ttlMs: 1_000,
|
||||
});
|
||||
expect(recovery.decide("k")).toBe("reload-once");
|
||||
now = 500;
|
||||
expect(recovery.decide("k")).toBe("show-failure");
|
||||
now = 5_000;
|
||||
expect(recovery.decide("k")).toBe("reload-once");
|
||||
});
|
||||
|
||||
it("fails closed without working storage", () => {
|
||||
expect(createReleaseMismatchRecovery(null).decide("k")).toBe("show-failure");
|
||||
const throwing: RecoveryMarkerStore = {
|
||||
read: () => {
|
||||
throw new Error("denied");
|
||||
},
|
||||
write: () => {
|
||||
throw new Error("denied");
|
||||
},
|
||||
clear: () => {
|
||||
throw new Error("denied");
|
||||
},
|
||||
};
|
||||
const recovery = createReleaseMismatchRecovery(throwing);
|
||||
expect(recovery.decide("k")).toBe("show-failure");
|
||||
expect(() => recovery.markCoherentBoot()).not.toThrow();
|
||||
const dropping: RecoveryMarkerStore = {
|
||||
read: () => null,
|
||||
write: () => {},
|
||||
clear: () => {},
|
||||
};
|
||||
expect(createReleaseMismatchRecovery(dropping).decide("k")).toBe("show-failure");
|
||||
});
|
||||
});
|
||||
|
||||
describe("boot release recovery wiring", () => {
|
||||
it("keys only release mismatches, never other boot failures", () => {
|
||||
const mismatch = new ReleaseManifestError("MANIFEST_RELEASE_MISMATCH", {
|
||||
buildId: "build-R10",
|
||||
releaseId: "release-R11",
|
||||
});
|
||||
expect(releaseMismatchKey(mismatch)).toBe(
|
||||
"build-R10:MANIFEST_RELEASE_MISMATCH:release-R11",
|
||||
);
|
||||
expect(
|
||||
releaseMismatchKey(new BootConfigError("CONFIG_BUILD_MISMATCH", { buildId: "build-R10" })),
|
||||
).toBe("build-R10:CONFIG_BUILD_MISMATCH:-");
|
||||
expect(
|
||||
releaseMismatchKey(new ReleaseManifestError("MANIFEST_TIMEOUT", { buildId: "b" })),
|
||||
).toBeNull();
|
||||
expect(
|
||||
releaseMismatchKey(new BootConfigError("CONFIG_FETCH_FAILED", { buildId: "b" })),
|
||||
).toBeNull();
|
||||
expect(releaseMismatchKey(new Error("boom"))).toBeNull();
|
||||
});
|
||||
|
||||
it("uses the registered RELEASE_MISMATCH_RECOVERY session key", () => {
|
||||
const storage = sessionStorageLike();
|
||||
const recovery = createBootReleaseRecovery({ sessionStorage: storage });
|
||||
const mismatch = new ReleaseManifestError("MANIFEST_BUILD_MISMATCH", { buildId: "build-R10" });
|
||||
|
||||
expect(decideBootFailure(mismatch, recovery)).toBe("reload-once");
|
||||
expect([...storage.values.keys()]).toEqual([
|
||||
STORAGE_REGISTRY.RELEASE_MISMATCH_RECOVERY.physicalKey,
|
||||
]);
|
||||
expect(decideBootFailure(mismatch, recovery)).toBe("show-failure");
|
||||
expect(
|
||||
decideBootFailure(new ReleaseManifestError("MANIFEST_TIMEOUT", { buildId: "b" }), recovery),
|
||||
).toBe("show-failure");
|
||||
});
|
||||
|
||||
it("remembers the attempt across the reload itself (a fresh boot, same session)", () => {
|
||||
const storage = sessionStorageLike();
|
||||
const mismatch = new ReleaseManifestError("MANIFEST_BUILD_MISMATCH", { buildId: "build-R10" });
|
||||
|
||||
expect(decideBootFailure(mismatch, createBootReleaseRecovery({ sessionStorage: storage }))).toBe(
|
||||
"reload-once",
|
||||
);
|
||||
const afterReload = createBootReleaseRecovery({ sessionStorage: storage });
|
||||
expect(decideBootFailure(mismatch, afterReload)).toBe("show-failure");
|
||||
afterReload.markCoherentBoot();
|
||||
expect(storage.values.size).toBe(0);
|
||||
});
|
||||
|
||||
it("degrades to show-failure when the host has no session storage", () => {
|
||||
const recovery = createBootReleaseRecovery({});
|
||||
expect(
|
||||
decideBootFailure(
|
||||
new ReleaseManifestError("MANIFEST_BUILD_MISMATCH", { buildId: "b" }),
|
||||
recovery,
|
||||
),
|
||||
).toBe("show-failure");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
DeadlineExceededError,
|
||||
remainingDeadlineMs,
|
||||
} from "../../../src/platform/resilience/deadline.ts";
|
||||
|
||||
describe("remainingDeadlineMs", () => {
|
||||
it("returns only time remaining from the original absolute deadline", () => {
|
||||
expect(remainingDeadlineMs(6_000, 1_000)).toBe(5_000);
|
||||
expect(remainingDeadlineMs(6_000, 5_500)).toBe(500);
|
||||
expect(() => remainingDeadlineMs(6_000, 6_001)).toThrow(DeadlineExceededError);
|
||||
});
|
||||
|
||||
it("treats the exact deadline instant as zero remaining", () => {
|
||||
expect(remainingDeadlineMs(6_000, 6_000)).toBe(0);
|
||||
});
|
||||
|
||||
it("rejects non-finite clock values", () => {
|
||||
expect(() => remainingDeadlineMs(Number.POSITIVE_INFINITY, 0)).toThrow(TypeError);
|
||||
expect(() => remainingDeadlineMs(10, Number.NaN)).toThrow(TypeError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createRetryBudget } from "../../../src/platform/resilience/retry-budget.ts";
|
||||
|
||||
describe("createRetryBudget", () => {
|
||||
it("shares retry capacity across independent requests in the same interaction", () => {
|
||||
const budget = createRetryBudget(1);
|
||||
|
||||
expect(budget.tryConsume("request-a")).toBe(true);
|
||||
expect(budget.tryConsume("request-b")).toBe(false);
|
||||
expect(budget.consumed).toBe(1);
|
||||
});
|
||||
|
||||
it("does not reset per request id", () => {
|
||||
const budget = createRetryBudget(2);
|
||||
expect(budget.tryConsume("a")).toBe(true);
|
||||
expect(budget.tryConsume("b")).toBe(true);
|
||||
expect(budget.tryConsume("a")).toBe(false);
|
||||
expect(budget.tryConsume("c")).toBe(false);
|
||||
});
|
||||
|
||||
it("supports a zero-retry interaction", () => {
|
||||
expect(createRetryBudget(0).tryConsume("a")).toBe(false);
|
||||
});
|
||||
|
||||
it.each([-1, Number.POSITIVE_INFINITY, 0.5])("rejects invalid maximum %s", (maximum) => {
|
||||
expect(() => createRetryBudget(maximum)).toThrow(TypeError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { defineDeployableAppModule } from "../../../src/apps/deployable-app-module.ts";
|
||||
import { defineBoundedContextModule } from "../../../src/contexts/bounded-context-module.ts";
|
||||
import { createAppRouteModules } from "../../../src/platform/routing/context-route-module.ts";
|
||||
|
||||
function contextWithLoader(
|
||||
id: string,
|
||||
loadRoutes: () => Promise<readonly []>,
|
||||
) {
|
||||
return defineBoundedContextModule({
|
||||
id,
|
||||
features: [],
|
||||
budget: { maxFeatures: 200 },
|
||||
route: { path: `${id}/*`, loadRoutes },
|
||||
});
|
||||
}
|
||||
|
||||
describe("context route module", () => {
|
||||
it("creates only direct context entries at app boot without loading routes", () => {
|
||||
let commerceLoads = 0;
|
||||
let accountLoads = 0;
|
||||
const commerce = contextWithLoader("commerce", async () => {
|
||||
commerceLoads += 1;
|
||||
return [];
|
||||
});
|
||||
const account = contextWithLoader("account", async () => {
|
||||
accountLoads += 1;
|
||||
return [];
|
||||
});
|
||||
const app = defineDeployableAppModule({
|
||||
id: "customer",
|
||||
contexts: [commerce, account],
|
||||
budget: { maxContexts: 20 },
|
||||
});
|
||||
|
||||
expect(createAppRouteModules(app).map((module) => module.id)).toEqual([
|
||||
"commerce",
|
||||
"account",
|
||||
]);
|
||||
expect(commerceLoads).toBe(0);
|
||||
expect(accountLoads).toBe(0);
|
||||
});
|
||||
|
||||
it("single-flights and caches one context route composition", async () => {
|
||||
let loadCount = 0;
|
||||
const context = contextWithLoader("commerce", async () => {
|
||||
loadCount += 1;
|
||||
await Promise.resolve();
|
||||
return [];
|
||||
});
|
||||
const app = defineDeployableAppModule({
|
||||
id: "customer",
|
||||
contexts: [context],
|
||||
budget: { maxContexts: 20 },
|
||||
});
|
||||
const [routeModule] = createAppRouteModules(app);
|
||||
expect(routeModule).toBeDefined();
|
||||
|
||||
const [first, second] = await Promise.all([
|
||||
routeModule!.loadRoutes(),
|
||||
routeModule!.loadRoutes(),
|
||||
]);
|
||||
const third = await routeModule!.loadRoutes();
|
||||
|
||||
expect(loadCount).toBe(1);
|
||||
expect(first).toBe(second);
|
||||
expect(third).toBe(first);
|
||||
expect(Object.isFrozen(first)).toBe(true);
|
||||
});
|
||||
|
||||
it("allows a failed context route load to retry", async () => {
|
||||
let loadCount = 0;
|
||||
const context = contextWithLoader("commerce", async () => {
|
||||
loadCount += 1;
|
||||
if (loadCount === 1) throw new Error("chunk unavailable");
|
||||
return [];
|
||||
});
|
||||
const app = defineDeployableAppModule({
|
||||
id: "customer",
|
||||
contexts: [context],
|
||||
budget: { maxContexts: 20 },
|
||||
});
|
||||
const [routeModule] = createAppRouteModules(app);
|
||||
expect(routeModule).toBeDefined();
|
||||
|
||||
await expect(routeModule!.loadRoutes()).rejects.toThrow("chunk unavailable");
|
||||
await expect(routeModule!.loadRoutes()).resolves.toEqual([]);
|
||||
expect(loadCount).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,190 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
DEFAULT_TELEMETRY_PAYLOAD_BUDGET,
|
||||
REDACTED,
|
||||
redactTelemetryPayload,
|
||||
TRUNCATED,
|
||||
} from "../../../src/platform/telemetry/redact-telemetry.ts";
|
||||
|
||||
describe("redactTelemetryPayload", () => {
|
||||
it.each([
|
||||
"password",
|
||||
"authorization",
|
||||
"cookie",
|
||||
"accessToken",
|
||||
"refreshToken",
|
||||
"access_token",
|
||||
"Set-Cookie",
|
||||
"apiKey",
|
||||
"clientSecret",
|
||||
])("redacts %s recursively", (secretKey) => {
|
||||
const input = { nested: { [secretKey]: "secret", safe: "ok" } };
|
||||
const result = redactTelemetryPayload(input);
|
||||
|
||||
expect(JSON.stringify(result)).not.toContain("secret");
|
||||
expect(result).toMatchObject({ nested: { safe: "ok" } });
|
||||
});
|
||||
|
||||
it("redacts credential-shaped values under innocent keys", () => {
|
||||
const result = redactTelemetryPayload({
|
||||
note: "Bearer abc.def.ghi",
|
||||
jwt: "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.sig",
|
||||
list: ["Basic dXNlcjpwYXNz"],
|
||||
});
|
||||
expect(result).toEqual({ note: REDACTED, jwt: REDACTED, list: [REDACTED] });
|
||||
});
|
||||
|
||||
it("keeps legitimate telemetry values and innocent keys untouched", () => {
|
||||
const legitimate = {
|
||||
reason: "REQUEST_TIMEOUT",
|
||||
operation: "LIST_ORDER_ITEMS",
|
||||
routeId: "orders.items.detail",
|
||||
featureId: "order-feature",
|
||||
resourceId: "01J8Z3K7Q9W4N2B6C5D1E0F7GH",
|
||||
uuid: "3f2a9c1e-5b7d-4e8f-9a0b-1c2d3e4f5a6b",
|
||||
traceHex: "4bf92f3577b34da6a3ce929d0e0e4736",
|
||||
plan: "BASIC_PLAN",
|
||||
dependency: "react@19.1.0",
|
||||
path: "/api/resources?limit=20&cursor=c1#top",
|
||||
message: "error code=REQUEST_TIMEOUT after 3 attempts",
|
||||
status: 404,
|
||||
durationMs: 12.5,
|
||||
retried: false,
|
||||
spinner: "visible",
|
||||
author: "system",
|
||||
compass: "north",
|
||||
opinion: "none",
|
||||
shipping: "standard",
|
||||
isPinned: true,
|
||||
code: "E_CONFLICT",
|
||||
key: "sort-order",
|
||||
};
|
||||
expect(redactTelemetryPayload(legitimate)).toEqual(legitimate);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"pwd",
|
||||
"pass",
|
||||
"auth",
|
||||
"otp",
|
||||
"pin",
|
||||
"userPwd",
|
||||
"pin_code",
|
||||
"PINCode",
|
||||
"x-otp",
|
||||
"authHeader",
|
||||
"passcode",
|
||||
])("redacts the short secret key %s as a whole key token", (secretKey) => {
|
||||
const result = redactTelemetryPayload({ [secretKey]: "s3cr3t", safe: "ok" });
|
||||
expect(result).toEqual({ safe: "ok" });
|
||||
});
|
||||
|
||||
it("redacts credentials in the middle of a string", () => {
|
||||
expect(
|
||||
redactTelemetryPayload({
|
||||
header: "request failed: Authorization: Bearer abc",
|
||||
basic: "proxy said Basic dXNlcjpwYXNz was rejected",
|
||||
jwt: "retry with eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJl now",
|
||||
}),
|
||||
).toEqual({
|
||||
header: `request failed: Authorization: ${REDACTED}`,
|
||||
basic: `proxy said ${REDACTED} was rejected`,
|
||||
jwt: `retry with ${REDACTED} now`,
|
||||
});
|
||||
});
|
||||
|
||||
it("masks secret URL query and fragment parameters", () => {
|
||||
expect(
|
||||
redactTelemetryPayload(
|
||||
"GET https://api.example.com/cb?code=abc123&state=xyz&access_token=tok456&key=k1#id_token=jwt789",
|
||||
),
|
||||
).toBe(
|
||||
`GET https://api.example.com/cb?code=${REDACTED}&state=xyz&access_token=${REDACTED}&key=${REDACTED}#id_token=${REDACTED}`,
|
||||
);
|
||||
expect(redactTelemetryPayload("/login?user=a&password=hunter2&otp=123456")).toBe(
|
||||
`/login?user=a&password=${REDACTED}&otp=${REDACTED}`,
|
||||
);
|
||||
});
|
||||
|
||||
it("masks email addresses", () => {
|
||||
expect(
|
||||
redactTelemetryPayload({ note: "invite failed for jane.doe+test@example.co.uk twice" }),
|
||||
).toEqual({ note: `invite failed for ${REDACTED} twice` });
|
||||
});
|
||||
|
||||
it("does not leak a secret cut in half by truncation", () => {
|
||||
const budget = { ...DEFAULT_TELEMETRY_PAYLOAD_BUDGET, maxStringLength: 32 };
|
||||
const cut = redactTelemetryPayload(
|
||||
{
|
||||
email: `${"x".repeat(20)} jane.doe@example.com`,
|
||||
query: `/cb${"x".repeat(10)}?access_token=abcdefghijklmnopqrstuvwxyz`,
|
||||
bearer: `${"x".repeat(20)} Bearer abcdefghijklmnopqrstuvwxyz`,
|
||||
},
|
||||
budget,
|
||||
);
|
||||
expect(JSON.stringify(cut)).not.toMatch(/jane|abcd/u);
|
||||
expect(JSON.stringify(cut)).toContain(TRUNCATED);
|
||||
});
|
||||
|
||||
it("never invokes getters, toJSON or foreign prototypes", () => {
|
||||
let invoked = false;
|
||||
class Carrier {
|
||||
visible = "kept";
|
||||
toJSON() {
|
||||
invoked = true;
|
||||
return { leaked: true };
|
||||
}
|
||||
}
|
||||
const hostile = Object.defineProperty(new Carrier(), "computed", {
|
||||
enumerable: true,
|
||||
get() {
|
||||
invoked = true;
|
||||
return "computed";
|
||||
},
|
||||
});
|
||||
|
||||
const result = redactTelemetryPayload({ hostile });
|
||||
|
||||
expect(invoked).toBe(false);
|
||||
expect(result).toEqual({ hostile: { visible: "kept" } });
|
||||
expect(Object.getPrototypeOf((result as { hostile: object }).hostile)).toBe(
|
||||
Object.prototype,
|
||||
);
|
||||
});
|
||||
|
||||
it("bounds depth, width, array length and string length", () => {
|
||||
let deep: unknown = "leaf";
|
||||
for (let depth = 0; depth < 50; depth += 1) deep = { next: deep };
|
||||
const wide = Object.fromEntries(
|
||||
Array.from({ length: 500 }, (_, index) => [`k${index}`, index]),
|
||||
);
|
||||
const result = redactTelemetryPayload(
|
||||
{ deep, wide, list: Array.from({ length: 1_000 }, (_, i) => i), text: "x".repeat(5_000) },
|
||||
{ maxDepth: 4, maxKeys: 10, maxArrayItems: 5, maxStringLength: 16 },
|
||||
) as Record<string, unknown>;
|
||||
|
||||
expect(JSON.stringify(result)).toContain(TRUNCATED);
|
||||
expect(Object.keys(result["wide"] as object).length).toBeLessThanOrEqual(10);
|
||||
expect(result["list"]).toHaveLength(5);
|
||||
expect((result["text"] as string).length).toBeLessThanOrEqual(16 + TRUNCATED.length);
|
||||
});
|
||||
|
||||
it("does not let prototype keys pollute the copy", () => {
|
||||
const payload = JSON.parse('{"__proto__":{"polluted":true},"ok":1}') as unknown;
|
||||
const result = redactTelemetryPayload(payload) as Record<string, unknown>;
|
||||
expect(result).toEqual({ ok: 1 });
|
||||
expect(({} as Record<string, unknown>)["polluted"]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("normalizes non-JSON leaves", () => {
|
||||
expect(
|
||||
redactTelemetryPayload({
|
||||
n: Number.NaN,
|
||||
f: () => 1,
|
||||
u: undefined,
|
||||
b: 10n,
|
||||
}),
|
||||
).toEqual({ n: null, f: null, u: null, b: null });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTelemetryBuffer } from "../../../src/platform/telemetry/telemetry-buffer.ts";
|
||||
import type { TelemetryEvent } from "../../../src/platform/telemetry/telemetry-event.ts";
|
||||
import { createDeterministicSampler } from "../../../src/platform/telemetry/telemetry-sampler.ts";
|
||||
|
||||
const infoEvent = (id: string): TelemetryEvent<unknown> => ({
|
||||
kind: "test.info",
|
||||
severity: "info",
|
||||
payload: { id },
|
||||
});
|
||||
const criticalEvent = (id: string): TelemetryEvent<unknown> => ({
|
||||
kind: "test.critical",
|
||||
severity: "critical",
|
||||
payload: { id },
|
||||
});
|
||||
|
||||
describe("createDeterministicSampler", () => {
|
||||
it("makes the same sampling decision for the same stable key", () => {
|
||||
const sampler = createDeterministicSampler({ rate: 0.1 });
|
||||
|
||||
expect(sampler.keep("interaction-123")).toBe(sampler.keep("interaction-123"));
|
||||
});
|
||||
|
||||
it("approximates the configured rate over many keys", () => {
|
||||
const sampler = createDeterministicSampler({ rate: 0.1 });
|
||||
let kept = 0;
|
||||
for (let i = 0; i < 10_000; i += 1) if (sampler.keep(`interaction-${i}`)) kept += 1;
|
||||
expect(kept).toBeGreaterThan(700);
|
||||
expect(kept).toBeLessThan(1_300);
|
||||
});
|
||||
|
||||
it("is exact at the edges and rejects invalid rates", () => {
|
||||
expect(createDeterministicSampler({ rate: 1 }).keep("x")).toBe(true);
|
||||
expect(createDeterministicSampler({ rate: 0 }).keep("x")).toBe(false);
|
||||
expect(() => createDeterministicSampler({ rate: 1.5 })).toThrow(TypeError);
|
||||
expect(() => createDeterministicSampler({ rate: Number.NaN })).toThrow(TypeError);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createTelemetryBuffer", () => {
|
||||
it("never exceeds event or byte ceilings", () => {
|
||||
const buffer = createTelemetryBuffer({
|
||||
maxEvents: 2,
|
||||
maxBytes: 1_024,
|
||||
});
|
||||
|
||||
buffer.push(infoEvent("a"));
|
||||
buffer.push(infoEvent("b"));
|
||||
buffer.push(criticalEvent("c"));
|
||||
|
||||
expect(buffer.size).toBeLessThanOrEqual(2);
|
||||
expect(buffer.bytes).toBeLessThanOrEqual(1_024);
|
||||
expect(buffer.items.some((item) => item.severity === "critical")).toBe(true);
|
||||
});
|
||||
|
||||
it("drops an incoming low-severity event rather than evicting a severe one", () => {
|
||||
const buffer = createTelemetryBuffer({ maxEvents: 1, maxBytes: 1_024 });
|
||||
buffer.push(criticalEvent("keep"));
|
||||
expect(buffer.push(infoEvent("late"))).toBe(false);
|
||||
expect(buffer.items).toEqual([criticalEvent("keep")]);
|
||||
expect(buffer.dropped).toBe(1);
|
||||
});
|
||||
|
||||
it("evicts nothing when eviction cannot make room for the incoming event (Q-6.9-11)", () => {
|
||||
const at = (severity: TelemetryEvent<unknown>["severity"]) => ({
|
||||
kind: `test.${severity}`,
|
||||
severity,
|
||||
});
|
||||
const evicted: string[] = [];
|
||||
const buffer = createTelemetryBuffer({
|
||||
maxEvents: 10,
|
||||
maxBytes: 300,
|
||||
onEvict: (entry) => evicted.push(entry.event.severity),
|
||||
});
|
||||
buffer.push(at("info"), 50);
|
||||
buffer.push(at("error"), 240);
|
||||
|
||||
// Dropping the info event frees 50 bytes; the warning needs 100.
|
||||
expect(buffer.push(at("warning"), 100)).toBe(false);
|
||||
expect(buffer.items.map((item) => item.severity)).toEqual(["info", "error"]);
|
||||
expect(buffer.bytes).toBe(290);
|
||||
expect(buffer.dropped).toBe(1);
|
||||
expect(evicted).toEqual([]);
|
||||
});
|
||||
|
||||
it("evicts the oldest event of the same severity to admit a new one", () => {
|
||||
const buffer = createTelemetryBuffer({ maxEvents: 2, maxBytes: 1_024 });
|
||||
buffer.push(infoEvent("a"));
|
||||
buffer.push(infoEvent("b"));
|
||||
expect(buffer.push(infoEvent("c"))).toBe(true);
|
||||
expect(buffer.items).toEqual([infoEvent("b"), infoEvent("c")]);
|
||||
expect(buffer.dropped).toBe(1);
|
||||
});
|
||||
|
||||
it("enforces the byte ceiling independently of the event count", () => {
|
||||
const buffer = createTelemetryBuffer({ maxEvents: 100, maxBytes: 200 });
|
||||
for (let i = 0; i < 50; i += 1) buffer.push(infoEvent(`event-${i}`));
|
||||
expect(buffer.bytes).toBeLessThanOrEqual(200);
|
||||
expect(buffer.size).toBeLessThan(50);
|
||||
});
|
||||
|
||||
it("rejects a single event larger than the byte ceiling", () => {
|
||||
const buffer = createTelemetryBuffer({ maxEvents: 10, maxBytes: 64 });
|
||||
expect(buffer.push(infoEvent("x".repeat(100)))).toBe(false);
|
||||
expect(buffer.size).toBe(0);
|
||||
});
|
||||
|
||||
it("hands batches out in FIFO order and releases their bytes", () => {
|
||||
const buffer = createTelemetryBuffer({ maxEvents: 10, maxBytes: 10_000 });
|
||||
buffer.push(infoEvent("a"));
|
||||
buffer.push(infoEvent("b"));
|
||||
buffer.push(infoEvent("c"));
|
||||
const batch = buffer.take(2);
|
||||
expect(batch.map((entry) => entry.event)).toEqual([infoEvent("a"), infoEvent("b")]);
|
||||
expect(buffer.size).toBe(1);
|
||||
buffer.take(10);
|
||||
expect(buffer.bytes).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { TelemetryDeduplicator } from "../../../src/platform/telemetry/telemetry-deduplicator.ts";
|
||||
import {
|
||||
fingerprintTelemetryEvent,
|
||||
stableSerialize,
|
||||
} from "../../../src/platform/telemetry/telemetry-fingerprint.ts";
|
||||
|
||||
const FINGERPRINT = fingerprintTelemetryEvent({
|
||||
kind: "catalog.load.failed",
|
||||
severity: "error",
|
||||
payload: { reason: "timeout" },
|
||||
});
|
||||
|
||||
describe("fingerprintTelemetryEvent", () => {
|
||||
it("ignores request-cardinality identifiers and key order", () => {
|
||||
const a = fingerprintTelemetryEvent({
|
||||
kind: "catalog.load.failed",
|
||||
severity: "error",
|
||||
interactionId: "i-1",
|
||||
traceId: "4bf92f3577b34da6a3ce929d0e0e4736",
|
||||
payload: { reason: "timeout", operation: "list" },
|
||||
});
|
||||
const b = fingerprintTelemetryEvent({
|
||||
kind: "catalog.load.failed",
|
||||
severity: "error",
|
||||
interactionId: "i-2",
|
||||
payload: { operation: "list", reason: "timeout" },
|
||||
});
|
||||
expect(a).toBe(b);
|
||||
expect(a).toMatch(/^[0-9a-f]{16}$/);
|
||||
});
|
||||
|
||||
it("separates distinct failures", () => {
|
||||
expect(
|
||||
fingerprintTelemetryEvent({ kind: "a.b", severity: "error", payload: { reason: "x" } }),
|
||||
).not.toBe(
|
||||
fingerprintTelemetryEvent({ kind: "a.b", severity: "error", payload: { reason: "y" } }),
|
||||
);
|
||||
});
|
||||
|
||||
it("serializes structure unambiguously", () => {
|
||||
expect(stableSerialize({ b: [1, { c: "x" }], a: null })).toBe(
|
||||
'{"a":null,"b":[1,{"c":"x"}]}',
|
||||
);
|
||||
expect(stableSerialize(["]", ","])).toBe('["]",","]');
|
||||
});
|
||||
});
|
||||
|
||||
describe("TelemetryDeduplicator", () => {
|
||||
it("collapses repeated identical failures into one active fingerprint entry", () => {
|
||||
const dedup = new TelemetryDeduplicator({ maxEntries: 100, windowMs: 60_000 });
|
||||
|
||||
for (let i = 0; i < 10_000; i += 1) {
|
||||
dedup.record(FINGERPRINT, i);
|
||||
}
|
||||
|
||||
expect(dedup.size).toBe(1);
|
||||
expect(dedup.count(FINGERPRINT)).toBe(10_000);
|
||||
});
|
||||
|
||||
it("never retains more than maxEntries fingerprints", () => {
|
||||
const dedup = new TelemetryDeduplicator({ maxEntries: 2, windowMs: 60_000 });
|
||||
dedup.record("a", 1);
|
||||
dedup.record("b", 2);
|
||||
dedup.record("c", 3);
|
||||
|
||||
expect(dedup.size).toBe(2);
|
||||
});
|
||||
|
||||
it("admits a fingerprint again once its window expires", () => {
|
||||
const dedup = new TelemetryDeduplicator({ maxEntries: 10, windowMs: 1_000 });
|
||||
expect(dedup.record("a", 0)).toBe(true);
|
||||
expect(dedup.record("a", 999)).toBe(false);
|
||||
expect(dedup.record("a", 1_000)).toBe(true);
|
||||
expect(dedup.count("a")).toBe(1);
|
||||
});
|
||||
|
||||
it("evicts the least recently seen fingerprint under pressure", () => {
|
||||
const dedup = new TelemetryDeduplicator({ maxEntries: 2, windowMs: 60_000 });
|
||||
dedup.record("a", 1);
|
||||
dedup.record("b", 2);
|
||||
dedup.record("a", 3); // refresh a
|
||||
dedup.record("c", 4); // evicts b
|
||||
expect(dedup.count("a")).toBe(2);
|
||||
expect(dedup.count("b")).toBe(0);
|
||||
expect(dedup.count("c")).toBe(1);
|
||||
});
|
||||
|
||||
it("rejects unbounded configuration", () => {
|
||||
expect(() => new TelemetryDeduplicator({ maxEntries: Infinity, windowMs: 1 })).toThrow(TypeError);
|
||||
expect(() => new TelemetryDeduplicator({ maxEntries: 1, windowMs: 0 })).toThrow(TypeError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,267 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createTelemetryPipeline,
|
||||
DEFAULT_TELEMETRY_PIPELINE_BUDGET,
|
||||
type TelemetryBatchItem,
|
||||
type TelemetryPipelineBudget,
|
||||
} from "../../../src/platform/telemetry/telemetry-pipeline.ts";
|
||||
import type { TelemetryEvent } from "../../../src/platform/telemetry/telemetry-event.ts";
|
||||
|
||||
const TEST_TELEMETRY_BUDGET: TelemetryPipelineBudget = {
|
||||
...DEFAULT_TELEMETRY_PIPELINE_BUDGET,
|
||||
maxBufferedEvents: 50,
|
||||
maxSendsPerMinute: 10,
|
||||
};
|
||||
|
||||
const TEST_EVENT: TelemetryEvent<unknown> = {
|
||||
kind: "catalog.load.failed",
|
||||
severity: "error",
|
||||
featureId: "catalog",
|
||||
payload: { reason: "REQUEST_TIMEOUT" },
|
||||
};
|
||||
const REPEATED_ERROR = TEST_EVENT;
|
||||
|
||||
/** Runs scheduled work synchronously-ish and keeps timers in the test's hand. */
|
||||
function manualScheduling() {
|
||||
const timers: Array<() => void> = [];
|
||||
return {
|
||||
schedule: (callback: () => void) => queueMicrotask(callback),
|
||||
setTimer: (callback: () => void) => {
|
||||
timers.push(callback);
|
||||
return timers.length;
|
||||
},
|
||||
clearTimer: () => {},
|
||||
runTimers() {
|
||||
for (const callback of timers.splice(0)) callback();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("createTelemetryPipeline", () => {
|
||||
it("does not reject business flow when telemetry transport fails", async () => {
|
||||
const pipeline = createTelemetryPipeline({
|
||||
transport: {
|
||||
async send() {
|
||||
throw new Error("collector unavailable");
|
||||
},
|
||||
},
|
||||
budget: TEST_TELEMETRY_BUDGET,
|
||||
});
|
||||
|
||||
await expect(pipeline.emit(TEST_EVENT)).resolves.toBeUndefined();
|
||||
await expect(pipeline.flush()).resolves.toBeUndefined();
|
||||
expect(pipeline.stats().failedSends).toBe(1);
|
||||
});
|
||||
|
||||
it("does not throw when the transport throws synchronously", async () => {
|
||||
const pipeline = createTelemetryPipeline({
|
||||
transport: {
|
||||
send() {
|
||||
throw new Error("sdk crashed");
|
||||
},
|
||||
},
|
||||
budget: TEST_TELEMETRY_BUDGET,
|
||||
});
|
||||
await expect(pipeline.emit(TEST_EVENT)).resolves.toBeUndefined();
|
||||
await expect(pipeline.flush()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("bounds network sends during a repeated error storm", async () => {
|
||||
const send = vi.fn().mockResolvedValue(undefined);
|
||||
const pipeline = createTelemetryPipeline({
|
||||
transport: { send },
|
||||
budget: { ...TEST_TELEMETRY_BUDGET, maxSendsPerMinute: 10 },
|
||||
});
|
||||
|
||||
for (let i = 0; i < 100_000; i += 1) {
|
||||
await pipeline.emit(REPEATED_ERROR);
|
||||
}
|
||||
|
||||
await pipeline.flush();
|
||||
expect(send.mock.calls.length).toBeLessThanOrEqual(10);
|
||||
expect(pipeline.stats().deduplicated).toBe(99_999);
|
||||
});
|
||||
|
||||
it("reports how many occurrences a delivered fingerprint collapsed", async () => {
|
||||
const batches: TelemetryBatchItem[][] = [];
|
||||
let now = 0;
|
||||
const pipeline = createTelemetryPipeline({
|
||||
transport: { send: (batch) => void batches.push([...batch]) },
|
||||
budget: TEST_TELEMETRY_BUDGET,
|
||||
now: () => now,
|
||||
schedule: () => {},
|
||||
});
|
||||
for (let i = 0; i < 25; i += 1) {
|
||||
now = i;
|
||||
await pipeline.emit(REPEATED_ERROR);
|
||||
}
|
||||
await pipeline.flush();
|
||||
expect(batches.flat()).toHaveLength(1);
|
||||
expect(batches[0]?.[0]?.occurrences).toBe(25);
|
||||
});
|
||||
|
||||
it("delivers every duplicate as occurrences with the default microtask scheduler", async () => {
|
||||
const batches: TelemetryBatchItem[][] = [];
|
||||
const pipeline = createTelemetryPipeline({
|
||||
transport: { send: (batch) => void batches.push([...batch]) },
|
||||
budget: TEST_TELEMETRY_BUDGET,
|
||||
});
|
||||
for (let i = 0; i < 1_000; i += 1) {
|
||||
await pipeline.emit(REPEATED_ERROR);
|
||||
}
|
||||
await pipeline.flush();
|
||||
const items = batches.flat();
|
||||
expect(items.reduce((sum, item) => sum + item.occurrences, 0)).toBe(1_000);
|
||||
expect(new Set(items.map((item) => item.fingerprint)).size).toBe(1);
|
||||
expect(batches.length).toBeLessThanOrEqual(2);
|
||||
pipeline.dispose();
|
||||
});
|
||||
|
||||
it("reports held duplicates when the dedup window closes without another flush", async () => {
|
||||
const batches: TelemetryBatchItem[][] = [];
|
||||
const timers: Array<Readonly<{ callback: () => void; ms: number }>> = [];
|
||||
const pipeline = createTelemetryPipeline({
|
||||
transport: { send: (batch) => void batches.push([...batch]) },
|
||||
budget: TEST_TELEMETRY_BUDGET,
|
||||
setTimer: (callback, ms) => timers.push({ callback, ms }),
|
||||
clearTimer: () => {},
|
||||
});
|
||||
for (let i = 0; i < 10; i += 1) {
|
||||
await pipeline.emit(REPEATED_ERROR);
|
||||
}
|
||||
expect(timers.map((timer) => timer.ms)).toEqual([TEST_TELEMETRY_BUDGET.dedupWindowMs]);
|
||||
for (const timer of timers.splice(0)) timer.callback();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(batches.flat().reduce((sum, item) => sum + item.occurrences, 0)).toBe(10);
|
||||
pipeline.dispose();
|
||||
});
|
||||
|
||||
it("does not let a rejected or evicted event suppress its fingerprint", async () => {
|
||||
const batches: TelemetryBatchItem[][] = [];
|
||||
const pipeline = createTelemetryPipeline({
|
||||
transport: { send: (batch) => void batches.push([...batch]) },
|
||||
budget: { ...TEST_TELEMETRY_BUDGET, maxBufferedEvents: 1 },
|
||||
schedule: () => {},
|
||||
});
|
||||
const info: TelemetryEvent<unknown> = { ...TEST_EVENT, kind: "catalog.load.slow", severity: "info" };
|
||||
// Rejected on arrival: the buffer holds a more important event.
|
||||
await pipeline.emit(TEST_EVENT);
|
||||
await pipeline.emit(info);
|
||||
await pipeline.flush();
|
||||
await pipeline.emit(info);
|
||||
expect(pipeline.stats()).toMatchObject({ buffered: 1, deduplicated: 0 });
|
||||
await pipeline.flush();
|
||||
// Evicted after admission: a more important event takes its slot.
|
||||
await pipeline.emit({ ...info, payload: { reason: "evicted" } });
|
||||
await pipeline.emit({ ...TEST_EVENT, payload: { reason: "other" } });
|
||||
await pipeline.flush();
|
||||
await pipeline.emit({ ...info, payload: { reason: "evicted" } });
|
||||
expect(pipeline.stats()).toMatchObject({ buffered: 1, deduplicated: 0 });
|
||||
await pipeline.flush();
|
||||
const kinds = batches.flat().map((item) => `${item.event.kind}:${item.occurrences}`);
|
||||
expect(kinds).toEqual([
|
||||
"catalog.load.failed:1",
|
||||
"catalog.load.slow:1",
|
||||
"catalog.load.failed:1",
|
||||
"catalog.load.slow:1",
|
||||
]);
|
||||
});
|
||||
|
||||
it("never reports a sampled-out event through a duplicate summary", async () => {
|
||||
const send = vi.fn();
|
||||
const pipeline = createTelemetryPipeline({
|
||||
transport: { send },
|
||||
budget: { ...TEST_TELEMETRY_BUDGET, sampleRate: 0 },
|
||||
});
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
await pipeline.emit({ kind: "a.info", severity: "info" });
|
||||
}
|
||||
await pipeline.flush();
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
expect(pipeline.stats().sampledOut).toBe(3);
|
||||
pipeline.dispose();
|
||||
});
|
||||
|
||||
it("rate-limits distinct events and resumes after the window reopens", async () => {
|
||||
let now = 0;
|
||||
const scheduling = manualScheduling();
|
||||
const send = vi.fn().mockResolvedValue(undefined);
|
||||
const pipeline = createTelemetryPipeline({
|
||||
transport: { send },
|
||||
budget: {
|
||||
...TEST_TELEMETRY_BUDGET,
|
||||
maxSendsPerMinute: 2,
|
||||
maxBatchEvents: 1,
|
||||
maxBufferedEvents: 100,
|
||||
},
|
||||
now: () => now,
|
||||
...scheduling,
|
||||
});
|
||||
for (let i = 0; i < 5; i += 1) {
|
||||
await pipeline.emit({ ...TEST_EVENT, payload: { reason: `r${i}` } });
|
||||
}
|
||||
await pipeline.flush();
|
||||
expect(send).toHaveBeenCalledTimes(2);
|
||||
expect(pipeline.stats().buffered).toBe(3);
|
||||
|
||||
now = 60_000;
|
||||
scheduling.runTimers();
|
||||
await pipeline.flush();
|
||||
expect(send).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it("keeps memory bounded when events are all distinct and the collector is down", async () => {
|
||||
const pipeline = createTelemetryPipeline({
|
||||
transport: { send: () => Promise.reject(new Error("down")) },
|
||||
budget: { ...TEST_TELEMETRY_BUDGET, maxBufferedEvents: 20, maxFingerprints: 30 },
|
||||
schedule: () => {},
|
||||
});
|
||||
for (let i = 0; i < 5_000; i += 1) {
|
||||
await pipeline.emit({ ...TEST_EVENT, payload: { reason: `distinct-${i}` } });
|
||||
}
|
||||
const stats = pipeline.stats();
|
||||
expect(stats.buffered).toBeLessThanOrEqual(20);
|
||||
expect(stats.peakBuffered).toBeLessThanOrEqual(20);
|
||||
expect(stats.fingerprints).toBeLessThanOrEqual(30);
|
||||
});
|
||||
|
||||
it("redacts before anything is buffered or sent", async () => {
|
||||
const batches: TelemetryBatchItem[][] = [];
|
||||
const pipeline = createTelemetryPipeline({
|
||||
transport: { send: (batch) => void batches.push([...batch]) },
|
||||
budget: TEST_TELEMETRY_BUDGET,
|
||||
});
|
||||
await pipeline.emit({
|
||||
...TEST_EVENT,
|
||||
payload: { reason: "x", accessToken: "secret-token", headers: { cookie: "sid=1" } },
|
||||
});
|
||||
await pipeline.flush();
|
||||
expect(JSON.stringify(batches)).not.toMatch(/secret-token|sid=1/);
|
||||
});
|
||||
|
||||
it("samples low-severity events deterministically but always keeps errors", async () => {
|
||||
const pipeline = createTelemetryPipeline({
|
||||
transport: { send: () => {} },
|
||||
budget: { ...TEST_TELEMETRY_BUDGET, sampleRate: 0 },
|
||||
schedule: () => {},
|
||||
});
|
||||
await pipeline.emit({ kind: "a.info", severity: "info", interactionId: "i-1" });
|
||||
await pipeline.emit({ kind: "a.error", severity: "error", interactionId: "i-1" });
|
||||
expect(pipeline.stats()).toMatchObject({ sampledOut: 1, buffered: 1 });
|
||||
});
|
||||
|
||||
it("drops invalid envelopes and stops admitting after dispose", async () => {
|
||||
const send = vi.fn();
|
||||
const pipeline = createTelemetryPipeline({
|
||||
transport: { send },
|
||||
budget: TEST_TELEMETRY_BUDGET,
|
||||
});
|
||||
await pipeline.emit({ kind: "NOT VALID", severity: "error" });
|
||||
expect(pipeline.stats().invalid).toBe(1);
|
||||
pipeline.dispose();
|
||||
await pipeline.emit(TEST_EVENT);
|
||||
await pipeline.flush();
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { TelemetryEvent } from "../../../src/platform/telemetry/telemetry-event.ts";
|
||||
import { isTelemetryEnvelopeValid } from "../../../src/platform/telemetry/telemetry-event.ts";
|
||||
import {
|
||||
failOpenTelemetryPort,
|
||||
NO_OP_TELEMETRY_PORT,
|
||||
type TelemetryPort,
|
||||
} from "../../../src/platform/telemetry/telemetry-port.ts";
|
||||
|
||||
describe("TelemetryPort", () => {
|
||||
it("accepts feature-owned payloads through a generic envelope", async () => {
|
||||
const seen: TelemetryEvent<unknown>[] = [];
|
||||
const port: TelemetryPort = {
|
||||
emit(event) {
|
||||
seen.push(event);
|
||||
},
|
||||
};
|
||||
|
||||
await port.emit({
|
||||
kind: "catalog.load.failed",
|
||||
severity: "error",
|
||||
contextId: "commerce",
|
||||
featureId: "catalog",
|
||||
interactionId: "i-1",
|
||||
payload: { reason: "timeout" },
|
||||
});
|
||||
|
||||
expect(seen).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("contains a throwing or rejecting implementation", async () => {
|
||||
const throwing = failOpenTelemetryPort({
|
||||
emit() {
|
||||
throw new Error("vendor down");
|
||||
},
|
||||
});
|
||||
const rejecting = failOpenTelemetryPort({
|
||||
emit: () => Promise.reject(new Error("vendor down")),
|
||||
});
|
||||
await expect(throwing.emit({ kind: "a.b", severity: "info" })).resolves.toBeUndefined();
|
||||
await expect(rejecting.emit({ kind: "a.b", severity: "info" })).resolves.toBeUndefined();
|
||||
expect(() => NO_OP_TELEMETRY_PORT.emit({ kind: "a.b", severity: "info" })).not.toThrow();
|
||||
});
|
||||
|
||||
it("admits only bounded envelope identifiers", () => {
|
||||
expect(isTelemetryEnvelopeValid({ kind: "catalog.load.failed", severity: "warning" })).toBe(true);
|
||||
expect(isTelemetryEnvelopeValid({ kind: "Free Text Kind", severity: "warning" })).toBe(false);
|
||||
expect(
|
||||
isTelemetryEnvelopeValid({
|
||||
kind: "a.b",
|
||||
severity: "warning",
|
||||
featureId: "/users/123",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isTelemetryEnvelopeValid({
|
||||
kind: "a.b",
|
||||
severity: "verbose" as never,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { InstalledHttpContract } from "../../../src/contracts/external-contract-runtime.ts";
|
||||
import { safeTraceparent } from "../../../src/adapters/telemetry/best-effort-telemetry.ts";
|
||||
import {
|
||||
buildRequestHeaders,
|
||||
createTraceContext,
|
||||
} from "../../../src/platform/telemetry/trace-context.ts";
|
||||
import { createExecutionContext } from "../../../src/platform/execution/execution-context.ts";
|
||||
import { TEST_LIST_HTTP_CONTRACT } from "../../helpers/external-contract-fixture.ts";
|
||||
import {
|
||||
jsonRows,
|
||||
scopeSnapshot,
|
||||
testExecutor,
|
||||
type Transport,
|
||||
} from "../../helpers/traffic-test-kit.ts";
|
||||
|
||||
const VALID_TRACE_ID = "4bf92f3577b34da6a3ce929d0e0e4736";
|
||||
|
||||
function testExecutionContext(
|
||||
options: Readonly<{ interactionId: string; traceId: string }>,
|
||||
) {
|
||||
return createExecutionContext({
|
||||
interactionId: options.interactionId,
|
||||
deadlineMs: 5_000,
|
||||
traffic: { maxPhysicalRequests: 4, maxRetries: 1, maxConcurrentRequests: 2 },
|
||||
trace: createTraceContext({ traceId: options.traceId }),
|
||||
});
|
||||
}
|
||||
|
||||
describe("trace and correlation propagation", () => {
|
||||
it("propagates one interaction trace identity to child requests", () => {
|
||||
const context = testExecutionContext({ interactionId: "i-1", traceId: VALID_TRACE_ID });
|
||||
|
||||
const a = buildRequestHeaders(context);
|
||||
const b = buildRequestHeaders(context);
|
||||
|
||||
expect(a.get("traceparent")).toBe(b.get("traceparent"));
|
||||
expect(a.get("x-correlation-id")).toBe("i-1");
|
||||
});
|
||||
|
||||
it("emits a W3C traceparent the existing validator accepts", () => {
|
||||
const trace = createTraceContext({ traceId: VALID_TRACE_ID });
|
||||
expect(safeTraceparent(trace.traceparent)).toBe(trace.traceparent);
|
||||
expect(trace.traceparent.startsWith(`00-${VALID_TRACE_ID}-`)).toBe(true);
|
||||
expect(safeTraceparent(createTraceContext().traceparent)).not.toBeNull();
|
||||
});
|
||||
|
||||
it("rejects malformed or all-zero trace ids", () => {
|
||||
expect(() => createTraceContext({ traceId: "0".repeat(32) })).toThrow(TypeError);
|
||||
expect(() => createTraceContext({ traceId: "XYZ" })).toThrow(TypeError);
|
||||
});
|
||||
|
||||
it("sends the same trace headers on every physical request of the interaction", async () => {
|
||||
const seen: Array<Headers> = [];
|
||||
const transport = vi.fn<Transport>(async (_input, init) => {
|
||||
seen.push(new Headers(init?.headers));
|
||||
return jsonRows(1);
|
||||
});
|
||||
const execution = testExecutionContext({ interactionId: "i-9", traceId: VALID_TRACE_ID });
|
||||
const executor = testExecutor(transport);
|
||||
const operation = TEST_LIST_HTTP_CONTRACT as InstalledHttpContract<unknown, unknown, unknown>;
|
||||
const context = { routeId: "TEST_ROUTE", scope: scopeSnapshot(), execution };
|
||||
|
||||
await executor.execute(operation, { limit: 1 }, context);
|
||||
await executor.execute(operation, { limit: 1 }, context);
|
||||
|
||||
expect(seen).toHaveLength(2);
|
||||
expect(seen[0]?.get("traceparent")).toBe(execution.trace?.traceparent);
|
||||
expect(seen[1]?.get("traceparent")).toBe(execution.trace?.traceparent);
|
||||
expect(seen.every((headers) => headers.get("x-correlation-id") === "i-9")).toBe(true);
|
||||
});
|
||||
|
||||
it("adds no trace to an interaction that did not opt in, only its own request id", async () => {
|
||||
const seen: Array<Headers> = [];
|
||||
const transport = vi.fn<Transport>(async (_input, init) => {
|
||||
seen.push(new Headers(init?.headers));
|
||||
return jsonRows(1);
|
||||
});
|
||||
await testExecutor(transport).execute(
|
||||
TEST_LIST_HTTP_CONTRACT as InstalledHttpContract<unknown, unknown, unknown>,
|
||||
{ limit: 1 },
|
||||
{ routeId: "TEST_ROUTE", scope: scopeSnapshot() },
|
||||
);
|
||||
expect(seen[0]?.get("traceparent")).toBeNull();
|
||||
// 03-03. Every execution still sends a request id for the server log.
|
||||
expect(seen[0]?.get("x-correlation-id")).toMatch(/^[A-Za-z0-9._:-]{1,128}$/u);
|
||||
});
|
||||
|
||||
it("does not let a credential collaborator forge the trace headers", async () => {
|
||||
const transport = vi.fn<Transport>(async () => jsonRows(1));
|
||||
const outcome = await testExecutor(transport, {
|
||||
credentialHeaders: { traceparent: `00-${VALID_TRACE_ID}-00f067aa0ba902b7-01` },
|
||||
}).execute(
|
||||
TEST_LIST_HTTP_CONTRACT as InstalledHttpContract<unknown, unknown, unknown>,
|
||||
{ limit: 1 },
|
||||
{ routeId: "TEST_ROUTE", scope: scopeSnapshot() },
|
||||
);
|
||||
expect(outcome.kind).toBe("AUTH_INTEGRATION_FAILURE");
|
||||
expect(transport).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
ConcurrencyQueueFullError,
|
||||
createConcurrencyBudget,
|
||||
} from "../../../src/platform/traffic/concurrency-budget.ts";
|
||||
|
||||
const live = () => new AbortController().signal;
|
||||
|
||||
describe("createConcurrencyBudget", () => {
|
||||
it("never grants more than maximum simultaneous leases", async () => {
|
||||
const budget = createConcurrencyBudget({ maximum: 2, maxQueued: 1 });
|
||||
const first = await budget.acquire(live());
|
||||
const second = await budget.acquire(live());
|
||||
|
||||
expect(budget.active).toBe(2);
|
||||
const queued = budget.acquire(live());
|
||||
expect(budget.queued).toBe(1);
|
||||
await expect(budget.acquire(live())).rejects.toThrow(/queue/i);
|
||||
await expect(budget.acquire(live())).rejects.toBeInstanceOf(
|
||||
ConcurrencyQueueFullError,
|
||||
);
|
||||
|
||||
first.release();
|
||||
const third = await queued;
|
||||
expect(budget.active).toBe(2);
|
||||
second.release();
|
||||
third.release();
|
||||
expect(budget.active).toBe(0);
|
||||
});
|
||||
|
||||
it("removes an aborted waiter", async () => {
|
||||
const budget = createConcurrencyBudget({ maximum: 1, maxQueued: 1 });
|
||||
const lease = await budget.acquire(live());
|
||||
const controller = new AbortController();
|
||||
const waiting = budget.acquire(controller.signal);
|
||||
controller.abort();
|
||||
|
||||
await expect(waiting).rejects.toMatchObject({ name: "AbortError" });
|
||||
expect(budget.queued).toBe(0);
|
||||
lease.release();
|
||||
expect(budget.active).toBe(0);
|
||||
});
|
||||
|
||||
it("rejects immediately when the signal is already aborted", async () => {
|
||||
const budget = createConcurrencyBudget({ maximum: 1, maxQueued: 1 });
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await expect(budget.acquire(controller.signal)).rejects.toMatchObject({
|
||||
name: "AbortError",
|
||||
});
|
||||
expect(budget.active).toBe(0);
|
||||
});
|
||||
|
||||
it("grants waiters in FIFO order", async () => {
|
||||
const budget = createConcurrencyBudget({ maximum: 1, maxQueued: 3 });
|
||||
const holder = await budget.acquire(live());
|
||||
const order: string[] = [];
|
||||
const a = budget.acquire(live()).then((lease) => {
|
||||
order.push("a");
|
||||
return lease;
|
||||
});
|
||||
const b = budget.acquire(live()).then((lease) => {
|
||||
order.push("b");
|
||||
return lease;
|
||||
});
|
||||
holder.release();
|
||||
(await a).release();
|
||||
(await b).release();
|
||||
expect(order).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
it("treats release as idempotent", async () => {
|
||||
const budget = createConcurrencyBudget({ maximum: 1, maxQueued: 0 });
|
||||
const lease = await budget.acquire(live());
|
||||
lease.release();
|
||||
lease.release();
|
||||
expect(budget.active).toBe(0);
|
||||
const again = await budget.acquire(live());
|
||||
await expect(budget.acquire(live())).rejects.toBeInstanceOf(
|
||||
ConcurrencyQueueFullError,
|
||||
);
|
||||
again.release();
|
||||
});
|
||||
|
||||
it("rejects an unbounded configuration", () => {
|
||||
expect(() =>
|
||||
createConcurrencyBudget({ maximum: 1, maxQueued: Number.POSITIVE_INFINITY }),
|
||||
).toThrow(TypeError);
|
||||
expect(() => createConcurrencyBudget({ maximum: 0, maxQueued: 1 })).toThrow(
|
||||
TypeError,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,244 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { InstalledHttpContract } from "../../../src/contracts/external-contract-runtime.ts";
|
||||
import {
|
||||
TEST_CREATE_HTTP_CONTRACT,
|
||||
TEST_LIST_HTTP_CONTRACT,
|
||||
} from "../../helpers/external-contract-fixture.ts";
|
||||
import {
|
||||
jsonRows,
|
||||
manualClock,
|
||||
networkFailure,
|
||||
scopeSnapshot,
|
||||
testExecutionContext,
|
||||
testExecutor,
|
||||
type Transport,
|
||||
} from "../../helpers/traffic-test-kit.ts";
|
||||
|
||||
const TEST_QUERY = TEST_LIST_HTTP_CONTRACT as InstalledHttpContract<
|
||||
unknown,
|
||||
unknown,
|
||||
unknown
|
||||
>;
|
||||
const TEST_COMMAND = TEST_CREATE_HTTP_CONTRACT as InstalledHttpContract<
|
||||
unknown,
|
||||
unknown,
|
||||
unknown
|
||||
>;
|
||||
const ROUTE_ID = "TEST_ROUTE";
|
||||
|
||||
/** A transport that only ever ends when its request is aborted. */
|
||||
function hangingTransport(): Transport & { calls: number } {
|
||||
const transport = ((_input: RequestInfo | URL, init?: RequestInit) => {
|
||||
transport.calls += 1;
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener(
|
||||
"abort",
|
||||
() => reject(new DOMException("aborted", "AbortError")),
|
||||
{ once: true },
|
||||
);
|
||||
});
|
||||
}) as Transport & { calls: number };
|
||||
transport.calls = 0;
|
||||
return transport;
|
||||
}
|
||||
|
||||
describe("HTTP dispatch under interaction traffic budgets", () => {
|
||||
it("does not dispatch after the interaction physical-request budget is exhausted", async () => {
|
||||
const transport = vi.fn<Transport>(networkFailure);
|
||||
const execution = testExecutionContext({
|
||||
maxPhysicalRequests: 1,
|
||||
maxRetries: 3,
|
||||
});
|
||||
|
||||
const outcome = await testExecutor(transport).execute(TEST_QUERY, { limit: 5 }, {
|
||||
routeId: ROUTE_ID,
|
||||
scope: scopeSnapshot(),
|
||||
execution,
|
||||
});
|
||||
|
||||
expect(outcome.kind).toBe("TRANSPORT_FAILURE");
|
||||
expect(transport).toHaveBeenCalledTimes(1);
|
||||
expect(execution.traffic.requests.consumed).toBe(1);
|
||||
});
|
||||
|
||||
it("rejects a second operation once the shared request budget is gone", async () => {
|
||||
const transport = vi.fn<Transport>(networkFailure);
|
||||
const execution = testExecutionContext({
|
||||
maxPhysicalRequests: 1,
|
||||
maxRetries: 0,
|
||||
});
|
||||
const executor = testExecutor(transport);
|
||||
const context = { routeId: ROUTE_ID, scope: scopeSnapshot(), execution };
|
||||
|
||||
await executor.execute(TEST_QUERY, { limit: 5 }, context);
|
||||
const second = await executor.execute(TEST_QUERY, { limit: 5 }, context);
|
||||
|
||||
expect(second).toMatchObject({
|
||||
kind: "TRANSPORT_FAILURE",
|
||||
failure: { kind: "OVERLOADED_BEFORE_SEND" },
|
||||
});
|
||||
expect(transport).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("shares one retry budget across independent failing operations", async () => {
|
||||
const transport = vi.fn<Transport>(networkFailure);
|
||||
const execution = testExecutionContext({
|
||||
maxPhysicalRequests: 10,
|
||||
maxRetries: 1,
|
||||
});
|
||||
const executor = testExecutor(transport);
|
||||
const context = { routeId: ROUTE_ID, scope: scopeSnapshot(), execution };
|
||||
|
||||
await executor.execute(TEST_QUERY, { limit: 5 }, context);
|
||||
await executor.execute(TEST_QUERY, { limit: 5 }, context);
|
||||
|
||||
// First operation: attempt + its one shared retry. Second: attempt only.
|
||||
expect(transport).toHaveBeenCalledTimes(3);
|
||||
expect(execution.traffic.retries.consumed).toBe(1);
|
||||
});
|
||||
|
||||
it("does not reset the interaction deadline before retry", async () => {
|
||||
const clock = manualClock(0);
|
||||
const execution = testExecutionContext({
|
||||
deadlineMs: 5_000,
|
||||
maxPhysicalRequests: 4,
|
||||
maxRetries: 3,
|
||||
clock: clock.now,
|
||||
});
|
||||
const transport = vi.fn<Transport>(() => {
|
||||
clock.advance(5_001);
|
||||
return networkFailure();
|
||||
});
|
||||
|
||||
const outcome = await testExecutor(transport).execute(TEST_QUERY, { limit: 5 }, {
|
||||
routeId: ROUTE_ID,
|
||||
scope: scopeSnapshot(),
|
||||
execution,
|
||||
});
|
||||
|
||||
expect(outcome.kind).toBe("TRANSPORT_FAILURE");
|
||||
expect(transport).toHaveBeenCalledTimes(1);
|
||||
expect(execution.traffic.retries.consumed).toBe(0);
|
||||
});
|
||||
|
||||
it("gives a late operation only the interaction's remaining deadline", async () => {
|
||||
const clock = manualClock(0);
|
||||
const execution = testExecutionContext({
|
||||
deadlineMs: 1_000,
|
||||
clock: clock.now,
|
||||
});
|
||||
clock.advance(1_000);
|
||||
const transport = vi.fn<Transport>(async () => jsonRows(1));
|
||||
|
||||
const outcome = await testExecutor(transport).execute(TEST_QUERY, { limit: 5 }, {
|
||||
routeId: ROUTE_ID,
|
||||
scope: scopeSnapshot(),
|
||||
execution,
|
||||
});
|
||||
|
||||
expect(outcome).toMatchObject({
|
||||
kind: "TRANSPORT_FAILURE",
|
||||
failure: { kind: "TIMEOUT" },
|
||||
});
|
||||
expect(transport).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects instead of queueing beyond the interaction queue bound", async () => {
|
||||
const transport = hangingTransport();
|
||||
const execution = testExecutionContext({
|
||||
maxPhysicalRequests: 10,
|
||||
maxConcurrentRequests: 1,
|
||||
maxQueuedRequests: 0,
|
||||
});
|
||||
const executor = testExecutor(transport);
|
||||
const context = { routeId: ROUTE_ID, scope: scopeSnapshot(), execution };
|
||||
|
||||
const first = executor.execute(TEST_QUERY, { limit: 5 }, context);
|
||||
await vi.waitFor(() => expect(transport.calls).toBe(1));
|
||||
const second = await executor.execute(TEST_QUERY, { limit: 5 }, context);
|
||||
|
||||
expect(second).toMatchObject({
|
||||
kind: "TRANSPORT_FAILURE",
|
||||
failure: { kind: "OVERLOADED_BEFORE_SEND" },
|
||||
});
|
||||
execution.cancellation.cancel();
|
||||
await expect(first).resolves.toMatchObject({ kind: "CANCELLED" });
|
||||
expect(transport.calls).toBe(1);
|
||||
});
|
||||
|
||||
it("releases every lease and waiting entry when the interaction is aborted", async () => {
|
||||
const transport = hangingTransport();
|
||||
const execution = testExecutionContext({
|
||||
maxPhysicalRequests: 10,
|
||||
maxConcurrentRequests: 1,
|
||||
maxQueuedRequests: 2,
|
||||
});
|
||||
const executor = testExecutor(transport);
|
||||
const context = { routeId: ROUTE_ID, scope: scopeSnapshot(), execution };
|
||||
|
||||
const running = [1, 2, 3].map(() =>
|
||||
executor.execute(TEST_QUERY, { limit: 5 }, context),
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
expect(execution.traffic.concurrency.active).toBe(1);
|
||||
expect(execution.traffic.concurrency.queued).toBe(2);
|
||||
});
|
||||
|
||||
execution.cancellation.cancel();
|
||||
const outcomes = await Promise.all(running);
|
||||
|
||||
expect(outcomes.map((outcome) => outcome.kind)).toEqual([
|
||||
"CANCELLED",
|
||||
"CANCELLED",
|
||||
"CANCELLED",
|
||||
]);
|
||||
expect(execution.traffic.concurrency.active).toBe(0);
|
||||
expect(execution.traffic.concurrency.queued).toBe(0);
|
||||
expect(transport.calls).toBe(1);
|
||||
});
|
||||
|
||||
it("keeps KEYED command replay safety even when the budget allows retries", async () => {
|
||||
const transport = vi.fn<Transport>(networkFailure);
|
||||
const execution = testExecutionContext({
|
||||
maxPhysicalRequests: 10,
|
||||
maxRetries: 5,
|
||||
});
|
||||
|
||||
const outcome = await testExecutor(transport).execute(
|
||||
TEST_COMMAND,
|
||||
{ name: "entity" },
|
||||
{
|
||||
routeId: ROUTE_ID,
|
||||
scope: scopeSnapshot(),
|
||||
execution,
|
||||
intent: Object.freeze({
|
||||
intentId: "intent-1",
|
||||
operationId: "TEST_CREATE_ENTITY",
|
||||
canonicalInputIdentity: "opaque",
|
||||
idempotencyKey: "key-1",
|
||||
createdAtMonotonicMs: 1,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
expect(outcome).toMatchObject({
|
||||
kind: "TRANSPORT_FAILURE",
|
||||
effect: "MAYBE_APPLIED",
|
||||
});
|
||||
expect(transport).toHaveBeenCalledTimes(1);
|
||||
expect(execution.traffic.retries.consumed).toBe(0);
|
||||
});
|
||||
|
||||
it("bounds an execution without an explicit interaction by the default policy", async () => {
|
||||
const transport = vi.fn<Transport>(networkFailure);
|
||||
|
||||
await testExecutor(transport, { maxRetryAttempts: 2 }).execute(
|
||||
TEST_QUERY,
|
||||
{ limit: 5 },
|
||||
{ routeId: ROUTE_ID, scope: scopeSnapshot() },
|
||||
);
|
||||
|
||||
expect(transport).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
composeContractContributions,
|
||||
ContractContributionError,
|
||||
type InstalledContractContribution,
|
||||
type InstalledHttpContract,
|
||||
} from "../../../src/contracts/external-contract-runtime.ts";
|
||||
import type { TrafficBudget } from "../../../src/platform/traffic/traffic-budget.ts";
|
||||
import {
|
||||
TEST_CONTRACT_CONTRIBUTION,
|
||||
TEST_LIST_HTTP_CONTRACT,
|
||||
} from "../../helpers/external-contract-fixture.ts";
|
||||
|
||||
function compositionReason(run: () => unknown): string {
|
||||
try {
|
||||
run();
|
||||
} catch (error) {
|
||||
return error instanceof ContractContributionError ? error.reason : String(error);
|
||||
}
|
||||
throw new Error("composition unexpectedly succeeded");
|
||||
}
|
||||
|
||||
const FINITE: TrafficBudget = Object.freeze({
|
||||
maxPhysicalRequests: 3,
|
||||
maxRetries: 2,
|
||||
maxConcurrentRequests: 2,
|
||||
maxQueuedRequests: 2,
|
||||
});
|
||||
|
||||
function withTraffic(traffic: unknown): InstalledContractContribution {
|
||||
const list = {
|
||||
...TEST_LIST_HTTP_CONTRACT,
|
||||
frontend: { ...TEST_LIST_HTTP_CONTRACT.frontend, traffic },
|
||||
} as unknown as InstalledHttpContract<unknown, unknown, unknown>;
|
||||
return {
|
||||
...TEST_CONTRACT_CONTRIBUTION,
|
||||
http: [list],
|
||||
};
|
||||
}
|
||||
|
||||
describe("operation traffic policy", () => {
|
||||
it("requires finite positive traffic limits for an operation", () => {
|
||||
expect(
|
||||
compositionReason(() =>
|
||||
composeContractContributions([
|
||||
withTraffic({ ...FINITE, maxPhysicalRequests: Number.POSITIVE_INFINITY }),
|
||||
]),
|
||||
),
|
||||
).toMatch(/traffic.*maxPhysicalRequests/i);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ ...FINITE, maxRetries: -1 },
|
||||
{ ...FINITE, maxConcurrentRequests: 0 },
|
||||
{ maxPhysicalRequests: 3, maxRetries: 1, maxConcurrentRequests: 1 },
|
||||
{ ...FINITE, extra: 1 },
|
||||
])("rejects a malformed traffic policy %#", (traffic) => {
|
||||
expect(
|
||||
compositionReason(() => composeContractContributions([withTraffic(traffic)])),
|
||||
).toMatch(/traffic|field/i);
|
||||
});
|
||||
|
||||
it("installs an immutable snapshot of a finite traffic policy", () => {
|
||||
const source = { ...FINITE };
|
||||
const composed = composeContractContributions([withTraffic(source)]);
|
||||
source.maxPhysicalRequests = 60;
|
||||
|
||||
const installed = composed.httpByOperationId.get("TEST_LIST_ENTITIES");
|
||||
expect(installed?.frontend.traffic).toEqual(FINITE);
|
||||
expect(Object.isFrozen(installed?.frontend.traffic)).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps operations without a traffic policy valid", () => {
|
||||
const composed = composeContractContributions([TEST_CONTRACT_CONTRIBUTION]);
|
||||
expect(
|
||||
composed.httpByOperationId.get("TEST_LIST_ENTITIES")?.frontend.traffic,
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createRequestBudget } from "../../../src/platform/traffic/request-budget.ts";
|
||||
|
||||
describe("createRequestBudget", () => {
|
||||
it("allows exactly the configured number of physical requests", () => {
|
||||
const budget = createRequestBudget(2);
|
||||
expect(budget.tryConsume()).toBe(true);
|
||||
expect(budget.tryConsume()).toBe(true);
|
||||
expect(budget.tryConsume()).toBe(false);
|
||||
expect(budget.consumed).toBe(2);
|
||||
expect(budget.remaining).toBe(0);
|
||||
});
|
||||
|
||||
it("never refills and never over-counts after exhaustion", () => {
|
||||
const budget = createRequestBudget(1);
|
||||
budget.tryConsume();
|
||||
for (let i = 0; i < 100; i += 1) budget.tryConsume();
|
||||
expect(budget.consumed).toBe(1);
|
||||
});
|
||||
|
||||
it.each([0, -1, Number.POSITIVE_INFINITY, Number.NaN, 2.5])(
|
||||
"rejects non-positive or unbounded maximum %s",
|
||||
(maximum) => {
|
||||
expect(() => createRequestBudget(maximum)).toThrow(TypeError);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createQueryClient,
|
||||
QUERY_CACHE_DEFAULTS,
|
||||
} from "../../../src/adapters/query-cache/tanstack-query-cache.ts";
|
||||
import type { InstalledHttpContract } from "../../../src/contracts/external-contract-runtime.ts";
|
||||
import { TEST_LIST_HTTP_CONTRACT } from "../../helpers/external-contract-fixture.ts";
|
||||
import {
|
||||
jsonRows,
|
||||
networkFailure,
|
||||
scopeSnapshot,
|
||||
testExecutor,
|
||||
type Transport,
|
||||
} from "../../helpers/traffic-test-kit.ts";
|
||||
|
||||
const TEST_QUERY = TEST_LIST_HTTP_CONTRACT as InstalledHttpContract<
|
||||
unknown,
|
||||
unknown,
|
||||
unknown
|
||||
>;
|
||||
|
||||
/**
|
||||
* Spec §16. Multiple consumers of one query identity must not imply multiple
|
||||
* physical requests. TanStack Query owns in-flight coalescing; this suite pins
|
||||
* that the installed query client plus the real V3 executor keep it that way.
|
||||
*/
|
||||
describe("request deduplication and coalescing", () => {
|
||||
function loadSameQuery(
|
||||
client: ReturnType<typeof createQueryClient>,
|
||||
executor: ReturnType<typeof testExecutor>,
|
||||
key: readonly unknown[] = ["entities", "list", { limit: 20 }],
|
||||
) {
|
||||
return client.fetchQuery({
|
||||
queryKey: key,
|
||||
queryFn: ({ signal }) =>
|
||||
executor.execute(TEST_QUERY, { limit: 20 }, {
|
||||
routeId: "TEST_ROUTE",
|
||||
scope: scopeSnapshot(),
|
||||
signal,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
it("coalesces concurrent consumers of the same query identity", async () => {
|
||||
const transport = vi.fn<Transport>(async () => jsonRows(3));
|
||||
const executor = testExecutor(transport);
|
||||
const client = createQueryClient();
|
||||
|
||||
const results = await Promise.all([
|
||||
loadSameQuery(client, executor),
|
||||
loadSameQuery(client, executor),
|
||||
loadSameQuery(client, executor),
|
||||
]);
|
||||
|
||||
expect(transport).toHaveBeenCalledTimes(1);
|
||||
expect(results.every((result) => result.kind === "SUCCESS")).toBe(true);
|
||||
client.clear();
|
||||
});
|
||||
|
||||
it("keeps distinct query identities as distinct physical requests", async () => {
|
||||
const transport = vi.fn<Transport>(async () => jsonRows(1));
|
||||
const executor = testExecutor(transport);
|
||||
const client = createQueryClient();
|
||||
|
||||
await Promise.all([
|
||||
loadSameQuery(client, executor, ["entities", "list", 1]),
|
||||
loadSameQuery(client, executor, ["entities", "list", 2]),
|
||||
]);
|
||||
|
||||
expect(transport).toHaveBeenCalledTimes(2);
|
||||
client.clear();
|
||||
});
|
||||
|
||||
it("does not stack a query-layer retry on top of the executor retry budget", async () => {
|
||||
expect(QUERY_CACHE_DEFAULTS.retry).toBe(false);
|
||||
expect(QUERY_CACHE_DEFAULTS.mutationRetry).toBe(false);
|
||||
|
||||
const transport = vi.fn<Transport>(networkFailure);
|
||||
const executor = testExecutor(transport, { maxRetryAttempts: 2 });
|
||||
const client = createQueryClient();
|
||||
|
||||
await Promise.all([loadSameQuery(client, executor), loadSameQuery(client, executor)]);
|
||||
|
||||
// One coalesced logical execution: 1 attempt + at most 2 executor retries.
|
||||
expect(transport.mock.calls.length).toBeLessThanOrEqual(3);
|
||||
client.clear();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { InstalledHttpContract } from "../../../src/contracts/external-contract-runtime.ts";
|
||||
import {
|
||||
assertRequestFanoutWithinBudget,
|
||||
RequestFanoutExceededError,
|
||||
} from "../../../src/platform/traffic/request-fanout.ts";
|
||||
import { TEST_LIST_HTTP_CONTRACT } from "../../helpers/external-contract-fixture.ts";
|
||||
import {
|
||||
jsonRows,
|
||||
paginatedCollection,
|
||||
scopeSnapshot,
|
||||
testExecutionContext,
|
||||
testExecutor,
|
||||
type Transport,
|
||||
} from "../../helpers/traffic-test-kit.ts";
|
||||
|
||||
const TEST_QUERY = TEST_LIST_HTTP_CONTRACT as InstalledHttpContract<
|
||||
unknown,
|
||||
unknown,
|
||||
unknown
|
||||
>;
|
||||
|
||||
/** Physical requests one collection load may cost. */
|
||||
const COLLECTION_LOAD_FANOUT_BUDGET = 1;
|
||||
|
||||
/**
|
||||
* Spec §12 / §41. Feature-neutral fan-out gate over the installed-contract
|
||||
* path; the reference feature's own collection proof lives with the feature.
|
||||
*/
|
||||
async function loadCollection(transport: Transport) {
|
||||
const execution = testExecutionContext({ maxPhysicalRequests: 3 });
|
||||
const outcome = await testExecutor(transport).execute(TEST_QUERY, { limit: 100 }, {
|
||||
routeId: "TEST_ROUTE",
|
||||
scope: scopeSnapshot(),
|
||||
execution,
|
||||
});
|
||||
return { outcome, execution };
|
||||
}
|
||||
|
||||
describe("request fan-out budget", () => {
|
||||
it.each([10, 50, 100, 1_000])(
|
||||
"loads a page of a %i-row collection with one physical request",
|
||||
async (totalRows) => {
|
||||
const transport = paginatedCollection(totalRows);
|
||||
|
||||
const { outcome, execution } = await loadCollection(transport);
|
||||
|
||||
expect(outcome.kind).toBe("SUCCESS");
|
||||
expect(outcome.kind === "SUCCESS" && outcome.value).toHaveLength(Math.min(totalRows, 100));
|
||||
expect(execution.traffic.requests.consumed).toBe(transport.calls);
|
||||
expect(() =>
|
||||
assertRequestFanoutWithinBudget(transport.calls, COLLECTION_LOAD_FANOUT_BUDGET),
|
||||
).not.toThrow();
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects a single oversized response in one request without row-proportional fan-out", async () => {
|
||||
const transport = vi.fn<Transport>(async () => jsonRows(1_000));
|
||||
const { outcome } = await loadCollection(transport);
|
||||
expect(outcome.kind).toBe("CONTRACT_VIOLATION");
|
||||
expect(transport).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("fails loudly when a flow exceeds its fan-out budget", () => {
|
||||
expect(() => assertRequestFanoutWithinBudget(4, 3)).toThrow(
|
||||
RequestFanoutExceededError,
|
||||
);
|
||||
expect(() => assertRequestFanoutWithinBudget(4, 3)).toThrow(
|
||||
/fan-out 4 exceeds 3/,
|
||||
);
|
||||
expect(() => assertRequestFanoutWithinBudget(1, 0)).toThrow(TypeError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { InstalledHttpContract } from "../../../src/contracts/external-contract-runtime.ts";
|
||||
import { TEST_LIST_HTTP_CONTRACT } from "../../helpers/external-contract-fixture.ts";
|
||||
import {
|
||||
networkFailure,
|
||||
scopeSnapshot,
|
||||
testExecutionContext,
|
||||
testExecutor,
|
||||
type Transport,
|
||||
} from "../../helpers/traffic-test-kit.ts";
|
||||
|
||||
const TEST_QUERY = TEST_LIST_HTTP_CONTRACT as InstalledHttpContract<
|
||||
unknown,
|
||||
unknown,
|
||||
unknown
|
||||
>;
|
||||
|
||||
/**
|
||||
* Spec §32 / §34. Backend failure coinciding with a user spike must not let
|
||||
* the client multiply the incident: physical requests per interaction stay at
|
||||
* or below the interaction budget no matter how many operations it starts.
|
||||
*/
|
||||
async function runInteraction(
|
||||
options: Readonly<{
|
||||
transport: Transport;
|
||||
maxPhysicalRequests: number;
|
||||
maxRetries: number;
|
||||
operationsPerInteraction?: number;
|
||||
}>,
|
||||
) {
|
||||
const executor = testExecutor(options.transport, { maxRetryAttempts: 2 });
|
||||
const execution = testExecutionContext({
|
||||
maxPhysicalRequests: options.maxPhysicalRequests,
|
||||
maxRetries: options.maxRetries,
|
||||
maxConcurrentRequests: 2,
|
||||
maxQueuedRequests: 8,
|
||||
});
|
||||
const context = { routeId: "TEST_ROUTE", scope: scopeSnapshot(), execution };
|
||||
await Promise.all(
|
||||
Array.from({ length: options.operationsPerInteraction ?? 1 }, () =>
|
||||
executor.execute(TEST_QUERY, { limit: 5 }, context),
|
||||
),
|
||||
);
|
||||
return execution;
|
||||
}
|
||||
|
||||
describe("traffic amplification invariants", () => {
|
||||
it("keeps physical requests bounded when every dispatch fails", async () => {
|
||||
const transport = vi.fn<Transport>(networkFailure);
|
||||
const interactions = Array.from({ length: 1_000 }, () =>
|
||||
runInteraction({ transport, maxPhysicalRequests: 2, maxRetries: 1 }),
|
||||
);
|
||||
|
||||
await Promise.allSettled(interactions);
|
||||
|
||||
expect(transport.mock.calls.length).toBeLessThanOrEqual(2_000);
|
||||
});
|
||||
|
||||
it("does not let parallel operations inside one interaction multiply retries", async () => {
|
||||
const transport = vi.fn<Transport>(networkFailure);
|
||||
const results = await Promise.all(
|
||||
Array.from({ length: 200 }, () =>
|
||||
runInteraction({
|
||||
transport,
|
||||
maxPhysicalRequests: 4,
|
||||
maxRetries: 1,
|
||||
operationsPerInteraction: 5,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
// Without the shared budget: 5 ops x 3 attempts = 15 requests each.
|
||||
expect(transport.mock.calls.length).toBeLessThanOrEqual(200 * 4);
|
||||
for (const execution of results) {
|
||||
expect(execution.traffic.retries.consumed).toBeLessThanOrEqual(1);
|
||||
expect(execution.traffic.requests.consumed).toBeLessThanOrEqual(4);
|
||||
expect(execution.traffic.concurrency.active).toBe(0);
|
||||
expect(execution.traffic.concurrency.queued).toBe(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("amplifies at most maxPhysicalRequests per interaction across budget sizes", async () => {
|
||||
for (const maxPhysicalRequests of [1, 2, 3]) {
|
||||
const transport = vi.fn<Transport>(networkFailure);
|
||||
await Promise.all(
|
||||
Array.from({ length: 100 }, () =>
|
||||
runInteraction({
|
||||
transport,
|
||||
maxPhysicalRequests,
|
||||
maxRetries: 5,
|
||||
operationsPerInteraction: 3,
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(transport.mock.calls.length / 100).toBeLessThanOrEqual(
|
||||
maxPhysicalRequests,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createTrafficRuntime,
|
||||
defineTrafficBudget,
|
||||
} from "../../../src/platform/traffic/traffic-budget.ts";
|
||||
import { createExecutionContext } from "../../../src/platform/execution/execution-context.ts";
|
||||
|
||||
const POLICY = {
|
||||
maxPhysicalRequests: 4,
|
||||
maxRetries: 1,
|
||||
maxConcurrentRequests: 2,
|
||||
maxQueuedRequests: 2,
|
||||
} as const;
|
||||
|
||||
describe("createTrafficRuntime", () => {
|
||||
it("creates one request, retry, and concurrency budget per interaction", () => {
|
||||
const runtime = createTrafficRuntime(POLICY);
|
||||
|
||||
expect(runtime.requests.maximum).toBe(4);
|
||||
expect(runtime.retries.maximum).toBe(1);
|
||||
expect(runtime.concurrency.maximum).toBe(2);
|
||||
expect(runtime.concurrency.maxQueued).toBe(2);
|
||||
expect(Object.isFrozen(runtime.policy)).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps immutable policy separate from mutable per-interaction counters", () => {
|
||||
const a = createTrafficRuntime(POLICY);
|
||||
const b = createTrafficRuntime(POLICY);
|
||||
a.requests.tryConsume();
|
||||
expect(a.requests.consumed).toBe(1);
|
||||
expect(b.requests.consumed).toBe(0);
|
||||
});
|
||||
|
||||
it("shares one runtime with every child of an execution context", () => {
|
||||
const context = createExecutionContext({
|
||||
interactionId: "shared",
|
||||
deadlineMs: 1_000,
|
||||
traffic: POLICY,
|
||||
});
|
||||
const childA = context.traffic;
|
||||
const childB = context.traffic;
|
||||
childA.retries.tryConsume("a");
|
||||
expect(childB.retries.tryConsume("b")).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["maxPhysicalRequests", Number.POSITIVE_INFINITY],
|
||||
["maxRetries", -1],
|
||||
["maxConcurrentRequests", 0],
|
||||
["maxQueuedRequests", Number.NaN],
|
||||
["maxPhysicalRequests", 65],
|
||||
["maxQueuedRequests", 257],
|
||||
] as const)("rejects %s=%s", (key, value) => {
|
||||
expect(() => defineTrafficBudget({ ...POLICY, [key]: value })).toThrow(
|
||||
new RegExp(key),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { InstalledHttpContract } from "../../../src/contracts/external-contract-runtime.ts";
|
||||
import {
|
||||
checkJsonStructure,
|
||||
JsonBudgetExceededError,
|
||||
parseBoundedJson,
|
||||
validateJsonStructure,
|
||||
} from "../../../src/platform/validation/bounded-json.ts";
|
||||
import { TEST_LIST_HTTP_CONTRACT } from "../../helpers/external-contract-fixture.ts";
|
||||
import {
|
||||
scopeSnapshot,
|
||||
testExecutor,
|
||||
type Transport,
|
||||
} from "../../helpers/traffic-test-kit.ts";
|
||||
|
||||
const BUDGET = {
|
||||
maxBytes: 100,
|
||||
maxItems: 10,
|
||||
maxDepth: 10,
|
||||
maxStringLength: 100,
|
||||
};
|
||||
|
||||
describe("parseBoundedJson", () => {
|
||||
it("rejects oversized input before JSON.parse is invoked", () => {
|
||||
const parse = vi.spyOn(JSON, "parse");
|
||||
const payload = "x".repeat(101);
|
||||
|
||||
expect(() =>
|
||||
parseBoundedJson(payload, {
|
||||
maxBytes: 100,
|
||||
maxItems: 10,
|
||||
maxDepth: 10,
|
||||
maxStringLength: 100,
|
||||
}),
|
||||
).toThrow(/too-large/i);
|
||||
|
||||
expect(parse).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("counts multi-byte characters against the byte ceiling", () => {
|
||||
const payload = `"${"한".repeat(40)}"`; // 42 UTF-16 units, 122 UTF-8 bytes
|
||||
expect(() => parseBoundedJson(payload, BUDGET)).toThrow(/too-large/i);
|
||||
});
|
||||
|
||||
it("parses a payload inside every limit", () => {
|
||||
expect(parseBoundedJson('{"a":[1,2,3]}', BUDGET)).toEqual({ a: [1, 2, 3] });
|
||||
});
|
||||
|
||||
it("reports malformed JSON as a budget error, not a raw SyntaxError", () => {
|
||||
expect(() => parseBoundedJson("{", BUDGET)).toThrow(JsonBudgetExceededError);
|
||||
});
|
||||
});
|
||||
|
||||
describe("validateJsonStructure", () => {
|
||||
it("rejects arrays above maxItems", () => {
|
||||
expect(() => validateJsonStructure([1, 2, 3], { ...BUDGET, maxItems: 2 }))
|
||||
.toThrow(/items/i);
|
||||
});
|
||||
|
||||
it("rejects nesting above maxDepth", () => {
|
||||
let nested: unknown = 1;
|
||||
for (let depth = 0; depth < 5; depth += 1) nested = [nested];
|
||||
expect(() =>
|
||||
validateJsonStructure(nested, { ...BUDGET, maxDepth: 3 }),
|
||||
).toThrow(/deep/i);
|
||||
});
|
||||
|
||||
it("rejects strings above maxStringLength", () => {
|
||||
expect(() =>
|
||||
validateJsonStructure({ name: "x".repeat(11) }, { ...BUDGET, maxStringLength: 10 }),
|
||||
).toThrow(/string/i);
|
||||
});
|
||||
|
||||
it("rejects objects wider than maxItems and counts total nodes", () => {
|
||||
const wide = Object.fromEntries(
|
||||
Array.from({ length: 11 }, (_, index) => [`k${index}`, index]),
|
||||
);
|
||||
expect(checkJsonStructure(wide, BUDGET)).toMatchObject({ ok: false });
|
||||
expect(checkJsonStructure([[1, 2], [3, 4]], { ...BUDGET, maxItems: 6 })).toMatchObject({
|
||||
ok: false,
|
||||
violation: "too-many-items",
|
||||
});
|
||||
});
|
||||
|
||||
it("walks adversarial nesting iteratively without overflowing the stack", () => {
|
||||
let nested: unknown = 0;
|
||||
for (let depth = 0; depth < 200_000; depth += 1) nested = [nested];
|
||||
expect(() =>
|
||||
validateJsonStructure(nested, {
|
||||
maxBytes: 1_000_000,
|
||||
maxItems: 1_000_000,
|
||||
maxDepth: 1_000_000,
|
||||
maxStringLength: 10,
|
||||
}),
|
||||
).not.toThrow();
|
||||
expect(checkJsonStructure(nested, { ...BUDGET, maxItems: 1_000_000 })).toMatchObject({
|
||||
ok: false,
|
||||
violation: "too-deep",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("response structure budget in the V3 executor", () => {
|
||||
const TEST_QUERY = TEST_LIST_HTTP_CONTRACT as InstalledHttpContract<
|
||||
unknown,
|
||||
unknown,
|
||||
unknown
|
||||
>;
|
||||
|
||||
it("rejects a deeply nested response before schema validation runs", async () => {
|
||||
let nested = "0";
|
||||
for (let depth = 0; depth < 100; depth += 1) nested = `[${nested}]`;
|
||||
const safeParse = vi.fn(() => ({ success: true as const, data: [] }));
|
||||
const operation = {
|
||||
...TEST_QUERY,
|
||||
contract: {
|
||||
...TEST_QUERY.contract,
|
||||
outputValidator: { schemaId: "SpyPayload", safeParse },
|
||||
},
|
||||
} as InstalledHttpContract<unknown, unknown, unknown>;
|
||||
const transport = vi.fn<Transport>(
|
||||
async () =>
|
||||
new Response(nested, { headers: { "content-type": "application/json" } }),
|
||||
);
|
||||
|
||||
const outcome = await testExecutor(transport).execute(operation, { limit: 1 }, {
|
||||
routeId: "TEST_ROUTE",
|
||||
scope: scopeSnapshot(),
|
||||
});
|
||||
|
||||
expect(outcome).toMatchObject({
|
||||
kind: "CONTRACT_VIOLATION",
|
||||
violation: { kind: "RESPONSE_TOO_LARGE" },
|
||||
});
|
||||
expect(safeParse).not.toHaveBeenCalled();
|
||||
expect(transport).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
defineValidationBudget,
|
||||
responseValidationBudget,
|
||||
} from "../../../src/platform/validation/validation-budget.ts";
|
||||
|
||||
const BUDGET = {
|
||||
maxBytes: 1_024,
|
||||
maxItems: 1_000,
|
||||
maxDepth: 20,
|
||||
maxStringLength: 32_768,
|
||||
};
|
||||
|
||||
describe("defineValidationBudget", () => {
|
||||
it("rejects unbounded validation configuration", () => {
|
||||
expect(() =>
|
||||
defineValidationBudget({ ...BUDGET, maxBytes: Infinity }),
|
||||
).toThrow(/maxBytes/);
|
||||
});
|
||||
|
||||
it.each(["maxBytes", "maxItems", "maxDepth", "maxStringLength"] as const)(
|
||||
"rejects a non-positive or fractional %s",
|
||||
(key) => {
|
||||
expect(() => defineValidationBudget({ ...BUDGET, [key]: 0 })).toThrow(key);
|
||||
expect(() => defineValidationBudget({ ...BUDGET, [key]: 1.5 })).toThrow(key);
|
||||
expect(() => defineValidationBudget({ ...BUDGET, [key]: Number.NaN })).toThrow(key);
|
||||
},
|
||||
);
|
||||
|
||||
it("returns an immutable copy", () => {
|
||||
const budget = defineValidationBudget(BUDGET);
|
||||
expect(budget).toEqual(BUDGET);
|
||||
expect(Object.isFrozen(budget)).toBe(true);
|
||||
});
|
||||
|
||||
it("derives a finite response structure budget from the byte ceiling", () => {
|
||||
const budget = responseValidationBudget(262_144);
|
||||
expect(budget.maxBytes).toBe(262_144);
|
||||
expect(Number.isSafeInteger(budget.maxItems)).toBe(true);
|
||||
expect(Number.isSafeInteger(budget.maxDepth)).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user