Files
clean-architecture-frontend…/tests/unit/runtime-adapters-product-scope-participants.test.ts
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

205 lines
6.3 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import type { ProductScopeParticipant } from "../../src/bootstrap/product-composition-contract.ts";
import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts";
import { testRuntimeConfig } from "../helpers/runtime-config.ts";
/**
* 2026-11-03 02-01. A product hands the template what must close with a
* session through `ProductComposition.scopeParticipants`, so it never edits
* `runtime-adapters.ts`. The real `createRuntimeAdapters` runs; only the
* product-owned file is replaced.
*/
const fixture = vi.hoisted(() => ({
participants: [] as ProductScopeParticipant[],
owner: undefined as Readonly<{ switchUser(subject: string): void }> | undefined,
}));
vi.mock("../../src/bootstrap/product-composition.ts", () => ({
composeProductSessionOwner: () => {
const listeners = new Set<() => void>();
let subject = "user-a";
const owner = {
readState: () => "authenticated",
readSubject: () => subject,
subscribe(listener: () => void) {
listeners.add(listener);
return () => listeners.delete(listener);
},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({ headers: {} }),
recoverSession: async () => "no-session",
notifyUnauthenticated: () => {},
switchUser(next: string) {
subject = next;
for (const listener of listeners) listener();
},
};
fixture.owner = owner;
return owner;
},
composeProduct: () => ({
capabilities: {},
credentialProviders: {},
scopeParticipants: fixture.participants,
}),
}));
let current: Awaited<ReturnType<typeof createRuntimeAdapters>> | undefined;
afterEach(() => {
current?.infrastructure.dispose();
current = undefined;
fixture.participants = [];
});
async function compose() {
current = await createRuntimeAdapters({
runtime: {
config: testRuntimeConfig({
APP_ENV: "local",
API_BASE_URL: "http://localhost:8080",
TELEMETRY_ENABLED: false,
AUTH_MODE: "external",
REQUEST_TIMEOUT_MS: 10_000,
MAX_RETRY_ATTEMPTS: 0,
RELEASE_MANIFEST_URL: "/release-manifest.json",
CONFIG_SCHEMA_VERSION: "2.0",
CAPABILITY_OVERRIDES: {
REALTIME: "DEFAULT",
WEB_WORKER: "DEFAULT",
SERVICE_WORKER: "DEFAULT",
OFFLINE_COMMANDS: "DEFAULT",
},
FEATURE_OVERRIDES: {},
}),
configSchema: "V2",
build: {
buildId: "build-a",
commitSha: "abc123",
routerBasePath: "/",
runtimeConfigUrl: "/config.json",
},
validationDurationMs: 0,
},
release: {
schemaVersion: 2,
appVersion: "0.1.0",
buildId: "build-a",
commitSha: "abc123",
configSchemaVersion: "2.0",
contractSet: {
setAlgorithm: "CA_CONTRACT_SET_V1",
setDigest: `sha256:${"0".repeat(64)}`,
packages: [],
},
assetManifestHash: "hash-a",
releaseId: "release-a",
builtAt: "2026-07-25T00:00:00Z",
routeChunks: { "route-home": "assets/home.js" },
},
host: {},
});
const owner = fixture.owner;
if (!owner) throw new Error("The product session owner was not asked");
return {
scope: current.infrastructure.serverStateScope,
owner,
diagnostics: current.outputPorts.diagnostics,
};
}
describe("product scope participants (2026-11-03 02-01)", () => {
it("closes each one, in order, on every identity change before READY", async () => {
const closed: string[] = [];
fixture.participants = [
{ label: "first", close: () => void closed.push("first") },
{
label: "second",
async close() {
await Promise.resolve();
closed.push("second");
},
},
];
const { scope, owner } = await compose();
expect(closed).toEqual([]);
owner.switchUser("user-b");
expect(scope.getPhase()).toBe("FENCED");
await vi.waitFor(() => expect(scope.getPhase()).toBe("READY"));
expect(closed).toEqual(["first", "second"]);
owner.switchUser("user-c");
await vi.waitFor(() => expect(closed).toHaveLength(4));
await vi.waitFor(() => expect(scope.getPhase()).toBe("READY"));
});
it("keeps the scope from READY when one fails, and still closes the rest", async () => {
const closed: string[] = [];
fixture.participants = [
{
label: "broken",
close() {
throw new Error("cannot close");
},
},
{ label: "after", close: () => void closed.push("after") },
];
const { scope, owner } = await compose();
owner.switchUser("user-b");
await vi.waitFor(() => expect(scope.getPhase()).toBe("FAILED"));
expect(closed).toEqual(["after"]);
});
// 1105/02-01 (E-3). A failing closer left the scope FAILED, every request
// SCOPE_FENCED, and no diagnostic at all: the label was never read.
it("records which participant kept the scope from READY, on every retry", async () => {
fixture.participants = [
{
label: "broken-closer",
close() {
throw new Error("cannot close");
},
},
{ label: "fine-closer", close() {} },
];
const { scope, owner, diagnostics } = await compose();
const resetFailures = () =>
diagnostics
.entries()
.filter(
(entry) =>
entry.eventId === "cache.operation.failed" &&
entry.context.operation === "SCOPE_RESET",
)
.map((entry) => entry.context);
owner.switchUser("user-b");
await vi.waitFor(() => expect(scope.getPhase()).toBe("FAILED"));
expect(resetFailures()).toEqual([
{
operation: "SCOPE_RESET",
reason: "PARTICIPANT_FAILED",
error_kind: "ERROR",
scope_participant: "broken-closer",
},
]);
// The same identity retries a FAILED reset; it fails and says so again.
owner.switchUser("user-b");
await vi.waitFor(() => expect(resetFailures()).toHaveLength(2));
await vi.waitFor(() => expect(scope.getPhase()).toBe("FAILED"));
expect(resetFailures()[1]).toMatchObject({ scope_participant: "broken-closer" });
});
it("refuses a participant label the diagnostics could not carry", async () => {
fixture.participants = [{ label: "Browser Files", close() {} }];
await expect(compose()).rejects.toThrow(TypeError);
});
});