Files
clean-architecture-frontend…/src/adapters/query-cache/server-state-scope-runtime.ts
T
DongHyeonkaandClaude Opus 5.5 c6300e9d40 feat(auth): require readSubject so a token refresh keeps server state
An external owner without readSubject made every authenticated
notification (every token refresh) abort requests and clear the
server-state cache. readSubject is now a required owner method and
getSubject a required SessionGateway method.

- ExternalSessionOwner.readSubject(): required; the host owner check
  (EXTERNAL_OWNER_METHODS) rejects an owner without it, so the session
  fails closed as integration-failed like any other missing method.
- SessionGateway.getSubject(): required. Anonymous and unavailable
  adapters return null; demo already returned its fixed user.
- Scope runtime: same (state, subject) still skips the fence; a state
  or subject change still fences. An authenticated session with a
  null/empty subject still fences (fail closed) and now records
  cache.operation.failed {operation: SCOPE_FENCE, reason:
  SUBJECT_MISSING} once per fence. Bootstrap passes diagnostics in.
- Docs: starter-experience external owner section and port comments
  describe what readSubject returns, the fail-closed diagnostic and a
  migration note.

RED before the change (vitest tests/unit/server-state-scope-runtime.test.ts
tests/unit/runtime-adapters.test.ts): 4 failed | 31 passed
- fails closed when the owner lacks readSubject:
  expected 'authenticated' to be 'integration-failed'
- fences and reports SUBJECT_MISSING ... null / empty subject, and the
  external owner whose readSubject returns null:
  expected [] to deeply equal [[{ level: 'warn', ... }]]
- type level: an owner literal without readSubject compiled (tsc exit
  0). The new @ts-expect-error pin fails check:types:test with TS2578
  if readSubject becomes optional again.
Pins that stayed green: same-subject token refresh keeps the cache,
subject change fences, sign-out fences, owner missing readState is
rejected.

GREEN: check:architecture, check:types:app, check:types:test, lint,
test:unit (2084), test:component (182), test:reference-feature (59),
test:integration (151), verify:documentation, check:diagnostics,
check:ci all pass.

BREAKING: external auth owners must implement readSubject(); code that
implements AuthSessionPort/SessionGateway directly must implement
getSubject().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 16:25:22 +09:00

266 lines
8.7 KiB
TypeScript

import type { AuthSessionPort } from "../../application/ports/auth-session-port.ts";
import type { DiagnosticsPort } from "../../application/ports/diagnostics-port.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;
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. */
diagnostics?: DiagnosticsPort;
tokenFactory?: () => string;
participants?: 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 participants = [...(dependencies.participants ?? [])].sort(
(left, right) => left.order - right.order,
);
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;
// Steps 4-11: close admission, cancel and clear, release leases.
for (const participant of participants) {
try {
await participant.close();
} catch {
failed = true;
}
}
try {
await dependencies.queryInvalidation.resetLocal();
} catch {
failed = true;
}
previousIdentities.close();
if (disposed || generation !== targetGeneration) return;
if (!failed) {
try {
await dependencies.activateNextGeneration?.();
} catch {
failed = true;
}
}
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 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;
}