chore: initialize from frontend template 4dc033c
This commit is contained in:
@@ -0,0 +1,182 @@
|
||||
import { projectTelemetryEvent } from "../../contracts/telemetry.ts";
|
||||
import { queueSizeBucket } from "../../contracts/diagnostic-buckets.ts";
|
||||
import type {
|
||||
TelemetryEvent,
|
||||
TelemetryEventName,
|
||||
} from "../../contracts/telemetry.ts";
|
||||
import type { TelemetryPort } from "../../application/ports/telemetry-port.ts";
|
||||
|
||||
export type TelemetryAdapter = TelemetryPort &
|
||||
Readonly<{
|
||||
flush(): Promise<void>;
|
||||
pendingCount(): number;
|
||||
droppedCount(): number;
|
||||
dropReasons(): Readonly<Record<string, number>>;
|
||||
deliveryEvidence(): TelemetryEvent | null;
|
||||
dispose(): void;
|
||||
}>;
|
||||
|
||||
export type TelemetryAdapterOptions = Readonly<{
|
||||
enabled: boolean;
|
||||
endpoint?: string;
|
||||
fetcher?: typeof fetch;
|
||||
maxQueue?: number;
|
||||
schedule?: (callback: () => void) => void;
|
||||
now?: () => number;
|
||||
onDrop?: (event: TelemetryEvent) => void;
|
||||
lifecycle?: Pick<EventTarget, "addEventListener" | "removeEventListener">;
|
||||
}>;
|
||||
|
||||
export const noOpTelemetry: TelemetryAdapter = Object.freeze({
|
||||
emit: () => {},
|
||||
flush: async () => {},
|
||||
pendingCount: () => 0,
|
||||
droppedCount: () => 0,
|
||||
dropReasons: () => Object.freeze({}),
|
||||
deliveryEvidence: () => null,
|
||||
dispose: () => {},
|
||||
});
|
||||
|
||||
export function createTelemetryAdapter(
|
||||
options: TelemetryAdapterOptions,
|
||||
): TelemetryAdapter {
|
||||
if (!options.enabled || !options.endpoint) {
|
||||
return noOpTelemetry;
|
||||
}
|
||||
|
||||
const endpoint = options.endpoint;
|
||||
const fetcher = options.fetcher ?? fetch;
|
||||
const maxQueue = Math.max(1, options.maxQueue ?? 100);
|
||||
const schedule = options.schedule ?? queueMicrotask;
|
||||
const queue: TelemetryEvent[] = [];
|
||||
let scheduled = false;
|
||||
let flushing = false;
|
||||
let dropped = 0;
|
||||
const dropReasons = new Map<string, number>();
|
||||
let lastDeliveryEvidence: TelemetryEvent | null = null;
|
||||
const lifecycle =
|
||||
options.lifecycle ??
|
||||
(typeof globalThis.addEventListener === "function" &&
|
||||
typeof globalThis.removeEventListener === "function"
|
||||
? globalThis
|
||||
: undefined);
|
||||
|
||||
function recordDrop(reason: string, count = 1): void {
|
||||
const safeReason =
|
||||
{
|
||||
"queue-full": "queue-full",
|
||||
"sink-failure": "sink-failure",
|
||||
"serialization-failure": "serialization-failure",
|
||||
"unknown-attributes": "invalid-context",
|
||||
"invalid-attribute-value": "invalid-context",
|
||||
"missing-required-attributes": "invalid-context",
|
||||
"unregistered-event": "invalid-event",
|
||||
}[reason] ?? "invalid-event";
|
||||
dropped += count;
|
||||
dropReasons.set(safeReason, (dropReasons.get(safeReason) ?? 0) + count);
|
||||
const internal = projectTelemetryEvent(
|
||||
"telemetry.delivery.dropped",
|
||||
{
|
||||
reason: safeReason,
|
||||
queue_size_bucket: queueSizeBucket(queue.length),
|
||||
},
|
||||
options.now,
|
||||
);
|
||||
if (internal.success) {
|
||||
lastDeliveryEvidence = internal.event;
|
||||
try {
|
||||
options.onDrop?.(internal.event);
|
||||
} catch {
|
||||
// Drop observers are deliberately nonrecursive.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleFlush(): void {
|
||||
if (scheduled) return;
|
||||
scheduled = true;
|
||||
schedule(() => {
|
||||
scheduled = false;
|
||||
void flush();
|
||||
});
|
||||
}
|
||||
|
||||
function emit(
|
||||
eventName: TelemetryEventName,
|
||||
attributes: Record<string, unknown>,
|
||||
): void {
|
||||
const projected = projectTelemetryEvent(
|
||||
eventName,
|
||||
attributes,
|
||||
options.now,
|
||||
);
|
||||
if (!projected.success) {
|
||||
recordDrop(projected.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
if (queue.length >= maxQueue) {
|
||||
queue.shift();
|
||||
recordDrop("queue-full");
|
||||
}
|
||||
queue.push(projected.event);
|
||||
|
||||
scheduleFlush();
|
||||
}
|
||||
|
||||
async function flush(): Promise<void> {
|
||||
if (flushing || queue.length === 0) return;
|
||||
flushing = true;
|
||||
const batch = queue.splice(0, queue.length);
|
||||
try {
|
||||
const response = await fetcher(endpoint, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ events: batch }),
|
||||
keepalive: true,
|
||||
});
|
||||
if (!response.ok) recordDrop("sink-failure", batch.length);
|
||||
} catch {
|
||||
recordDrop("sink-failure", batch.length);
|
||||
} finally {
|
||||
flushing = false;
|
||||
if (queue.length > 0) {
|
||||
scheduleFlush();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const flushBeforePageExit = () => {
|
||||
void flush();
|
||||
};
|
||||
lifecycle?.addEventListener("pagehide", flushBeforePageExit);
|
||||
|
||||
function dispose(): void {
|
||||
lifecycle?.removeEventListener("pagehide", flushBeforePageExit);
|
||||
}
|
||||
|
||||
return Object.freeze({
|
||||
emit,
|
||||
flush,
|
||||
pendingCount: () => queue.length,
|
||||
droppedCount: () => dropped,
|
||||
dropReasons: () => Object.freeze(Object.fromEntries(dropReasons)),
|
||||
deliveryEvidence: () =>
|
||||
lastDeliveryEvidence ? structuredClone(lastDeliveryEvidence) : null,
|
||||
dispose,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Propagates only a structurally valid W3C traceparent. Invalid/raw headers are
|
||||
* discarded rather than logged or surfaced.
|
||||
*
|
||||
*/
|
||||
export function safeTraceparent(
|
||||
traceparent: string | null | undefined,
|
||||
): string | null {
|
||||
return typeof traceparent === "string" &&
|
||||
/^00-[0-9a-f]{32}-[0-9a-f]{16}-0[01]$/i.test(traceparent)
|
||||
? traceparent.toLowerCase()
|
||||
: null;
|
||||
}
|
||||
Reference in New Issue
Block a user