feat: add diagnostics and telemetry runtime

This commit is contained in:
donghyeon-ka
2026-07-26 16:42:27 +09:00
parent 2fa0baa577
commit 5173b6c8d6
43 changed files with 1760 additions and 116 deletions
@@ -0,0 +1,102 @@
import type { DiagnosticsPort } from "../../application/ports/diagnostics-port.js";
import {
projectDiagnosticRecord,
safeErrorKind,
type DiagnosticRecord,
type DiagnosticRecordInput,
} from "../../contracts/diagnostics.js";
import { projectTelemetryEvent } from "../../contracts/telemetry.js";
export const noOpDiagnostics: DiagnosticsPort = Object.freeze({
record() {},
});
export function createDiagnosticsAdapter(
options: Readonly<{
maxEntries?: number;
now?: () => number;
sink?: (record: DiagnosticRecord) => void;
}> = {},
) {
const maxEntries = Math.max(1, options.maxEntries ?? 100);
const entries: DiagnosticRecord[] = [];
const droppedReasons = new Map<string, number>();
function drop(reason: string) {
droppedReasons.set(reason, (droppedReasons.get(reason) ?? 0) + 1);
}
function record(input: DiagnosticRecordInput) {
try {
const projected = projectDiagnosticRecord(input, options.now);
if (!projected.success) {
drop(projected.reason);
return;
}
if (entries.length >= maxEntries) {
entries.shift();
drop("queue-full");
}
entries.push(projected.record);
try {
options.sink?.(projected.record);
} catch {
drop("sink-failure");
}
} catch {
drop("serialization-failure");
}
}
return Object.freeze({
record,
entries: () => structuredClone(entries) as readonly DiagnosticRecord[],
dropped: () => Object.freeze(Object.fromEntries(droppedReasons)),
});
}
type BootSafeContext = Readonly<{
kind?: string;
buildId?: string;
configSchemaVersion?: string;
supportReference?: string;
}>;
let lastBootEvidence:
| Readonly<{
diagnostic: DiagnosticRecord | null;
telemetry: Readonly<Record<string, unknown>> | null;
}>
| undefined;
export function recordBootFailure(
error: unknown,
safe: BootSafeContext,
now: () => number = Date.now,
) {
const errorKind =
typeof safe.kind === "string" ? safe.kind : safeErrorKind(error);
const attributes = {
error_kind: errorKind,
build_id: safe.buildId ?? "unknown",
config_schema_version: safe.configSchemaVersion ?? "unknown",
};
const diagnostic = projectDiagnosticRecord(
{
level: "error",
eventId: "app.boot.failed",
context: attributes,
},
now,
);
const telemetry = projectTelemetryEvent("app.boot.failed", attributes, now);
lastBootEvidence = Object.freeze({
diagnostic: diagnostic.success ? diagnostic.record : null,
telemetry: telemetry.success ? telemetry.event : null,
});
return lastBootEvidence;
}
export function getLastBootEvidence() {
return lastBootEvidence ? structuredClone(lastBootEvidence) : undefined;
}
+98 -20
View File
@@ -14,6 +14,11 @@ import {
validateOperationRequest,
} from "./schema-registry.js";
import { buildRequestTarget } from "./request-builder.js";
import {
attemptBucket,
durationBucket,
statusGroup,
} from "../../contracts/diagnostics.js";
const noAuthSession =
/** @type {import("../../application/ports/auth-session-port.js").AuthSessionPort} */ ({
@@ -54,7 +59,10 @@ const noAuthSession =
* timeoutMs?: number,
* maxRetryAttempts?: number,
* scheduler?: Scheduler,
* getOperation?: typeof getApiOperation
* getOperation?: typeof getApiOperation,
* diagnostics?: import("../../application/ports/diagnostics-port.js").DiagnosticsPort,
* telemetry?: import("../../application/ports/telemetry-port.js").TelemetryPort,
* correlationIdFactory?: () => string
* }} dependencies
*/
export function createHttpClient(dependencies) {
@@ -72,6 +80,11 @@ export function createHttpClient(dependencies) {
const defaultTimeoutMs = dependencies.timeoutMs ?? 10_000;
const maxRetryAttempts = dependencies.maxRetryAttempts ?? 2;
const selectOperation = dependencies.getOperation ?? getApiOperation;
const diagnostics = dependencies.diagnostics;
const telemetry = dependencies.telemetry;
const correlationIdFactory =
dependencies.correlationIdFactory ??
(() => `request-${Math.floor(random() * 1_000_000).toString(36)}`);
const scheduler =
dependencies.scheduler ??
/** @type {Scheduler} */ ({
@@ -91,7 +104,8 @@ export function createHttpClient(dependencies) {
* pathParams?: Record<string, string | number>,
* searchParams?: unknown,
* signal?: AbortSignal,
* idempotencyKey?: string
* idempotencyKey?: string,
* correlationId?: string
* }} [legacyInput]
* @returns {Promise<HttpResult>}
*/
@@ -106,9 +120,55 @@ export function createHttpClient(dependencies) {
body: legacyInput.body,
signal: legacyInput.signal,
idempotencyKey: legacyInput.idempotencyKey,
correlationId: legacyInput.correlationId,
}
: request;
const operation = selectOperation(input.operationId);
const startedAt = clock.now();
const correlationId = input.correlationId ?? correlationIdFactory();
/**
* @param {HttpResult} outcome
* @param {"success" | "recovered" | "failed" | "aborted"} outcomeKind
*/
function finalize(outcome, outcomeKind) {
const error = outcome.ok ? undefined : outcome.error;
const context = {
route_id: input.routeId,
operation_id: input.operationId,
correlation_id: correlationId,
outcome: outcomeKind,
error_kind: error?.kind ?? "NONE",
http_status_group: statusGroup(error?.httpStatus),
attempt_count_bucket: attemptBucket(
error?.attemptCount ?? retryCount + 1,
),
duration_bucket: durationBucket(clock.now() - startedAt),
};
try {
diagnostics?.record({
level: error ? "warn" : "info",
eventId: "http.request.completed",
context,
});
} catch {
// Diagnostics cannot change the HTTP result.
}
if (error && outcomeKind !== "aborted") {
try {
telemetry?.emit("api.request.failed", {
error_kind: context.error_kind,
http_status_group: context.http_status_group,
attempt_count_bucket: context.attempt_count_bucket,
route_id: context.route_id,
operation_id: context.operation_id,
duration_bucket: context.duration_bucket,
});
} catch {
// Telemetry cannot change the HTTP result.
}
}
return outcome;
}
const logicalIdempotencyKey =
operation.idempotency === "keyed"
? input.idempotencyKey ?? idempotencyKeyFactory()
@@ -126,28 +186,40 @@ export function createHttpClient(dependencies) {
idempotencyKey: logicalIdempotencyKey,
});
if (outcome.ok) return outcome;
if (outcome.ok) {
return finalize(
outcome,
retryCount > 0 || recoveryUsed ? "recovered" : "success",
);
}
if (outcome.error.httpStatus === 401 && !recoveryUsed) {
recoveryUsed = true;
const recovered = await recoverSession(authSession, operation, outcome.error);
if (!recovered.ok) return recovered;
const recovered = await recoverSession(
authSession,
operation,
outcome.error,
);
if (!recovered.ok) return finalize(recovered, "failed");
if (operation.idempotency === "none") {
return {
ok: false,
error: {
...outcome.error,
retryable: false,
action: "retry",
return finalize(
{
ok: false,
error: {
...outcome.error,
retryable: false,
action: "retry",
},
},
};
"failed",
);
}
continue;
}
if (outcome.error.httpStatus === 401 && recoveryUsed) {
authSession.onUnauthenticated();
return outcome;
return finalize(outcome, "failed");
}
if (
@@ -158,7 +230,10 @@ export function createHttpClient(dependencies) {
maxRetryAttempts,
)
) {
return outcome;
return finalize(
outcome,
outcome.error.kind === "REQUEST_ABORTED" ? "aborted" : "failed",
);
}
const delay = retryDelay(outcome.error, retryCount, random, clock.now());
@@ -167,12 +242,15 @@ export function createHttpClient(dependencies) {
try {
await clock.sleep(delay, input.signal);
} catch {
return {
ok: false,
error: failure("REQUEST_ABORTED", input.operationId, retryCount, {
code: "REQUEST_ABORTED",
}),
};
return finalize(
{
ok: false,
error: failure("REQUEST_ABORTED", input.operationId, retryCount, {
code: "REQUEST_ABORTED",
}),
},
"aborted",
);
}
}
}
+1
View File
@@ -8,6 +8,7 @@ export type OperationRequestInput = Readonly<{
body?: unknown;
signal?: AbortSignal;
idempotencyKey?: string;
correlationId?: string;
}>;
export type RequestTargetResult =
@@ -1,6 +1,7 @@
import { QueryClient } from "@tanstack/react-query";
import { MutationCache, QueryCache, QueryClient } from "@tanstack/react-query";
import { createFailure } from "../../contracts/errors.js";
import { safeErrorKind } from "../../contracts/diagnostics.js";
export const QUERY_CACHE_DEFAULTS = Object.freeze({
staleTime: 30_000,
@@ -11,8 +12,32 @@ export const QUERY_CACHE_DEFAULTS = Object.freeze({
persistence: false,
});
export function createQueryClient() {
/**
* @param {{diagnostics?: import("../../application/ports/diagnostics-port.js").DiagnosticsPort}} [dependencies]
*/
export function createQueryClient(dependencies = {}) {
/** @param {string} operation @param {unknown} error */
function report(operation, error) {
try {
dependencies.diagnostics?.record({
level: "warn",
eventId: "cache.operation.failed",
context: {
operation,
error_kind: safeErrorKind(error),
},
});
} catch {
// Query behavior remains independent from diagnostics.
}
}
return new QueryClient({
queryCache: new QueryCache({
onError: (error) => report("query", error),
}),
mutationCache: new MutationCache({
onError: (error) => report("mutation", error),
}),
defaultOptions: {
queries: {
staleTime: QUERY_CACHE_DEFAULTS.staleTime,
@@ -29,15 +54,16 @@ export function createQueryClient() {
/**
* @param {QueryClient} queryClient
* @param {{diagnostics?: import("../../application/ports/diagnostics-port.js").DiagnosticsPort}} [dependencies]
* @returns {import("../../application/ports/query-cache-port.js").QueryCachePort}
*/
export function createQueryCacheAdapter(queryClient) {
export function createQueryCacheAdapter(queryClient, dependencies = {}) {
return Object.freeze({
read(key) {
try {
return { ok: true, value: queryClient.getQueryData(key) };
} catch {
return cacheFailure("read", key);
return cacheFailure("read", key, dependencies.diagnostics);
}
},
write(key, value) {
@@ -45,7 +71,7 @@ export function createQueryCacheAdapter(queryClient) {
queryClient.setQueryData(key, structuredClone(value));
return { ok: true };
} catch {
return cacheFailure("write", key);
return cacheFailure("write", key, dependencies.diagnostics);
}
},
async invalidate(namespace) {
@@ -53,15 +79,31 @@ export function createQueryCacheAdapter(queryClient) {
await queryClient.invalidateQueries({ queryKey: namespace, exact: false });
return { ok: true };
} catch {
return cacheFailure("invalidate", namespace);
return cacheFailure("invalidate", namespace, dependencies.diagnostics);
}
},
});
}
/** @param {string} phase @param {readonly unknown[]} key */
function cacheFailure(phase, key) {
/**
* @param {string} phase
* @param {readonly unknown[]} key
* @param {import("../../application/ports/diagnostics-port.js").DiagnosticsPort | undefined} diagnostics
*/
function cacheFailure(phase, key, diagnostics) {
const namespace = typeof key[0] === "string" ? key[0] : "unknown";
try {
diagnostics?.record({
level: "warn",
eventId: "cache.operation.failed",
context: {
operation: phase,
error_kind: "QUERY_CACHE_FAILURE",
},
});
} catch {
// Cache behavior remains independent from diagnostics.
}
return {
ok: /** @type {false} */ (false),
error: createFailure("QUERY_CACHE_FAILURE", "QUERY_CACHE", 0, {
@@ -5,7 +5,8 @@ import { getStorageDefinition } from "../../contracts/storage-keys.js";
* @param {{
* localStorage?: Storage,
* sessionStorage?: Storage,
* now?: () => number
* now?: () => number,
* diagnostics?: import("../../application/ports/diagnostics-port.js").DiagnosticsPort
* }} [dependencies]
* @returns {import("../../application/ports/storage-port.js").StoragePort}
*/
@@ -26,7 +27,7 @@ export function createBrowserStorageAdapter(dependencies = {}) {
try {
definition = getStorageDefinition(logicalName);
} catch {
return unavailable("read", logicalName);
return unavailable("read", logicalName, dependencies.diagnostics);
}
const backend = backendFor(definition.backend);
@@ -50,7 +51,7 @@ export function createBrowserStorageAdapter(dependencies = {}) {
}
return { ok: true, value: structuredClone(envelope.value) };
} catch {
return unavailable("read", logicalName);
return unavailable("read", logicalName, dependencies.diagnostics);
}
},
@@ -59,7 +60,7 @@ export function createBrowserStorageAdapter(dependencies = {}) {
try {
definition = getStorageDefinition(logicalName);
} catch {
return unavailable("write", logicalName);
return unavailable("write", logicalName, dependencies.diagnostics);
}
const expiresAt =
@@ -82,12 +83,24 @@ export function createBrowserStorageAdapter(dependencies = {}) {
if (definition.quotaFallback === "memory") {
memory.set(definition.physicalKey, structuredClone(value));
recordStorageFailure(
dependencies.diagnostics,
"write",
logicalName,
quota,
);
return {
ok: false,
error: storageFailure(quota, "write", logicalName),
fallback: "memory",
};
}
recordStorageFailure(
dependencies.diagnostics,
"write",
logicalName,
quota,
);
return {
ok: false,
error: storageFailure(quota, "write", logicalName),
@@ -101,14 +114,14 @@ export function createBrowserStorageAdapter(dependencies = {}) {
try {
definition = getStorageDefinition(logicalName);
} catch {
return unavailable("remove", logicalName);
return unavailable("remove", logicalName, dependencies.diagnostics);
}
try {
backendFor(definition.backend)?.removeItem(definition.physicalKey);
memory.delete(definition.physicalKey);
return { ok: true };
} catch {
return unavailable("remove", logicalName);
return unavailable("remove", logicalName, dependencies.diagnostics);
}
},
});
@@ -128,10 +141,38 @@ function storageFailure(quota, phase, logicalName) {
);
}
/** @param {string} phase @param {string} logicalName */
function unavailable(phase, logicalName) {
/**
* @param {string} phase
* @param {string} logicalName
* @param {import("../../application/ports/diagnostics-port.js").DiagnosticsPort | undefined} diagnostics
*/
function unavailable(phase, logicalName, diagnostics) {
recordStorageFailure(diagnostics, phase, logicalName, false);
return {
ok: /** @type {false} */ (false),
error: storageFailure(false, phase, logicalName),
};
}
/**
* @param {import("../../application/ports/diagnostics-port.js").DiagnosticsPort | undefined} diagnostics
* @param {string} phase
* @param {string} logicalName
* @param {boolean} quota
*/
function recordStorageFailure(diagnostics, phase, logicalName, quota) {
try {
diagnostics?.record({
level: "warn",
eventId: "storage.operation.failed",
context: {
operation: `${phase}:${logicalName}`,
error_kind: quota
? "STORAGE_QUOTA_EXCEEDED"
: "STORAGE_UNAVAILABLE",
},
});
} catch {
// Storage behavior remains independent from diagnostics.
}
}
+76 -13
View File
@@ -1,7 +1,14 @@
import { projectTelemetryEvent } from "../../contracts/telemetry.js";
import { queueSizeBucket } from "../../contracts/diagnostics.js";
export const noOpTelemetry = Object.freeze({
emit: () => {},
flush: async () => {},
pendingCount: () => 0,
droppedCount: () => 0,
dropReasons: () => Object.freeze({}),
deliveryEvidence: () => null,
dispose: () => {},
});
/**
@@ -10,22 +17,20 @@ export const noOpTelemetry = Object.freeze({
* endpoint?: string,
* fetcher?: typeof fetch,
* maxQueue?: number,
* schedule?: (callback: () => void) => void
* schedule?: (callback: () => void) => void,
* now?: () => number,
* onDrop?: (event: Readonly<Record<string, unknown>>) => void,
* lifecycle?: Pick<EventTarget, "addEventListener" | "removeEventListener">
* }} options
*/
export function createTelemetryAdapter(options) {
if (!options.enabled || !options.endpoint) {
return Object.freeze({
...noOpTelemetry,
flush: async () => {},
pendingCount: () => 0,
droppedCount: () => 0,
});
return noOpTelemetry;
}
const endpoint = /** @type {string} */ (options.endpoint);
const fetcher = options.fetcher ?? fetch;
const maxQueue = options.maxQueue ?? 100;
const maxQueue = Math.max(1, options.maxQueue ?? 100);
const schedule = options.schedule ?? queueMicrotask;
const queue =
/** @type {Array<{eventName: string, attributes: Readonly<Record<string, unknown>>}>} */ (
@@ -34,18 +39,63 @@ export function createTelemetryAdapter(options) {
let scheduled = false;
let flushing = false;
let dropped = 0;
const dropReasons = new Map();
let lastDeliveryEvidence =
/** @type {Readonly<Record<string, unknown>> | null} */ (null);
const lifecycle =
options.lifecycle ??
(typeof globalThis.addEventListener === "function" &&
typeof globalThis.removeEventListener === "function"
? globalThis
: undefined);
/** @param {string} reason @param {number} count */
function recordDrop(reason, count = 1) {
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.
}
}
}
/** @param {string} eventName @param {Record<string, unknown>} attributes */
function emit(eventName, attributes) {
const projected = projectTelemetryEvent(eventName, attributes);
const projected = projectTelemetryEvent(
eventName,
attributes,
options.now,
);
if (!projected.success) {
dropped += 1;
recordDrop(projected.reason);
return;
}
if (queue.length >= maxQueue) {
queue.shift();
dropped += 1;
recordDrop("queue-full");
}
queue.push(projected.event);
@@ -69,19 +119,32 @@ export function createTelemetryAdapter(options) {
body: JSON.stringify({ events: batch }),
keepalive: true,
});
if (!response.ok) dropped += batch.length;
if (!response.ok) recordDrop("sink-failure", batch.length);
} catch {
dropped += batch.length;
recordDrop("sink-failure", batch.length);
} finally {
flushing = false;
}
}
const flushBeforePageExit = () => {
void flush();
};
lifecycle?.addEventListener("pagehide", flushBeforePageExit);
function dispose() {
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,
});
}