Files
tech-log-frontend/tests/unit/telemetry.test.ts
T
DongHyeonkaandClaude Opus 5 4bff9ca151 chore: sync the frontend template from 4dc033c to 8157ad4
The product was materialized from the template at `4dc033c` and has stayed
on it through 43 template commits, so it was missing all three rounds of
adapter remediation — including files it never had, such as the shared
`abortable-operation` primitive and the `exact-snapshot` decoder that
later fixes are written against. Taking only the newest round was not
possible for that reason: the delta is coherent only as a whole.

The product had not touched `src/adapters` at all since materialization,
so the 140-file delta applied with a three-way merge and no conflicts.
`package.json` was the single overlap and merged cleanly: the product owns
`name`, the template contributed `check:adapter-inventory`,
`check:remediation-ledger` and the image-resolve-signal type fixture.
All 24 product-owned files — README, index.html, CI workflow, i18n
catalog, home page, generated schemas, evidence scripts, component and
visual snapshots — are byte-identical to `main`.

`template.lock.json` now pins the synced revision and tree.

Verified in this repository, not inherited from the template: six type
projects, lint, nine gates (adapter inventory, remediation ledger,
registries, diagnostics, realtime boundaries, architecture, browser
file/storage boundaries, optional recipes, documentation), the production
build, and 2,054 of 2,073 tests. The 19 failures are all in
`tests/unit/ci-artifact-contract.test.ts` and are the same pre-existing
sandbox RLIMIT, EMFILE, umask and `/tmp` permission behaviour the template
records; four suites that failed once under parallel load pass in
isolation.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 12:04:58 +09:00

359 lines
12 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import { createDiagnosticsAdapter } from "../../src/adapters/diagnostics/bounded-diagnostics.ts";
import {
createTelemetryAdapter,
safeTraceparent,
} from "../../src/adapters/telemetry/best-effort-telemetry.ts";
import {
TELEMETRY_REGISTRY,
projectTelemetryEvent,
} from "../../src/contracts/telemetry.ts";
const validAttributes = {
error_kind: "SERVER_FAILURE",
http_status_group: "5xx",
attempt_count_bucket: "3",
route_id: "TEST_ROUTE",
};
describe("telemetry registry and redaction", () => {
it("defines all event contract fields", () => {
for (const definition of Object.values(TELEMETRY_REGISTRY)) {
expect(definition).toEqual(
expect.objectContaining({
eventName: expect.any(String),
trigger: expect.any(String),
requiredAttributes: expect.any(Array),
optionalAttributes: expect.any(Array),
forbiddenAttributes: expect.any(Array),
sampling: expect.any(String),
delivery: "best-effort",
}),
);
}
});
it("redacts forbidden attributes and rejects unknown context", () => {
const projected = projectTelemetryEvent("api.request.failed", {
...validAttributes,
raw_url: "https://api.test/path?token=secret",
});
expect(projected.success).toBe(true);
expect(JSON.stringify(projected)).not.toMatch(/raw_url|token|secret/);
expect(
projectTelemetryEvent("api.request.failed", {
...validAttributes,
unregistered: "private",
}),
).toEqual({ success: false, reason: "unknown-attributes" });
expect(
projectTelemetryEvent("api.request.failed", {
...validAttributes,
route_id: "/users/actual-user-id",
}),
).toEqual({ success: false, reason: "invalid-attribute-value" });
});
it("validates traceparent without exposing invalid values", () => {
expect(
safeTraceparent(
"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
),
).toBe("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01");
expect(safeTraceparent("Bearer secret")).toBeNull();
});
});
describe("best-effort telemetry adapter", () => {
it("bounds the queue using oldest-drop without blocking callers", () => {
const scheduled: Array<() => void> = [];
const adapter = createTelemetryAdapter({
enabled: true,
endpoint: "https://telemetry.test/events",
maxQueue: 2,
schedule: (callback: () => void) => scheduled.push(callback),
fetcher: vi.fn(),
});
adapter.emit("api.request.failed", validAttributes);
adapter.emit("api.request.failed", validAttributes);
adapter.emit("api.request.failed", validAttributes);
expect(adapter.pendingCount()).toBe(2);
expect(adapter.droppedCount()).toBe(1);
expect(adapter.dropReasons()).toEqual({ "queue-full": 1 });
expect(adapter.deliveryEvidence()).toMatchObject({
eventName: "telemetry.delivery.dropped",
attributes: { reason: "queue-full", queue_size_bucket: "1-10" },
});
expect(scheduled).toHaveLength(1);
});
it("degrades on sink failure without throwing or recursive events", async () => {
const onDrop = vi.fn(() => {
throw new Error("observer unavailable");
});
const adapter = createTelemetryAdapter({
enabled: true,
endpoint: "https://telemetry.test/events",
schedule: () => {},
fetcher: async () => {
throw new Error("sink unavailable");
},
onDrop,
});
expect(() => adapter.emit("api.request.failed", validAttributes)).not.toThrow();
await expect(adapter.flush()).resolves.toBeUndefined();
expect(adapter.droppedCount()).toBe(1);
expect(adapter.dropReasons()).toEqual({ "sink-failure": 1 });
expect(onDrop).toHaveBeenCalledOnce();
expect(adapter.pendingCount()).toBe(0);
});
it("reschedules events whose flush callback runs during an active delivery", async () => {
const scheduled: Array<() => void> = [];
const deliveredRouteIds: unknown[][] = [];
let releaseFirstDelivery: () => void = () => {};
const firstDelivery = new Promise<void>((resolve) => {
releaseFirstDelivery = resolve;
});
let deliveryCount = 0;
const fetcher = vi.fn(async (_endpoint: RequestInfo | URL, init?: RequestInit) => {
deliveryCount += 1;
const body = JSON.parse(String(init?.body));
deliveredRouteIds.push(
(body.events as Array<{ attributes: { route_id: unknown } }>).map(
(event) => event.attributes.route_id,
),
);
if (deliveryCount === 1) {
await firstDelivery;
}
return new Response(null, { status: 204 });
});
const adapter = createTelemetryAdapter({
enabled: true,
endpoint: "https://telemetry.test/events",
schedule: (callback: () => void) => scheduled.push(callback),
fetcher,
});
const runScheduled = () => {
const callback = scheduled.shift();
if (!callback) throw new Error("Expected a scheduled telemetry flush");
callback();
};
adapter.emit("api.request.failed", {
...validAttributes,
route_id: "FIRST_ROUTE",
});
runScheduled();
await vi.waitFor(() => expect(fetcher).toHaveBeenCalledOnce());
adapter.emit("api.request.failed", {
...validAttributes,
route_id: "SECOND_ROUTE",
});
runScheduled();
expect(fetcher).toHaveBeenCalledOnce();
expect(adapter.pendingCount()).toBe(1);
releaseFirstDelivery();
await vi.waitFor(() => expect(scheduled).toHaveLength(1));
runScheduled();
await vi.waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));
expect(adapter.pendingCount()).toBe(0);
expect(deliveredRouteIds).toEqual([["FIRST_ROUTE"], ["SECOND_ROUTE"]]);
});
it("never serializes circular or unbounded event context", () => {
const adapter = createTelemetryAdapter({
enabled: true,
endpoint: "https://telemetry.test/events",
schedule: () => {},
});
const circular: Record<string, unknown> = {};
circular.self = circular;
const hostile = new Proxy(
{},
{
ownKeys() {
throw new Error("private proxy value");
},
},
);
expect(() =>
adapter.emit("api.request.failed", {
...validAttributes,
unregistered: circular,
}),
).not.toThrow();
expect(adapter.pendingCount()).toBe(0);
expect(adapter.dropReasons()).toEqual({ "invalid-context": 1 });
expect(() =>
adapter.emit("api.request.failed", hostile),
).not.toThrow();
expect(adapter.dropReasons()).toEqual({
"invalid-context": 1,
"serialization-failure": 1,
});
});
it("performs no network or queue work when disabled", async () => {
const fetcher = vi.fn();
const adapter = createTelemetryAdapter({
enabled: false,
endpoint: "https://telemetry.test/events",
fetcher,
});
adapter.emit("api.request.failed", validAttributes);
await adapter.flush();
expect(fetcher).not.toHaveBeenCalled();
expect(adapter.pendingCount()).toBe(0);
});
it("flushes on page exit and removes the lifecycle listener", async () => {
const lifecycle = new EventTarget();
const remove = vi.spyOn(lifecycle, "removeEventListener");
const fetcher = vi.fn(async () => new Response(null, { status: 204 }));
const adapter = createTelemetryAdapter({
enabled: true,
endpoint: "https://telemetry.test/events",
schedule: () => {},
lifecycle,
fetcher,
});
adapter.emit("api.request.failed", validAttributes);
lifecycle.dispatchEvent(new Event("pagehide"));
await vi.waitFor(() => expect(fetcher).toHaveBeenCalledOnce());
adapter.dispose();
expect(adapter.pendingCount()).toBe(0);
expect(remove).toHaveBeenCalledWith("pagehide", expect.any(Function));
});
it("drops queued events and invalidates scheduled callbacks on dispose", async () => {
const callbacks: Array<() => void> = [];
const fetcher = vi.fn(async () => new Response(null, { status: 204 }));
const adapter = createTelemetryAdapter({
enabled: true,
endpoint: "https://telemetry.test/events",
schedule: (callback) => callbacks.push(callback),
fetcher,
});
adapter.emit("api.request.failed", validAttributes);
expect(adapter.pendingCount()).toBe(1);
adapter.dispose();
expect(adapter.pendingCount()).toBe(0);
for (const callback of callbacks) callback();
await Promise.resolve();
expect(fetcher).not.toHaveBeenCalled();
// Disposal is a silent shutdown, not a recursive drop event.
expect(adapter.dropReasons()).toEqual({});
});
it("ignores emit after dispose", async () => {
const fetcher = vi.fn(async () => new Response(null, { status: 204 }));
const adapter = createTelemetryAdapter({
enabled: true,
endpoint: "https://telemetry.test/events",
schedule: () => {},
fetcher,
});
adapter.dispose();
adapter.emit("api.request.failed", validAttributes);
await adapter.flush();
expect(adapter.pendingCount()).toBe(0);
expect(fetcher).not.toHaveBeenCalled();
});
it("aborts an in-flight sink and prevents post-dispose rescheduling", async () => {
const callbacks: Array<() => void> = [];
let observedSignal: AbortSignal | undefined;
let releaseSink: (() => void) | undefined;
const fetcher = vi.fn(async (_input: unknown, init?: RequestInit) => {
observedSignal = init?.signal ?? undefined;
await new Promise<void>((resolve) => {
releaseSink = resolve;
});
return new Response(null, { status: 204 });
});
const adapter = createTelemetryAdapter({
enabled: true,
endpoint: "https://telemetry.test/events",
schedule: (callback) => callbacks.push(callback),
fetcher: fetcher as unknown as typeof fetch,
});
adapter.emit("api.request.failed", validAttributes);
callbacks.splice(0).forEach((callback) => callback());
await vi.waitFor(() => expect(fetcher).toHaveBeenCalledOnce());
adapter.dispose();
expect(observedSignal?.aborted).toBe(true);
// The sink ignored the abort and settles late.
releaseSink?.();
await Promise.resolve();
await Promise.resolve();
expect(callbacks).toHaveLength(0);
expect(fetcher).toHaveBeenCalledOnce();
});
it("joins an already active flush", async () => {
let releaseSink: (() => void) | undefined;
const fetcher = vi.fn(async () => {
await new Promise<void>((resolve) => {
releaseSink = resolve;
});
return new Response(null, { status: 204 });
});
const adapter = createTelemetryAdapter({
enabled: true,
endpoint: "https://telemetry.test/events",
schedule: () => {},
fetcher: fetcher as unknown as typeof fetch,
});
adapter.emit("api.request.failed", validAttributes);
const first = adapter.flush();
await vi.waitFor(() => expect(fetcher).toHaveBeenCalledOnce());
let secondSettled = false;
const second = adapter.flush().then(() => {
secondSettled = true;
});
await Promise.resolve();
expect(secondSettled).toBe(false);
releaseSink?.();
await first;
await second;
expect(secondSettled).toBe(true);
adapter.dispose();
});
it.each([Number.NaN, Number.POSITIVE_INFINITY, 0, -1, 1.5])(
"rejects invalid telemetry and diagnostics capacity %s",
(value) => {
expect(() =>
createTelemetryAdapter({
enabled: true,
endpoint: "https://telemetry.test/events",
maxQueue: value,
}),
).toThrow(TypeError);
expect(() => createDiagnosticsAdapter({ maxEntries: value })).toThrow(
TypeError,
);
},
);
});