Files
clean-architecture-frontend…/src/adapters/query-cache/server-state-scope-runtime.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

343 lines
11 KiB
TypeScript

import type { AuthSessionPort } from "../../application/ports/auth-session-port.ts";
import type { DiagnosticsPort } from "../../application/ports/diagnostics-port.ts";
import {
isScopeParticipantLabel,
safeErrorKind,
} from "../../contracts/diagnostics.ts";
import type { QueryInvalidationCoordinator } from "../../contracts/query-invalidation.ts";
import {
createRuntimeIdentityRegistry,
type RuntimeIdentityRegistry,
} from "../../contracts/query-keys.ts";
import type {
CacheScopeSnapshot,
ClientScopeLifecycleEvent,
ClientScopePhase,
ServerStateScopeRuntime,
} from "../../contracts/server-state-scope.ts";
/**
* Steps 4-11 of §10.6 that this runtime does not own directly. Each optional
* capability registers its own closer so the ordering lives in one place rather
* than being re-derived by every subsystem.
*/
export type ScopeResetParticipant = Readonly<{
/** Lower runs earlier; the §10.6 step number is used as the rank. */
order: number;
/**
* 1105/02-01. Names the participant in the diagnostic a failed close
* records (`scope_participant`). Use a lowercase kebab-case token
* (`isScopeParticipantLabel`); any other is left out of that record.
*/
label: string;
close(): void | Promise<void>;
}>;
export type ServerStateScopeDependencies = Readonly<{
/**
* `getState`/`getSubject` let the runtime skip a notification that changes
* neither. Without `getState` every notification fences, as before.
*/
session: Pick<AuthSessionPort, "subscribe"> &
Partial<Pick<AuthSessionPort, "getState" | "getSubject">>;
queryInvalidation: Pick<QueryInvalidationCoordinator, "resetLocal">;
/**
* Hears about an authenticated session that could not name its subject, and
* about every step of a reset that failed (1105/02-01).
*/
diagnostics?: DiagnosticsPort;
tokenFactory?: () => string;
/**
* The closers, or a function read at each reset (1105/02-01): composition
* that learns some of them only after the runtime exists, such as the
* product's, passes the function instead of wrapping them in one closer.
*/
participants?:
| readonly ScopeResetParticipant[]
| (() => readonly ScopeResetParticipant[]);
activateNextGeneration?: () => void | Promise<void>;
}>;
export function createServerStateScopeRuntime(
dependencies: ServerStateScopeDependencies,
): ServerStateScopeRuntime {
const listeners = new Set<() => void>();
const lifecycleListeners = new Set<
(event: ClientScopeLifecycleEvent) => void
>();
const listParticipants = dependencies.participants;
const fixedParticipants =
typeof listParticipants === "function"
? undefined
: orderParticipants(listParticipants ?? []);
let generation = 1;
let identities = newIdentityRegistry(dependencies.tokenFactory);
let fingerprint = scopeFingerprint(dependencies.tokenFactory);
let generationLifetime = new AbortController();
let phase: ClientScopePhase = "READY";
let disposed = false;
let resetChain = Promise.resolve();
let sessionIdentity = readSessionIdentity(dependencies.session).identity;
function createSnapshot(): CacheScopeSnapshot {
const capturedGeneration = generation;
const capturedIdentities = identities;
return Object.freeze({
generation: capturedGeneration,
fingerprint,
identities: capturedIdentities,
signal: generationLifetime.signal,
isCurrent: () =>
!disposed &&
phase === "READY" &&
generation === capturedGeneration &&
identities === capturedIdentities,
});
}
let currentSnapshot = createSnapshot();
function publishLifecycle(event: ClientScopeLifecycleEvent): void {
for (const listener of [...lifecycleListeners]) {
try {
listener(event);
} catch {
// One subscriber defect cannot stop the fence from propagating.
}
}
}
function publishSnapshot(): void {
for (const listener of [...listeners]) {
try {
listener();
} catch {
// Subscriber defects are isolated from the mandatory reset sequence.
}
}
}
const unsubscribe = dependencies.session.subscribe(() => {
if (disposed) return;
// §10.6 is for identity-affecting changes only. A notification that keeps
// (state, subject) — a token refresh, a repeated sign-out — must not abort
// requests and clear the cache. A FAILED scope still retries its reset.
const next = readSessionIdentity(dependencies.session);
if (
next.identity !== null &&
next.identity === sessionIdentity &&
phase !== "FAILED"
) {
return;
}
// The fence below is correct but costly: an owner that cannot name its
// subject clears the cache on every token refresh. Make that visible.
if (next.subjectMissing) reportSubjectMissing(dependencies.diagnostics);
sessionIdentity = next.identity;
const previousIdentities = identities;
const previousGeneration = generation;
// §10.6 steps 1-3 are synchronous: increment the generation, invalidate the
// old snapshot, publish FENCED. Nothing between here and READY may render a
// value that belonged to the previous identity.
generationLifetime.abort();
const targetGeneration = ++generation;
phase = "FENCED";
currentSnapshot = createSnapshot();
publishLifecycle(
Object.freeze({ kind: "FENCED" as const, previousGeneration }),
);
publishSnapshot();
resetChain = resetChain
.catch(() => {})
.then(async () => {
let failed = false;
// 1105/02-01. Each failed step is recorded once, with the label of
// the participant that threw. A FAILED scope fences every request, and
// without this nothing said which closer kept it there.
const report = (
reason: ScopeResetFailureReason,
error: unknown,
label?: string,
) => reportResetFailure(dependencies.diagnostics, reason, error, label);
let participants: readonly ScopeResetParticipant[] = [];
try {
participants =
fixedParticipants ??
orderParticipants(
(listParticipants as () => readonly ScopeResetParticipant[])(),
);
} catch (error) {
failed = true;
report("PARTICIPANTS_UNREADABLE", error);
}
// Steps 4-11: close admission, cancel and clear, release leases.
for (const participant of participants) {
try {
await participant.close();
} catch (error) {
failed = true;
report("PARTICIPANT_FAILED", error, participant.label);
}
}
try {
await dependencies.queryInvalidation.resetLocal();
} catch (error) {
failed = true;
report("CACHE_RESET_FAILED", error);
}
previousIdentities.close();
if (disposed || generation !== targetGeneration) return;
if (!failed) {
try {
await dependencies.activateNextGeneration?.();
} catch (error) {
failed = true;
report("GENERATION_ACTIVATION_FAILED", error);
}
}
if (disposed || generation !== targetGeneration) return;
if (failed) {
phase = "FAILED";
currentSnapshot = createSnapshot();
publishLifecycle(
Object.freeze({
kind: "FAILED" as const,
generation: targetGeneration,
}),
);
publishSnapshot();
return;
}
// Steps 12-15: new identity registry, READY, notify, reopen admission.
identities = newIdentityRegistry(dependencies.tokenFactory);
fingerprint = scopeFingerprint(dependencies.tokenFactory);
generationLifetime = new AbortController();
phase = "READY";
currentSnapshot = createSnapshot();
publishLifecycle(
Object.freeze({ kind: "READY" as const, snapshot: currentSnapshot }),
);
publishSnapshot();
});
});
return Object.freeze({
getSnapshot: () => currentSnapshot,
getPhase: () => phase,
subscribe(listener: () => void) {
listeners.add(listener);
return () => listeners.delete(listener);
},
subscribeLifecycle(listener: (event: ClientScopeLifecycleEvent) => void) {
lifecycleListeners.add(listener);
return () => lifecycleListeners.delete(listener);
},
dispose() {
if (disposed) return;
disposed = true;
phase = "DISPOSED";
generationLifetime.abort();
unsubscribe();
publishLifecycle(Object.freeze({ kind: "DISPOSED" as const }));
listeners.clear();
lifecycleListeners.clear();
identities.close();
},
});
}
/**
* A `null` identity cannot be proven unchanged: no `getState`, a throwing
* owner, or an authenticated session without a non-empty subject (the last one
* is flagged `subjectMissing`). Those always fence, which keeps an account
* switch from reusing the previous cache.
*/
function readSessionIdentity(
session: ServerStateScopeDependencies["session"],
): Readonly<{ identity: string | null; subjectMissing: boolean }> {
try {
const state = session.getState?.();
if (state === undefined) return { identity: null, subjectMissing: false };
const subject = session.getSubject?.();
const knownSubject =
typeof subject === "string" && subject !== "" ? subject : null;
if (state === "authenticated" && knownSubject === null) {
return { identity: null, subjectMissing: true };
}
return {
identity: JSON.stringify([state, knownSubject]),
subjectMissing: false,
};
} catch {
return { identity: null, subjectMissing: false };
}
}
function orderParticipants(
participants: readonly ScopeResetParticipant[],
): readonly ScopeResetParticipant[] {
return [...participants].sort((left, right) => left.order - right.order);
}
type ScopeResetFailureReason =
| "PARTICIPANTS_UNREADABLE"
| "PARTICIPANT_FAILED"
| "CACHE_RESET_FAILED"
| "GENERATION_ACTIVATION_FAILED";
function reportResetFailure(
diagnostics: DiagnosticsPort | undefined,
reason: ScopeResetFailureReason,
error: unknown,
label: string | undefined,
): void {
try {
diagnostics?.record({
level: "warn",
eventId: "cache.operation.failed",
context: {
operation: "SCOPE_RESET",
reason,
error_kind: safeErrorKind(error),
...(isScopeParticipantLabel(label) ? { scope_participant: label } : {}),
},
});
} catch {
// The reset ends FAILED whether or not diagnostics works.
}
}
function reportSubjectMissing(diagnostics: DiagnosticsPort | undefined): void {
try {
diagnostics?.record({
level: "warn",
eventId: "cache.operation.failed",
context: { operation: "SCOPE_FENCE", reason: "SUBJECT_MISSING" },
});
} catch {
// The fence must run whether or not diagnostics works.
}
}
function newIdentityRegistry(
tokenFactory: (() => string) | undefined,
): RuntimeIdentityRegistry {
return createRuntimeIdentityRegistry({
...(tokenFactory ? { tokenFactory } : {}),
});
}
function scopeFingerprint(tokenFactory: (() => string) | undefined): string {
const candidate = tokenFactory?.() ?? crypto.randomUUID();
if (!/^[A-Za-z0-9._:-]{16,128}$/.test(candidate)) {
throw new TypeError("Invalid cache scope fingerprint.");
}
return candidate;
}