Files
clean-architecture-frontend…/src/contracts/diagnostics.ts
T
DongHyeonka f738348d9d fix(bootstrap): 실패한 scope closer를 label과 함께 진단에 남긴다
문제: 1103/02-01이 제품 closer를 scope reset에 넣었다. template
participant 하나가 제품 closer를 차례로 부르고, 하나라도 던지면 이유 없는
Error를 던진다. scope runtime은 그 실패를 `failed = true`로만 받아 scope를
`FAILED`에 둔다. 그동안 모든 서버 요청이 `SCOPE_FENCED`로 막히는데 진단
기록은 0건이다(리뷰 실험 E-3). 계약의 `ProductScopeParticipant.label`을
읽는 코드도 없다. 개발자는 "로그아웃 뒤 앱이 요청을 안 보낸다"만 보고 원인
closer를 찾으려면 closer를 하나씩 지워 봐야 한다.

고른 방법(리뷰 대안 (다)):
- scope runtime이 reset의 실패 단계마다 `cache.operation.failed`를 하나
  남긴다. `operation: "SCOPE_RESET"`, `reason`은 `PARTICIPANT_FAILED`·
  `CACHE_RESET_FAILED`·`GENERATION_ACTIVATION_FAILED`(+ 목록 함수가 던질
  때 `PARTICIPANTS_UNREADABLE`), `error_kind`, participant 실패면
  `scope_participant: <label>`. template participant 실패도 같은 길로
  남는다.
- 진단 계약에 `scope_participant` 키를 더한다(cardinality `topology`,
  값 정책 `isScopeParticipantLabel` = 소문자 kebab-case 48자 이하). label은
  제품 코드가 고른 문자열이라 projection이 받는 닫힌 토큰으로 제한했다.
- 제품 closer를 wrapper 하나로 감싸지 않고 각자 order 10 participant로
  넘긴다. 그래서 `participants`가 reset마다 읽는 함수도 받는다
  (`ServerStateScopeDependencies`, 배열은 그대로 받는다). 순서와 "하나가
  실패해도 나머지를 부른다"는 그대로다.
- 조립은 형식에 맞지 않는 제품 label을 `TypeError`로 거절한다. 부팅에서
  바로 드러나야 진단에서 label이 빠지는 일이 없다.

버린 대안:
- (가) 문서에 "closer는 던지지 않게 쓴다"만 적기: 결함이 그대로다.
- (나) wrapper만 제품 label을 기록: template participant 실패는 계속
  조용하고, 한 실패가 wrapper와 runtime에서 두 번 기록된다.
- label을 `operation`이나 `reason` 값에 섞기: 계약 변경은 없지만 그 키의
  뜻이 흐려진다.

위험·한계:
- 진단 계약(`src/contracts/diagnostics.ts`)에 키 하나, 함수 하나가 더해진다.
  더하기만 해서 호환은 깨지지 않는다. CHANGELOG [계약] 행이 필요하다.
- 제품 label 형식이 좁아졌다. `Browser Files` 같은 label을 쓰던 제품은
  부팅에서 `TypeError`가 난다. 저장소 안의 label(`browser-files`, 테스트의
  label)은 모두 맞는다.
- 화면이 `FAILED`를 어떻게 보이는지는 바꾸지 않았다(영역 08·09).

검증: desktop batch에서 확인
- node scripts/run-vitest.ts run tests/unit/server-state-scope-runtime.test.ts
  tests/unit/runtime-adapters-product-scope-participants.test.ts
  tests/unit/observability-cardinality.test.ts tests/unit/diagnostics.test.ts
- corepack pnpm check:diagnostics
- node scripts/run-vitest.ts run tests/recipes/browser-file-session-capability.test.ts

Refs: 1105/02-01
2026-11-05 22:14:54 +09:00

297 lines
9.8 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" }),
"feature.override.unknown": 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",
"feature_override_key",
"effect_certainty",
"scope_participant",
] 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",
// 09-09. A key from the deployed runtime document; it changes with a config
// deployment, not with traffic.
feature_override_key: "deployment",
// 1103/03-05. The V3 effect certainty, five values.
effect_certainty: "bounded",
// 1105/02-01. The label of a scope reset participant, set in source by the
// template or the product composition, never by traffic.
scope_participant: "topology",
} 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),
effect_certainty: isEffectCertainty,
scope_participant: isScopeParticipantLabel,
});
/**
* 1103/03-05. Exactly the V3 `HttpEffectCertainty` values. Telemetry and
* diagnostics both validate `effect_certainty` with it.
*/
export function isEffectCertainty(value: unknown): value is string {
return (
typeof value === "string" &&
/^(?:NOT_APPLICABLE|NOT_STARTED|NOT_APPLIED|APPLIED_CONFIRMED|MAYBE_APPLIED)$/.test(
value,
)
);
}
/**
* 1105/02-01. A scope reset participant's label: a lowercase kebab-case token
* of at most 48 characters that starts with a letter. A failed close is
* recorded under it (`scope_participant`), so the label must pass this
* projection; product composition refuses any other.
*/
export function isScopeParticipantLabel(value: unknown): value is string {
return typeof value === "string" && /^[a-z][a-z0-9-]{0,47}$/.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";
}