Files
clean-architecture-frontend…/tests/unit/server-state-scope-runtime.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

528 lines
18 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import {
createDemoSessionAdapter,
createExternalAuthSessionAdapter,
} from "../../src/adapters/auth/external-session-adapter.ts";
import {
createServerStateScopeRuntime,
type ServerStateScopeDependencies,
} from "../../src/adapters/query-cache/server-state-scope-runtime.ts";
import type { SessionState } from "../../src/application/ports/auth-session-port.ts";
import type { DiagnosticRecordInput } from "../../src/contracts/diagnostics.ts";
import type { ClientScopeLifecycleEvent } from "../../src/contracts/server-state-scope.ts";
describe("server-state session generation runtime", () => {
it("fences the old generation synchronously and publishes READY after the reset order", async () => {
let sessionListener: () => void = () => {};
let completeReset: () => void = () => {};
const reset = new Promise<void>((resolve) => {
completeReset = resolve;
});
const resetLocal = vi.fn(() => reset);
const participantOrder: string[] = [];
let tokenSequence = 0;
const runtime = createServerStateScopeRuntime({
session: {
subscribe(listener) {
sessionListener = listener;
return () => {};
},
},
queryInvalidation: {
resetLocal,
},
participants: [
{
order: 9,
label: "realtime",
close: () => void participantOrder.push("realtime"),
},
{
order: 4,
label: "admission",
close: () => void participantOrder.push("admission"),
},
],
tokenFactory: () =>
`scope-token-${String(tokenSequence++).padStart(8, "0")}`,
});
const changed = vi.fn();
const lifecycle: ClientScopeLifecycleEvent[] = [];
runtime.subscribe(changed);
runtime.subscribeLifecycle((event) => lifecycle.push(event));
const before = runtime.getSnapshot();
const identity = before.identities.intern({ id: "private" });
identity.acquire();
sessionListener();
// §10.6 steps 1-3 are synchronous: the old snapshot is immediately stale,
// FENCED is published, and subscribers are notified before any await.
expect(before.isCurrent()).toBe(false);
expect(before.signal.aborted).toBe(true);
expect(runtime.getPhase()).toBe("FENCED");
expect(lifecycle[0]).toEqual({ kind: "FENCED", previousGeneration: 1 });
expect(changed).toHaveBeenCalledOnce();
// Nothing may read as current while the scope is fenced.
expect(runtime.getSnapshot().isCurrent()).toBe(false);
await vi.waitFor(() => expect(resetLocal).toHaveBeenCalledOnce());
// Participants close in §10.6 step order, before the local cache reset.
expect(participantOrder).toEqual(["admission", "realtime"]);
completeReset();
await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY"));
const after = runtime.getSnapshot();
expect(after.generation).toBe(before.generation + 1);
expect(after.fingerprint).not.toBe(before.fingerprint);
expect(after.isCurrent()).toBe(true);
expect(after.signal.aborted).toBe(false);
expect(after.signal).not.toBe(before.signal);
expect(before.identities.inspect().closed).toBe(true);
expect(lifecycle.at(-1)).toMatchObject({ kind: "READY" });
expect(changed).toHaveBeenCalledTimes(2);
runtime.dispose();
expect(runtime.getPhase()).toBe("DISPOSED");
expect(after.identities.inspect().closed).toBe(true);
expect(after.isCurrent()).toBe(false);
});
it("does not let a throwing snapshot subscriber prevent reset", async () => {
let sessionListener: () => void = () => {};
const resetLocal = vi.fn(async () => {});
const runtime = createServerStateScopeRuntime({
session: {
subscribe(listener) {
sessionListener = listener;
return () => {};
},
},
queryInvalidation: {
resetLocal,
},
tokenFactory: () => "scope-listener-token-0001",
});
runtime.subscribe(() => {
throw new Error("subscriber defect");
});
expect(() => sessionListener()).not.toThrow();
await vi.waitFor(() => expect(resetLocal).toHaveBeenCalledOnce());
await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY"));
});
// 1105/02-01. Each failure below is also recorded, with the participant's
// label when a participant threw; it used to leave no trace.
const resetFailure = (
reason: string,
participant?: string,
): DiagnosticRecordInput => ({
level: "warn",
eventId: "cache.operation.failed",
context: {
operation: "SCOPE_RESET",
reason,
error_kind: "ERROR",
...(participant ? { scope_participant: participant } : {}),
},
});
it("remains failed when a mandatory participant cannot close", async () => {
let sessionListener: () => void = () => {};
const resetLocal = vi.fn(async () => {});
const record = vi.fn<(input: DiagnosticRecordInput) => void>();
const runtime = createServerStateScopeRuntime({
session: {
subscribe(listener) {
sessionListener = listener;
return () => {};
},
},
queryInvalidation: {
resetLocal,
},
diagnostics: { record },
participants: [
{
order: 4,
label: "mandatory-admission",
close: async () => {
throw new Error("close failed");
},
},
],
tokenFactory: () => "scope-participant-token-0001",
});
sessionListener();
await vi.waitFor(() => expect(resetLocal).toHaveBeenCalledOnce());
await vi.waitFor(() =>
expect(runtime.getPhase() as string).toBe("FAILED"),
);
expect(runtime.getSnapshot().isCurrent()).toBe(false);
expect(record.mock.calls).toEqual([
[resetFailure("PARTICIPANT_FAILED", "mandatory-admission")],
]);
});
it("remains failed when local cache reset rejects", async () => {
let sessionListener: () => void = () => {};
const record = vi.fn<(input: DiagnosticRecordInput) => void>();
const runtime = createServerStateScopeRuntime({
session: {
subscribe(listener) {
sessionListener = listener;
return () => {};
},
},
queryInvalidation: {
resetLocal: async () => {
throw new Error("reset failed");
},
},
diagnostics: { record },
tokenFactory: () => "scope-reset-token-0000001",
});
sessionListener();
await vi.waitFor(() =>
expect(runtime.getPhase() as string).toBe("FAILED"),
);
expect(runtime.getSnapshot().isCurrent()).toBe(false);
expect(record.mock.calls).toEqual([[resetFailure("CACHE_RESET_FAILED")]]);
});
it("reads a participant list function at each reset and records a label it cannot carry without it", async () => {
let sessionListener: () => void = () => {};
const record = vi.fn<(input: DiagnosticRecordInput) => void>();
const closed: string[] = [];
const later: { order: number; label: string; close(): void }[] = [];
const runtime = createServerStateScopeRuntime({
session: {
subscribe(listener) {
sessionListener = listener;
return () => {};
},
},
queryInvalidation: { resetLocal: async () => {} },
diagnostics: { record },
participants: () => [
{ order: 4, label: "admission", close: () => void closed.push("admission") },
...later,
],
tokenFactory: () => "scope-participant-list-0001",
});
// Joins after the runtime exists, as the product's closers do.
later.push({
order: 10,
label: "Not A Token",
close() {
closed.push("late");
throw new Error("late close failed");
},
});
sessionListener();
await vi.waitFor(() =>
expect(runtime.getPhase() as string).toBe("FAILED"),
);
expect(closed).toEqual(["admission", "late"]);
// Still recorded, without the label the projection would refuse.
expect(record.mock.calls).toEqual([[resetFailure("PARTICIPANT_FAILED")]]);
});
it("activates the next generation after reset and fails closed on activation error", async () => {
let sessionListener: () => void = () => {};
const steps: string[] = [];
const record = vi.fn<(input: DiagnosticRecordInput) => void>();
const runtime = createServerStateScopeRuntime({
session: {
subscribe(listener) {
sessionListener = listener;
return () => {};
},
},
queryInvalidation: {
resetLocal: async () => {
steps.push("reset");
},
},
activateNextGeneration: async () => {
steps.push("activate");
throw new Error("activation failed");
},
diagnostics: { record },
tokenFactory: () => "scope-activation-token-001",
} as Parameters<typeof createServerStateScopeRuntime>[0] & {
activateNextGeneration(): Promise<void>;
});
sessionListener();
await vi.waitFor(() => expect(steps).toEqual(["reset", "activate"]));
await vi.waitFor(() =>
expect(runtime.getPhase() as string).toBe("FAILED"),
);
expect(record.mock.calls).toEqual([
[resetFailure("GENERATION_ACTIVATION_FAILED")],
]);
});
});
describe("identity-affecting session changes only", () => {
function fakeSession(
initial: Readonly<{ state: SessionState; subject?: string | null }>,
) {
let current = initial;
let listener: () => void = () => {};
return {
session: {
getState: () => current.state,
getSubject: () => current.subject ?? null,
subscribe(next: () => void) {
listener = next;
return () => {};
},
},
notify(next: Readonly<{ state: SessionState; subject?: string | null }>) {
current = next;
listener();
},
};
}
function scopeFor(session: ServerStateScopeDependencies["session"]) {
const resetLocal = vi.fn(async () => {});
const record = vi.fn<(input: DiagnosticRecordInput) => void>();
const lifecycle: ClientScopeLifecycleEvent[] = [];
let tokenSequence = 0;
const runtime = createServerStateScopeRuntime({
session,
queryInvalidation: { resetLocal },
diagnostics: { record },
tokenFactory: () =>
`scope-identity-token-${String(tokenSequence++).padStart(6, "0")}`,
});
runtime.subscribeLifecycle((event) => lifecycle.push(event));
return { runtime, resetLocal, record, lifecycle };
}
const SUBJECT_MISSING_RECORD = {
level: "warn",
eventId: "cache.operation.failed",
context: { operation: "SCOPE_FENCE", reason: "SUBJECT_MISSING" },
};
it.each([
["a repeated sign-out", { state: "unauthenticated" as const }],
[
"a token refresh for the same subject",
{ state: "authenticated" as const, subject: "user-a" },
],
])("does not fence, abort or clear on %s", async (_label, identity) => {
const fake = fakeSession(identity);
const { runtime, resetLocal, record, lifecycle } = scopeFor(fake.session);
const before = runtime.getSnapshot();
fake.notify(identity);
fake.notify({ ...identity });
await Promise.resolve();
expect(lifecycle).toEqual([]);
expect(before.isCurrent()).toBe(true);
expect(before.signal.aborted).toBe(false);
expect(resetLocal).not.toHaveBeenCalled();
expect(record).not.toHaveBeenCalled();
expect(runtime.getPhase()).toBe("READY");
});
it.each([
[
"the state changes",
{ state: "unauthenticated" as const },
{ state: "authenticated" as const, subject: "user-a" },
],
[
"the subject changes",
{ state: "authenticated" as const, subject: "user-a" },
{ state: "authenticated" as const, subject: "user-b" },
],
[
"the user signs out",
{ state: "authenticated" as const, subject: "user-a" },
{ state: "unauthenticated" as const },
],
])("still fences when %s", async (_label, initial, next) => {
const fake = fakeSession(initial);
const { runtime, resetLocal, record, lifecycle } = scopeFor(fake.session);
const before = runtime.getSnapshot();
fake.notify(next);
expect(before.isCurrent()).toBe(false);
expect(before.signal.aborted).toBe(true);
expect(lifecycle[0]).toEqual({ kind: "FENCED", previousGeneration: 1 });
await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY"));
expect(resetLocal).toHaveBeenCalledOnce();
expect(record).not.toHaveBeenCalled();
});
it.each([
["cannot name its subject", null],
["names an empty subject", ""],
])(
"fences and reports SUBJECT_MISSING on every notification when an authenticated session %s",
async (_label, subject) => {
const fake = fakeSession({ state: "authenticated", subject });
const { runtime, resetLocal, record, lifecycle } = scopeFor(fake.session);
const before = runtime.getSnapshot();
fake.notify({ state: "authenticated", subject });
expect(before.isCurrent()).toBe(false);
expect(before.signal.aborted).toBe(true);
expect(lifecycle[0]).toEqual({ kind: "FENCED", previousGeneration: 1 });
await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY"));
expect(record.mock.calls).toEqual([[SUBJECT_MISSING_RECORD]]);
fake.notify({ state: "authenticated", subject });
await vi.waitFor(() => expect(resetLocal).toHaveBeenCalledTimes(2));
expect(record.mock.calls).toEqual([
[SUBJECT_MISSING_RECORD],
[SUBJECT_MISSING_RECORD],
]);
// Signing out is an ordinary fence, not a misbehaving owner.
fake.notify({ state: "unauthenticated" });
await vi.waitFor(() => expect(resetLocal).toHaveBeenCalledTimes(3));
expect(record).toHaveBeenCalledTimes(2);
},
);
it("keeps fencing if diagnostics throws while reporting SUBJECT_MISSING", async () => {
const fake = fakeSession({ state: "authenticated", subject: null });
const runtime = createServerStateScopeRuntime({
session: fake.session,
queryInvalidation: { resetLocal: async () => {} },
diagnostics: {
record() {
throw new Error("diagnostics down");
},
},
tokenFactory: () => "scope-diagnostics-token-001",
});
const before = runtime.getSnapshot();
fake.notify({ state: "authenticated", subject: null });
expect(before.isCurrent()).toBe(false);
expect(runtime.getPhase()).toBe("FENCED");
});
it("does not fence when the demo session re-announces the same user", async () => {
const demo = createDemoSessionAdapter("authenticated");
const listeners: Array<() => void> = [];
const { runtime, resetLocal, lifecycle } = scopeFor({
...demo,
subscribe(listener) {
listeners.push(listener);
return demo.subscribe(listener);
},
});
const before = runtime.getSnapshot();
// A token refresh: the owner notifies while the user stays signed in.
for (const listener of listeners) listener();
await Promise.resolve();
expect(lifecycle).toEqual([]);
expect(before.isCurrent()).toBe(true);
expect(resetLocal).not.toHaveBeenCalled();
await demo.signOut();
expect(before.isCurrent()).toBe(false);
expect(lifecycle[0]).toEqual({ kind: "FENCED", previousGeneration: 1 });
await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY"));
});
it("fences and reports every authenticated notification from an external owner whose readSubject returns null", async () => {
let notify: () => void = () => {};
const session = createExternalAuthSessionAdapter({
readState: () => "authenticated",
readSubject: () => null,
subscribe(listener) {
notify = listener;
return () => {};
},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({ headers: {} }),
recoverSession: async () => "no-session",
notifyUnauthenticated: () => {},
});
const { runtime, resetLocal, record, lifecycle } = scopeFor(session);
const before = runtime.getSnapshot();
notify();
expect(before.isCurrent()).toBe(false);
expect(lifecycle[0]).toEqual({ kind: "FENCED", previousGeneration: 1 });
await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY"));
expect(resetLocal).toHaveBeenCalledOnce();
expect(record.mock.calls).toEqual([[SUBJECT_MISSING_RECORD]]);
});
it("keeps the cache when an external owner refreshes a token for the same subject", async () => {
let notify: () => void = () => {};
const session = createExternalAuthSessionAdapter({
readState: () => "authenticated",
readSubject: () => "user-a",
subscribe(listener) {
notify = listener;
return () => {};
},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({ headers: {} }),
recoverSession: async () => "no-session",
notifyUnauthenticated: () => {},
});
const { runtime, resetLocal, record, lifecycle } = scopeFor(session);
const before = runtime.getSnapshot();
notify();
await Promise.resolve();
expect(lifecycle).toEqual([]);
expect(before.isCurrent()).toBe(true);
expect(resetLocal).not.toHaveBeenCalled();
expect(record).not.toHaveBeenCalled();
});
it("retries a failed reset on a notification with the same identity", async () => {
const fake = fakeSession({ state: "unauthenticated" });
const resetLocal = vi
.fn<() => Promise<void>>()
.mockRejectedValueOnce(new Error("reset failed"))
.mockResolvedValue(undefined);
const runtime = createServerStateScopeRuntime({
session: fake.session,
queryInvalidation: { resetLocal },
tokenFactory: () => "scope-retry-token-0000001",
});
fake.notify({ state: "authenticated", subject: "user-a" });
await vi.waitFor(() =>
expect(runtime.getPhase() as string).toBe("FAILED"),
);
fake.notify({ state: "authenticated", subject: "user-a" });
await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY"));
expect(resetLocal).toHaveBeenCalledTimes(2);
});
});