Files
tech-log-frontend/tests/unit/telemetry.test.ts
DongHyeonka c80320dfc7 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)
2026-11-12 08:28:54 +09:00

807 lines
26 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 {
createFeatureTelemetry,
createFetchTelemetryTransport,
} from "../../src/adapters/telemetry/feature-telemetry.ts";
import { createTelemetryCollector } from "../../src/adapters/telemetry/telemetry-collector.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,
);
},
);
});
describe("telemetry collector payloads (Q-6.9-4)", () => {
function recordingFetcher() {
const calls: Array<Readonly<{ url: string; init: RequestInit }>> = [];
const fetcher = vi.fn(async (url: RequestInfo | URL, init?: RequestInit) => {
calls.push({ url: String(url), init: init ?? {} });
return new Response(null, { status: 204 });
});
return { calls, fetcher: fetcher as unknown as typeof fetch };
}
it("posts the contract projection for the application port", async () => {
const { calls, fetcher } = recordingFetcher();
const adapter = createTelemetryAdapter({
enabled: true,
endpoint: "https://telemetry.test/events",
schedule: () => {},
now: () => Date.parse("2026-09-24T00:00:00.000Z"),
fetcher,
});
adapter.emit("api.request.failed", validAttributes);
await adapter.flush();
expect(calls).toHaveLength(1);
expect(calls[0]?.url).toBe("https://telemetry.test/events");
expect(calls[0]?.init).toMatchObject({
method: "POST",
headers: { "Content-Type": "application/json" },
keepalive: true,
});
expect(JSON.parse(String(calls[0]?.init.body))).toEqual({
events: [
{
eventName: "api.request.failed",
timestamp: "2026-09-24T00:00:00.000Z",
attributes: validAttributes,
},
],
});
adapter.dispose();
});
it("posts the pipeline projection for the feature port", async () => {
const { calls, fetcher } = recordingFetcher();
const transport = createFetchTelemetryTransport({
endpoint: "https://telemetry.test/events",
fetcher,
});
await transport.send([
{
event: { kind: "catalog.load.failed", severity: "error", featureId: "catalog" },
fingerprint: "fp-1",
occurrences: 3,
},
]);
expect(calls).toHaveLength(1);
expect(calls[0]?.url).toBe("https://telemetry.test/events");
expect(calls[0]?.init).toMatchObject({
method: "POST",
headers: { "Content-Type": "application/json" },
keepalive: true,
credentials: "omit",
cache: "no-store",
});
expect(JSON.parse(String(calls[0]?.init.body))).toEqual({
events: [
{
kind: "catalog.load.failed",
severity: "error",
featureId: "catalog",
fingerprint: "fp-1",
occurrences: 3,
},
],
});
});
it("rejects a feature batch the collector refuses", async () => {
const transport = createFetchTelemetryTransport({
endpoint: "https://telemetry.test/events",
fetcher: (async () => new Response(null, { status: 503 })) as typeof fetch,
});
await expect(transport.send([])).rejects.toThrow();
});
});
describe("one collector transport for both telemetry ports (Q-6.9-4)", () => {
const featureEvent = {
kind: "catalog.load.failed",
severity: "error",
featureId: "catalog",
} as const;
const hungFetcher = () => {
const signals: AbortSignal[] = [];
// Never settles and ignores its signal: only the collector can end it.
const fetcher = vi.fn((_url: RequestInfo | URL, init?: RequestInit) => {
if (init?.signal) signals.push(init.signal);
return new Promise<Response>(() => {});
});
return { signals, fetcher: fetcher as unknown as typeof fetch, calls: fetcher };
};
it("sends application telemetry without cookies or HTTP cache", async () => {
const fetcher = vi.fn(async () => 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);
await adapter.flush();
expect(fetcher).toHaveBeenCalledWith(
"https://telemetry.test/events",
expect.objectContaining({ credentials: "omit", cache: "no-store" }),
);
adapter.dispose();
});
it("times out a hung collector so later application flushes still send", async () => {
const { fetcher, calls } = hungFetcher();
const collector = createTelemetryCollector({
endpoint: "https://telemetry.test/events",
fetcher,
timeoutMs: 5,
});
const adapter = createTelemetryAdapter({
enabled: true,
endpoint: "https://telemetry.test/events",
schedule: () => {},
collector,
});
adapter.emit("api.request.failed", validAttributes);
await adapter.flush();
expect(adapter.dropReasons()).toEqual({ "sink-failure": 1 });
adapter.emit("api.request.failed", validAttributes);
await adapter.flush();
expect(calls).toHaveBeenCalledTimes(2);
adapter.dispose();
});
it("times out a hung collector for feature telemetry", async () => {
const { fetcher } = hungFetcher();
const telemetry = createFeatureTelemetry({
enabled: true,
endpoint: "https://telemetry.test/events",
collector: createTelemetryCollector({
endpoint: "https://telemetry.test/events",
fetcher,
timeoutMs: 5,
}),
});
await telemetry.emit(featureEvent);
await telemetry.flush();
expect(telemetry.stats()).toMatchObject({ sends: 1, failedSends: 1 });
telemetry.dispose();
});
it("shares one send-rate window between the two ports", async () => {
const fetcher = vi.fn(async () => new Response(null, { status: 204 }));
const collector = createTelemetryCollector({
endpoint: "https://telemetry.test/events",
fetcher: fetcher as unknown as typeof fetch,
maxSendsPerMinute: 1,
});
const adapter = createTelemetryAdapter({
enabled: true,
endpoint: "https://telemetry.test/events",
schedule: () => {},
setTimer: () => 0,
clearTimer: () => {},
collector,
});
const telemetry = createFeatureTelemetry({
enabled: true,
endpoint: "https://telemetry.test/events",
collector,
});
adapter.emit("api.request.failed", validAttributes);
await adapter.flush();
await telemetry.emit(featureEvent);
await telemetry.flush();
expect(fetcher).toHaveBeenCalledOnce();
expect(telemetry.stats().buffered).toBe(1);
adapter.dispose();
telemetry.dispose();
});
it("flushes feature telemetry on page exit and stops listening on dispose", async () => {
const lifecycle = new EventTarget();
const remove = vi.spyOn(lifecycle, "removeEventListener");
const fetcher = vi.fn(async () => new Response(null, { status: 204 }));
const telemetry = createFeatureTelemetry({
enabled: true,
endpoint: "https://telemetry.test/events",
collector: createTelemetryCollector({
endpoint: "https://telemetry.test/events",
fetcher: fetcher as unknown as typeof fetch,
lifecycle,
}),
});
await telemetry.emit(featureEvent);
await vi.waitFor(() => expect(fetcher).toHaveBeenCalledOnce());
// A duplicate is held until the next flush; page exit is that flush.
await telemetry.emit(featureEvent);
expect(fetcher).toHaveBeenCalledOnce();
lifecycle.dispatchEvent(new Event("pagehide"));
await vi.waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));
telemetry.dispose();
expect(remove).toHaveBeenCalledWith("pagehide", expect.any(Function));
});
it("aborts an in-flight feature batch on dispose", async () => {
const { fetcher, signals } = hungFetcher();
const telemetry = createFeatureTelemetry({
enabled: true,
endpoint: "https://telemetry.test/events",
fetcher,
});
await telemetry.emit(featureEvent);
await vi.waitFor(() => expect(signals).toHaveLength(1));
telemetry.dispose();
expect(signals[0]?.aborted).toBe(true);
});
});
/**
* 13-11. Failures must be attributable to a release while old and new tabs
* coexist, so every event the collector sends carries both identities.
*/
describe("collector release identity (13-11)", () => {
it("stamps build_id and release_id on every event of both ports", async () => {
const bodies: { events: Record<string, unknown>[] }[] = [];
const fetcher = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
bodies.push(JSON.parse(String(init?.body)));
return new Response(null, { status: 204 });
});
const collector = createTelemetryCollector({
endpoint: "https://telemetry.test/events",
fetcher: fetcher as unknown as typeof fetch,
release: { buildId: "build-a", releaseId: "release-a" },
});
const adapter = createTelemetryAdapter({
enabled: true,
endpoint: "https://telemetry.test/events",
schedule: () => {},
collector,
});
adapter.emit("api.request.failed", validAttributes);
await adapter.flush();
await createFetchTelemetryTransport({
endpoint: "https://telemetry.test/events",
collector,
}).send([
{
event: { kind: "catalog.load.failed", severity: "error", featureId: "catalog" },
fingerprint: "fp-1",
occurrences: 1,
},
]);
// A split batch keeps the identity on every part.
await collector.post(
Array.from({ length: 70 }, (_, index) => ({ index, padding: "x".repeat(1_000) })),
);
const events = bodies.flatMap((body) => body.events);
expect(bodies.length).toBeGreaterThan(3);
expect(events).toHaveLength(72);
for (const sent of events) {
expect(sent).toMatchObject({ build_id: "build-a", release_id: "release-a" });
}
adapter.dispose();
});
});
/**
* 03-05. Fetch fails every keepalive request once the in-flight keepalive
* bodies exceed 64KiB, so a large queue must be split and the collector must
* never have more than that in flight with keepalive.
*/
describe("collector keepalive budget (03-05)", () => {
const KEEPALIVE_QUOTA = 64 * 1024;
const utf8 = new TextEncoder();
function recordingFetcher() {
const sent: { bytes: number; keepalive: boolean; events: number }[] = [];
let inflightKeepalive = 0;
let peakKeepalive = 0;
const releases: Array<() => void> = [];
const fetcher = vi.fn((_url: RequestInfo | URL, init?: RequestInit) => {
const body = String(init?.body);
const bytes = utf8.encode(body).byteLength;
const keepalive = init?.keepalive === true;
sent.push({
bytes,
keepalive,
events: (JSON.parse(body) as { events: unknown[] }).events.length,
});
if (keepalive) inflightKeepalive += bytes;
peakKeepalive = Math.max(peakKeepalive, inflightKeepalive);
return new Promise<Response>((resolve) => {
releases.push(() => {
if (keepalive) inflightKeepalive -= bytes;
resolve(new Response(null, { status: 204 }));
});
});
});
return {
sent,
peak: () => peakKeepalive,
releaseAll: () => releases.splice(0).forEach((release) => release()),
fetcher: fetcher as unknown as typeof fetch,
};
}
const bigEvents = (count: number) =>
Array.from({ length: count }, (_, index) => ({
index,
padding: "x".repeat(1_000),
}));
it("splits a queue over the keepalive limit into posts that all arrive", async () => {
const recording = recordingFetcher();
const collector = createTelemetryCollector({
endpoint: "https://telemetry.test/events",
fetcher: recording.fetcher,
});
const delivered = collector.post(bigEvents(70));
await vi.waitFor(() => expect(recording.sent.length).toBeGreaterThan(1));
recording.releaseAll();
await delivered;
expect(recording.sent.every((post) => post.bytes <= KEEPALIVE_QUOTA)).toBe(
true,
);
expect(recording.sent.reduce((sum, post) => sum + post.events, 0)).toBe(70);
expect(recording.peak()).toBeLessThanOrEqual(KEEPALIVE_QUOTA);
});
it("keeps concurrent posts under one keepalive quota", async () => {
const recording = recordingFetcher();
const collector = createTelemetryCollector({
endpoint: "https://telemetry.test/events",
fetcher: recording.fetcher,
});
// Two queues flushing together, as on pagehide.
const first = collector.post(bigEvents(40));
const second = collector.post(bigEvents(40));
await vi.waitFor(() => expect(recording.sent.length).toBeGreaterThan(1));
recording.releaseAll();
await Promise.all([first, second]);
expect(recording.peak()).toBeLessThanOrEqual(KEEPALIVE_QUOTA);
expect(recording.sent.some((post) => post.keepalive)).toBe(true);
expect(recording.sent.reduce((sum, post) => sum + post.events, 0)).toBe(80);
});
});
describe("telemetry adapter send-rate limit (spec §27)", () => {
function harness(maxSendsPerMinute = 3) {
let now = 0;
const timers: Array<() => void> = [];
const lifecycle = new EventTarget();
const fetcher = vi.fn(async () => new Response(null, { status: 204 }));
const adapter = createTelemetryAdapter({
enabled: true,
endpoint: "https://telemetry.test/events",
schedule: () => {},
fetcher,
lifecycle,
maxSendsPerMinute,
monotonicNow: () => now,
setTimer: (callback) => {
timers.push(callback);
return timers.length;
},
clearTimer: () => {},
});
return {
adapter,
fetcher,
lifecycle,
timers,
advance(ms: number) {
now += ms;
},
};
}
it("caps collector sends per minute during a sustained failure storm", async () => {
const { adapter, fetcher } = harness(3);
for (let i = 0; i < 25; i += 1) {
adapter.emit("api.request.failed", validAttributes);
await adapter.flush();
}
expect(fetcher).toHaveBeenCalledTimes(3);
expect(adapter.pendingCount()).toBeLessThanOrEqual(100);
});
it("delivers held events once the window reopens", async () => {
const { adapter, fetcher, timers, advance } = harness(1);
adapter.emit("api.request.failed", validAttributes);
await adapter.flush();
adapter.emit("api.request.failed", validAttributes);
await adapter.flush();
expect(fetcher).toHaveBeenCalledTimes(1);
expect(timers).toHaveLength(1);
advance(60_000);
timers.shift()?.();
await vi.waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));
expect(adapter.pendingCount()).toBe(0);
});
it("still delivers once on page exit when the window is exhausted", async () => {
const { adapter, fetcher, lifecycle } = harness(1);
adapter.emit("api.request.failed", validAttributes);
await adapter.flush();
adapter.emit("api.request.failed", validAttributes);
lifecycle.dispatchEvent(new Event("pagehide"));
await vi.waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));
adapter.dispose();
});
it("rejects an unbounded send rate", () => {
expect(() =>
createTelemetryAdapter({
enabled: true,
endpoint: "https://telemetry.test/events",
maxSendsPerMinute: Number.POSITIVE_INFINITY,
}),
).toThrow(TypeError);
});
});