Files
clean-architecture-frontend…/tests/unit/observability-cardinality.test.ts
DongHyeonka b02ebb85ff fix(observability): 배포 id의 +·한글·긴 ref를 관측 이벤트에 받는다
runtime config와 release manifest는 빈 값이 아닌 build·release id를
받는데, telemetry와 diagnostics는 64자 ASCII 규칙으로 본다. `+`·한글이
있거나 긴 id로 배포하면 release.mismatch.detected와 부팅·렌더 실패
기록이 통째로 버려진다.

build_id·release_id·active_release_id 셋과 Service Worker manifest의
releaseId를 contracts의 규칙 하나(제어문자 없는 1~512자, code point)로
본다. 규칙 모듈은 import가 없어 worker가 관측 모듈을 끌어오지 않는다.
manifest의 buildId 규칙은 그대로다. 공용 규칙을 넓히는 안은 다른
속성의 개인정보·cardinality 방어가 약해지고, 자르거나 hash하는 안은
collector가 붙이는 원값과 달라져 배포별로 묶을 수 없어 버렸다. `+`만
더하는 안은 긴 ref와 한글이 남는다.

위험: 이벤트 하나가 길어질 수 있다(값마다 최대 512자). diagnostics가
이 세 속성에 숫자·boolean을 더는 받지 않는다. worker 번들과 초기 JS
크기는 merge 단계 전에는 재지 않았다.

검증(노트북): 고치기 전 코드에 이 커밋의 시험을 얹으면 두 시험 파일
142개 가운데 30개가 실패한다. 이 트리에서는 142개와 manifest decoder
시험이 통과한다. check:types, lint, check:architecture,
check:adapter-inventory, test:unit, test:contract, test:runtime-schema
통과.

Refs: REV-FE-0042
2026-11-23 04:57:27 +09:00

252 lines
8.7 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
DIAGNOSTIC_CONTEXT_ALLOWLIST,
DIAGNOSTIC_CONTEXT_CARDINALITY,
projectDiagnosticRecord,
statusGroup,
} from "../../src/contracts/diagnostics.ts";
import {
TELEMETRY_ATTRIBUTE_ALLOWLIST,
projectTelemetryEvent,
} from "../../src/contracts/telemetry.ts";
describe("observability cardinality policy", () => {
it("classifies every diagnostic context key exactly once", () => {
expect(Object.keys(DIAGNOSTIC_CONTEXT_CARDINALITY).sort()).toEqual(
[...DIAGNOSTIC_CONTEXT_ALLOWLIST].sort(),
);
expect(DIAGNOSTIC_CONTEXT_CARDINALITY.correlation_id).toBe("request");
expect(DIAGNOSTIC_CONTEXT_CARDINALITY.route_id).toBe("topology");
expect(DIAGNOSTIC_CONTEXT_CARDINALITY.operation_id).toBe("topology");
expect(DIAGNOSTIC_CONTEXT_CARDINALITY.duration_bucket).toBe("bounded");
});
it("keeps request-cardinality keys out of telemetry dimensions", () => {
for (const key of TELEMETRY_ATTRIBUTE_ALLOWLIST) {
expect(DIAGNOSTIC_CONTEXT_CARDINALITY[key]).not.toBe("request");
}
expect(TELEMETRY_ATTRIBUTE_ALLOWLIST).not.toContain("correlation_id");
});
it("rejects free-form values for bounded diagnostic dimensions", () => {
expect(
projectDiagnosticRecord({
level: "info",
eventId: "http.request.completed",
context: {
outcome: "customer-123",
http_status_group: "599",
attempt_count_bucket: "37",
duration_bucket: "12345ms",
},
}),
).toEqual({ success: false, reason: "invalid-context" });
});
// 1103/03-05. The effect certainty is a closed five-value dimension in
// both sinks.
it.each(["NOT_APPLICABLE", "NOT_STARTED", "NOT_APPLIED", "APPLIED_CONFIRMED", "MAYBE_APPLIED"])(
"admits effect_certainty %s in diagnostics and failure telemetry",
(effect) => {
expect(DIAGNOSTIC_CONTEXT_CARDINALITY.effect_certainty).toBe("bounded");
expect(
projectDiagnosticRecord({
level: "warn",
eventId: "http.request.completed",
context: { effect_certainty: effect },
}).success,
).toBe(true);
expect(
projectTelemetryEvent("api.request.failed", {
error_kind: "PROBLEM",
http_status_group: "4xx",
attempt_count_bucket: "1",
route_id: "TEST_ROUTE",
effect_certainty: effect,
}).success,
).toBe(true);
},
);
it.each(["maybe", "UNKNOWN", "MAYBE_APPLIED_ON_RETRY"])(
"rejects effect_certainty %j in both sinks",
(effect) => {
expect(
projectDiagnosticRecord({
level: "warn",
eventId: "http.request.completed",
context: { effect_certainty: effect },
}),
).toEqual({ success: false, reason: "invalid-context" });
expect(
projectTelemetryEvent("api.request.failed", {
error_kind: "PROBLEM",
http_status_group: "4xx",
attempt_count_bucket: "1",
route_id: "TEST_ROUTE",
effect_certainty: effect,
}),
).toEqual({ success: false, reason: "invalid-attribute-value" });
},
);
it("allows request correlation only in bounded diagnostics evidence", () => {
const projected = projectDiagnosticRecord({
level: "info",
eventId: "http.request.completed",
context: {
correlation_id: "request-a1b2c3",
outcome: "success",
http_status_group: "2xx",
attempt_count_bucket: "1",
duration_bucket: "lt100ms",
},
});
expect(projected.success).toBe(true);
});
});
/**
* R-7.5. One operationId grammar. The V3 composition accepts camelCase ids of
* up to 128 characters; a failure for such an operation must not be dropped
* as an invalid telemetry attribute, and diagnostics apply the same rule.
*/
describe("shared operationId and status-group grammar", () => {
function telemetryFailure(operationId: string, httpStatusGroup = "5xx") {
return projectTelemetryEvent("api.request.failed", {
error_kind: "SERVER_FAILURE",
http_status_group: httpStatusGroup,
attempt_count_bucket: "1",
route_id: "TEST_ROUTE",
operation_id: operationId,
});
}
function diagnosticCompletion(operationId: string, httpStatusGroup = "5xx") {
return projectDiagnosticRecord({
level: "warn",
eventId: "http.request.completed",
context: { operation_id: operationId, http_status_group: httpStatusGroup },
});
}
it.each([
"getUser",
"LIST_ORDER_ITEMS",
"users.v1.get-item",
`a${"b".repeat(127)}`,
])("keeps both observability records for operationId %s", (operationId) => {
expect(telemetryFailure(operationId).success).toBe(true);
expect(diagnosticCompletion(operationId).success).toBe(true);
});
it.each(["", "1getUser", "get user", "get:user", "get/user", `a${"b".repeat(128)}`])(
"rejects operationId %j in both sinks",
(operationId) => {
expect(telemetryFailure(operationId)).toEqual({
success: false,
reason: "invalid-attribute-value",
});
expect(diagnosticCompletion(operationId)).toEqual({
success: false,
reason: "invalid-context",
});
},
);
it.each([undefined, 0, 101, 204, 302, 404, 503, 999])(
"accepts the status group statusGroup(%s) produces in both sinks",
(status) => {
const group = statusGroup(status);
expect(telemetryFailure("GET_USER", group).success).toBe(true);
expect(diagnosticCompletion("GET_USER", group).success).toBe(true);
},
);
});
/**
* REV-FE-0042. The deploy names the build and the release (a git ref with `+`,
* Hangul or a long branch name), so an event must not be dropped over it. Only
* these three attributes take that rule.
*/
describe("shared deployment id grammar", () => {
const DEPLOYMENT_KEYS = ["build_id", "release_id", "active_release_id"] as const;
function bothSinks(key: string, value: unknown) {
const attributes = {
build_id: "build-a",
active_release_id: "release-b",
mismatch_kind: "RELEASE_MISMATCH",
[key]: value,
};
return {
telemetry: projectTelemetryEvent("release.mismatch.detected", attributes),
diagnostics: projectDiagnosticRecord({
level: "warn",
eventId: "release.mismatch.detected",
context: attributes,
}),
};
}
const refused = {
telemetry: { success: false, reason: "invalid-attribute-value" },
diagnostics: { success: false, reason: "invalid-context" },
};
describe.each(DEPLOYMENT_KEYS)("%s", (key) => {
it.each([
["a build suffix", "refs/tags/v1.0.0+build.7-9-1"],
["Hangul", "refs/heads/기능-12-1"],
["78 characters", "refs/heads/feature/a-long-branch-name-that-a-derived-service-might-use-12345-1"],
["one character", "7"],
["a space", "release candidate 7"],
["a zero-width joiner", "release\u200d7"],
["512 characters", "r".repeat(512)],
["512 code points in 1024 code units", "\u{1F680}".repeat(512)],
])("keeps %s as given in both sinks", (_case, value) => {
const { telemetry, diagnostics } = bothSinks(key, value);
expect(telemetry).toMatchObject({ success: true, event: { attributes: { [key]: value } } });
expect(diagnostics).toMatchObject({ success: true, record: { context: { [key]: value } } });
});
it.each([
["an empty value", ""],
["NUL", "release\u0000"],
["a tab", "\trelease"],
["a line break inside", "release\nforged"],
["a trailing line break", "release\n"],
["a carriage return", "release\r7"],
["ESC", "release\u001b[31m"],
["the last C0 control", "release\u001f"],
["DEL", "release\u007f"],
["the first C1 control", "release\u0080"],
["NEL", "release\u0085"],
["the last C1 control", "release\u009f"],
["513 characters", "r".repeat(513)],
["513 code points", "\u{1F680}".repeat(513)],
["a number", 7],
["a boolean", true],
])("rejects %s in both sinks", (_case, value) => {
expect(bothSinks(key, value)).toEqual(refused);
});
});
// Every other key of both allowlists, so a new one cannot take the wide rule unseen.
const otherKey = (key: string) => !(DEPLOYMENT_KEYS as readonly string[]).includes(key);
const FREE_FORM = ["1.0.0+build.7", "기능", "1".repeat(65)];
it.each(TELEMETRY_ATTRIBUTE_ALLOWLIST.filter(otherKey))("leaves %s narrow in telemetry", (key) => {
for (const value of FREE_FORM) {
expect(bothSinks(key, value).telemetry).toEqual(refused.telemetry);
}
});
it.each(DIAGNOSTIC_CONTEXT_ALLOWLIST.filter(otherKey))("leaves %s narrow in diagnostics", (key) => {
for (const value of FREE_FORM) {
expect(bothSinks(key, value).diagnostics).toEqual(refused.diagnostics);
}
});
});