The V3 composition admits operationIds with /^[A-Za-z][A-Za-z0-9_.-]{0,127}$/
(camelCase, up to 128 chars), but telemetry validated operation_id with
/^[A-Z][A-Z0-9_]{0,63}$/, so api.request.failed for a V3 operation such as
`getUser` failed projection as invalid-attribute-value and was dropped.
Diagnostics used the free-form 64-char safe-string pattern instead.
http_status_group had the same split: statusGroup() emits [0-9]xx|none and
diagnostics accepted that, but telemetry only [1-5]xx|none, so a failure
with status 0 or >= 600 was dropped too.
- New src/contracts/operation-id.ts holds isOperationId (the V3 grammar);
the V3 composition, telemetry operation_id and diagnostics operation_id
all use it. The REST v2 and browser RPC registry grammars are subsets.
- isHttpStatusGroup sits next to statusGroup() in diagnostics.ts and is used
by both diagnostics and telemetry.
Other telemetry attribute policies (route_id, error_kind, redaction) are
unchanged.
RED: "shared operationId and status-group grammar" failed before the fix:
getUser, users.v1.get-item and a 128-char id were rejected by telemetry;
"1getUser", "get:user", "get/user" were accepted by diagnostics; and the
statusGroup(0)/statusGroup(999) groups were rejected by telemetry.
Gates: check:architecture, check:types:app/test/node, lint, test:component,
test:runtime-schema, test:contract pass; test:unit passes except the
environment-dependent removal-fixture.test.ts (needs generated
artifacts/release files; unrelated). check:diagnostics,
check:registries:structure, check:types:web-worker/service-worker and
tests/integration, tests/platform/telemetry also pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
260 lines
8.4 KiB
TypeScript
260 lines
8.4 KiB
TypeScript
import { isOperationId } from "./operation-id.ts";
|
|
|
|
export const DIAGNOSTIC_LEVELS = Object.freeze([
|
|
"debug",
|
|
"info",
|
|
"warn",
|
|
"error",
|
|
] as const);
|
|
export { queueSizeBucket } from "./diagnostic-buckets.ts";
|
|
export type DiagnosticLevel = (typeof DIAGNOSTIC_LEVELS)[number];
|
|
|
|
export const DIAGNOSTIC_EVENT_REGISTRY = Object.freeze({
|
|
"app.boot.failed": Object.freeze({ level: "error" }),
|
|
"http.request.completed": Object.freeze({ level: "info" }),
|
|
"cache.operation.failed": Object.freeze({ level: "warn" }),
|
|
"storage.operation.failed": Object.freeze({ level: "warn" }),
|
|
"route.changed": Object.freeze({ level: "info" }),
|
|
"ui.render.failed": Object.freeze({ level: "error" }),
|
|
"release.mismatch.detected": Object.freeze({ level: "warn" }),
|
|
"telemetry.delivery.dropped": Object.freeze({ level: "warn" }),
|
|
});
|
|
export type DiagnosticEventId = keyof typeof DIAGNOSTIC_EVENT_REGISTRY;
|
|
|
|
export const DIAGNOSTIC_CONTEXT_ALLOWLIST = Object.freeze([
|
|
"app_version",
|
|
"build_id",
|
|
"release_id",
|
|
"active_release_id",
|
|
"config_schema_version",
|
|
"api_contract_version",
|
|
"route_id",
|
|
"operation_id",
|
|
"correlation_id",
|
|
"error_kind",
|
|
"outcome",
|
|
"http_status_group",
|
|
"attempt_count_bucket",
|
|
"duration_bucket",
|
|
"component_boundary",
|
|
"mismatch_kind",
|
|
"operation",
|
|
"reason",
|
|
"queue_size_bucket",
|
|
] as const);
|
|
export type DiagnosticContextKey =
|
|
(typeof DIAGNOSTIC_CONTEXT_ALLOWLIST)[number];
|
|
|
|
export type DiagnosticCardinalityClass =
|
|
| "bounded"
|
|
| "taxonomy"
|
|
| "topology"
|
|
| "deployment"
|
|
| "request";
|
|
|
|
/**
|
|
* Cardinality ownership is explicit so a field cannot silently move from
|
|
* bounded operational evidence into an unbounded metric dimension.
|
|
*
|
|
* `request` values are unique per request and are diagnostics-only.
|
|
* `topology` values are bounded by the deployed App/Context/Feature topology.
|
|
* `taxonomy` values are bounded by source-controlled error/reason taxonomies.
|
|
* `deployment` values rotate with a release, not with user traffic.
|
|
* `bounded` values are validated against a finite set below.
|
|
*/
|
|
export const DIAGNOSTIC_CONTEXT_CARDINALITY = Object.freeze({
|
|
app_version: "deployment",
|
|
build_id: "deployment",
|
|
release_id: "deployment",
|
|
active_release_id: "deployment",
|
|
config_schema_version: "deployment",
|
|
api_contract_version: "deployment",
|
|
route_id: "topology",
|
|
operation_id: "topology",
|
|
correlation_id: "request",
|
|
error_kind: "taxonomy",
|
|
outcome: "bounded",
|
|
http_status_group: "bounded",
|
|
attempt_count_bucket: "bounded",
|
|
duration_bucket: "bounded",
|
|
component_boundary: "bounded",
|
|
mismatch_kind: "taxonomy",
|
|
operation: "topology",
|
|
reason: "taxonomy",
|
|
queue_size_bucket: "bounded",
|
|
} satisfies Readonly<Record<DiagnosticContextKey, DiagnosticCardinalityClass>>);
|
|
|
|
export type DiagnosticContext = Readonly<
|
|
Partial<Record<DiagnosticContextKey, string | number | boolean>>
|
|
>;
|
|
|
|
const BOUNDED_CONTEXT_VALUE_POLICIES: Readonly<
|
|
Partial<Record<DiagnosticContextKey, (value: unknown) => boolean>>
|
|
> = Object.freeze({
|
|
outcome: (value) =>
|
|
typeof value === "string" &&
|
|
/^(?:success|recovered|failed|aborted|SUCCESS|PROBLEM|UNAUTHENTICATED|FORBIDDEN|RATE_LIMITED|CONTRACT_VIOLATION|TRANSPORT_FAILURE|CANCELLED|AUTH_INTEGRATION_FAILURE|FAILED|DEGRADED)$/.test(
|
|
value,
|
|
),
|
|
http_status_group: isHttpStatusGroup,
|
|
// R-7.5. Not a finite set, but source-controlled topology: the shared
|
|
// grammar applies instead of the free-form safe-string pattern.
|
|
operation_id: isOperationId,
|
|
attempt_count_bucket: (value) =>
|
|
typeof value === "string" && /^(?:1|2|3|3-4|5\+)$/.test(value),
|
|
duration_bucket: (value) =>
|
|
typeof value === "string" &&
|
|
/^(?:lt100ms|100-499ms|500-1999ms|gte2000ms|unknown)$/.test(value),
|
|
component_boundary: (value) =>
|
|
typeof value === "string" && /^(?:route|feature|boot)$/.test(value),
|
|
queue_size_bucket: (value) =>
|
|
typeof value === "string" && /^(?:0|1-10|11-50|51\+)$/.test(value),
|
|
});
|
|
|
|
export type DiagnosticRecordInput = Readonly<{
|
|
level: DiagnosticLevel;
|
|
eventId: DiagnosticEventId;
|
|
context?: Readonly<Record<string, unknown>>;
|
|
}>;
|
|
|
|
export type DiagnosticRecord = Readonly<{
|
|
level: DiagnosticLevel;
|
|
eventId: DiagnosticEventId;
|
|
timestamp: string;
|
|
context: DiagnosticContext;
|
|
}>;
|
|
|
|
const SAFE_VALUE = /^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,63}$/;
|
|
|
|
function projectDiagnosticRecordUnsafe(
|
|
input: DiagnosticRecordInput,
|
|
now: () => number = Date.now,
|
|
):
|
|
| Readonly<{ success: true; record: DiagnosticRecord }>
|
|
| Readonly<{ success: false; reason: string }> {
|
|
if (!Object.hasOwn(DIAGNOSTIC_EVENT_REGISTRY, input.eventId)) {
|
|
return { success: false, reason: "unregistered-event" };
|
|
}
|
|
if (!DIAGNOSTIC_LEVELS.includes(input.level)) {
|
|
return { success: false, reason: "invalid-level" };
|
|
}
|
|
const contextEntries = Object.entries(input.context ?? {});
|
|
if (contextEntries.length > DIAGNOSTIC_CONTEXT_ALLOWLIST.length) {
|
|
return { success: false, reason: "invalid-context" };
|
|
}
|
|
const projected: Partial<
|
|
Record<DiagnosticContextKey, string | number | boolean>
|
|
> = {};
|
|
for (const [key, value] of contextEntries) {
|
|
if (
|
|
!DIAGNOSTIC_CONTEXT_ALLOWLIST.includes(key as DiagnosticContextKey)
|
|
) {
|
|
return { success: false, reason: "unknown-context" };
|
|
}
|
|
const contextKey = key as DiagnosticContextKey;
|
|
const boundedPolicy = BOUNDED_CONTEXT_VALUE_POLICIES[contextKey];
|
|
if (boundedPolicy && !boundedPolicy(value)) {
|
|
return { success: false, reason: "invalid-context" };
|
|
}
|
|
if (boundedPolicy && typeof value === "string") {
|
|
// Admitted from a finite, source-controlled set (e.g. "51+"), so the
|
|
// free-form safe-string pattern does not apply.
|
|
projected[contextKey] = value;
|
|
} else if (typeof value === "string") {
|
|
if (!SAFE_VALUE.test(value)) {
|
|
return { success: false, reason: "invalid-context" };
|
|
}
|
|
projected[contextKey] = value;
|
|
} else if (typeof value === "number" && Number.isFinite(value)) {
|
|
projected[key as DiagnosticContextKey] = value;
|
|
} else if (typeof value === "boolean") {
|
|
projected[key as DiagnosticContextKey] = value;
|
|
} else {
|
|
return { success: false, reason: "invalid-context" };
|
|
}
|
|
}
|
|
let timestamp: string;
|
|
try {
|
|
timestamp = new Date(now()).toISOString();
|
|
} catch {
|
|
timestamp = new Date(0).toISOString();
|
|
}
|
|
return {
|
|
success: true,
|
|
record: Object.freeze({
|
|
level: input.level,
|
|
eventId: input.eventId,
|
|
timestamp,
|
|
context: Object.freeze(projected),
|
|
}),
|
|
};
|
|
}
|
|
|
|
export function projectDiagnosticRecord(
|
|
input: DiagnosticRecordInput,
|
|
now: () => number = Date.now,
|
|
): ReturnType<typeof projectDiagnosticRecordUnsafe> {
|
|
try {
|
|
return projectDiagnosticRecordUnsafe(input, now);
|
|
} catch {
|
|
return { success: false, reason: "serialization-failure" };
|
|
}
|
|
}
|
|
|
|
export function safeErrorKind(error: unknown): string {
|
|
try {
|
|
if (error && typeof error === "object") {
|
|
const record = error as Readonly<Record<string, unknown>>;
|
|
if (
|
|
typeof record.kind === "string" &&
|
|
/^[A-Z][A-Z0-9_]{0,63}$/.test(record.kind)
|
|
) {
|
|
return record.kind;
|
|
}
|
|
if (
|
|
typeof record.name === "string" &&
|
|
/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(record.name)
|
|
) {
|
|
const normalized = record.name
|
|
.replace(/([a-z0-9])([A-Z])/g, "$1_$2")
|
|
.toUpperCase();
|
|
return /^[A-Z][A-Z0-9_]{0,63}$/.test(normalized)
|
|
? normalized
|
|
: "UNKNOWN_FAILURE";
|
|
}
|
|
}
|
|
} catch {
|
|
return "UNKNOWN_FAILURE";
|
|
}
|
|
return "UNKNOWN_FAILURE";
|
|
}
|
|
|
|
export function statusGroup(status: number | undefined): string {
|
|
return typeof status === "number" && Number.isFinite(status)
|
|
? `${Math.max(0, Math.min(9, Math.floor(status / 100)))}xx`
|
|
: "none";
|
|
}
|
|
|
|
/**
|
|
* R-7.5. Exactly the values `statusGroup` produces. Telemetry and diagnostics
|
|
* both validate `http_status_group` with it.
|
|
*/
|
|
export function isHttpStatusGroup(value: unknown): value is string {
|
|
return typeof value === "string" && /^(?:[0-9]xx|none)$/.test(value);
|
|
}
|
|
|
|
export function attemptBucket(attemptCount: number): string {
|
|
if (attemptCount <= 1) return "1";
|
|
if (attemptCount === 2) return "2";
|
|
if (attemptCount <= 4) return "3-4";
|
|
return "5+";
|
|
}
|
|
|
|
export function durationBucket(durationMs: number): string {
|
|
if (!Number.isFinite(durationMs) || durationMs < 0) return "unknown";
|
|
if (durationMs < 100) return "lt100ms";
|
|
if (durationMs < 500) return "100-499ms";
|
|
if (durationMs < 2_000) return "500-1999ms";
|
|
return "gte2000ms";
|
|
}
|