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 at 8210d48.

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 at
8210d48 first 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:
DongHyeonka
2026-11-12 08:28:54 +09:00
parent 585c62431a
commit c80320dfc7
738 changed files with 55027 additions and 13567 deletions
@@ -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();
});
});