fix(query-cache): fence the scope only when session state or subject changes (R-3.2)
Every session notification aborted in-flight requests, bumped the generation and cleared the cache, even when nothing changed. A repeated sign-out or a token-refresh notification wiped the cache, and with V3 calling onUnauthenticated() on a logged-out query it could loop. The scope runtime now reads (getState, getSubject) and skips a notification that leaves both unchanged. An identity it cannot prove unchanged still fences: a session without getState (old behavior), a throwing owner, or an authenticated session with no subject. A FAILED scope still retries its reset on any notification. To make the subject observable, SessionGateway gets an optional `getSubject?(): string | null` and ExternalSessionOwner an optional `readSubject?()` (additive; existing owners keep fencing on every authenticated notification). RED before fix: tests/unit/server-state-scope-runtime.test.ts "does not fence, abort or clear on a repeated sign-out" / "... on a token refresh for the same subject" saw FENCED. Pinned (passing before and after): "still fences when the state changes / the subject changes / an authenticated session cannot name its subject", "retries a failed reset ...". Gates: check:architecture, check:types:app, check:types:test, lint, test:component, test:integration, test:reference-feature pass. test:unit passes except removal-fixture.test.ts (needs generated artifacts/ release evidence absent in a fresh worktree; unrelated). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
ebbd50d4fb
commit
a39eed6c11
@@ -9,6 +9,8 @@ import { CREDENTIAL_HEADER_NAMES } from "../../contracts/rest-profiles.ts";
|
||||
|
||||
export type ExternalSessionOwner = Readonly<{
|
||||
readState(): SessionState;
|
||||
/** Opaque subject identifier; see `SessionGateway.getSubject`. */
|
||||
readSubject?(): string | null;
|
||||
subscribe(listener: () => void): () => void;
|
||||
beginSignIn(returnTo?: string): Promise<void>;
|
||||
signOut(): Promise<void>;
|
||||
@@ -53,6 +55,7 @@ export function createExternalAuthSessionAdapter(
|
||||
): AuthSessionPort {
|
||||
return Object.freeze({
|
||||
getState: () => owner.readState(),
|
||||
getSubject: () => owner.readSubject?.() ?? null,
|
||||
subscribe: (listener) => owner.subscribe(listener),
|
||||
beginSignIn: (returnTo) => owner.beginSignIn(returnTo),
|
||||
signOut: () => owner.signOut(),
|
||||
|
||||
@@ -24,7 +24,12 @@ export type ScopeResetParticipant = Readonly<{
|
||||
}>;
|
||||
|
||||
export type ServerStateScopeDependencies = Readonly<{
|
||||
session: Pick<AuthSessionPort, "subscribe">;
|
||||
/**
|
||||
* `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">;
|
||||
tokenFactory?: () => string;
|
||||
participants?: readonly ScopeResetParticipant[];
|
||||
@@ -49,6 +54,7 @@ export function createServerStateScopeRuntime(
|
||||
let phase: ClientScopePhase = "READY";
|
||||
let disposed = false;
|
||||
let resetChain = Promise.resolve();
|
||||
let sessionIdentity = readSessionIdentity(dependencies.session);
|
||||
|
||||
function createSnapshot(): CacheScopeSnapshot {
|
||||
const capturedGeneration = generation;
|
||||
@@ -89,6 +95,18 @@ export function createServerStateScopeRuntime(
|
||||
|
||||
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 nextSessionIdentity = readSessionIdentity(dependencies.session);
|
||||
if (
|
||||
nextSessionIdentity !== null &&
|
||||
nextSessionIdentity === sessionIdentity &&
|
||||
phase !== "FAILED"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
sessionIdentity = nextSessionIdentity;
|
||||
const previousIdentities = identities;
|
||||
const previousGeneration = generation;
|
||||
|
||||
@@ -185,6 +203,26 @@ export function createServerStateScopeRuntime(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* `null` means the identity cannot be proven unchanged: no `getState`, a
|
||||
* throwing owner, or an authenticated session without a subject. Those always
|
||||
* fence, which keeps an account switch from reusing the previous cache.
|
||||
*/
|
||||
function readSessionIdentity(
|
||||
session: ServerStateScopeDependencies["session"],
|
||||
): string | null {
|
||||
try {
|
||||
const state = session.getState?.();
|
||||
if (state === undefined) return null;
|
||||
const subject = session.getSubject?.();
|
||||
const knownSubject = typeof subject === "string" ? subject : null;
|
||||
if (state === "authenticated" && knownSubject === null) return null;
|
||||
return JSON.stringify([state, knownSubject]);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function newIdentityRegistry(
|
||||
tokenFactory: (() => string) | undefined,
|
||||
): RuntimeIdentityRegistry {
|
||||
|
||||
@@ -6,6 +6,13 @@ export type SessionState =
|
||||
|
||||
export type SessionGateway = Readonly<{
|
||||
getState(): SessionState;
|
||||
/**
|
||||
* Optional opaque identifier of the signed-in subject. The server-state scope
|
||||
* fences only when (state, subject) changes, so a token refresh does not clear
|
||||
* the cache. An authenticated session that returns `null` or omits this is
|
||||
* treated as possibly switched and still fences on every notification.
|
||||
*/
|
||||
getSubject?(): string | null;
|
||||
subscribe(listener: () => void): () => void;
|
||||
beginSignIn(returnTo?: string): Promise<void>;
|
||||
signOut(): Promise<void>;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createServerStateScopeRuntime } from "../../src/adapters/query-cache/server-state-scope-runtime.ts";
|
||||
import type { SessionState } from "../../src/application/ports/auth-session-port.ts";
|
||||
import type { ClientScopeLifecycleEvent } from "../../src/contracts/server-state-scope.ts";
|
||||
|
||||
describe("server-state session generation runtime", () => {
|
||||
@@ -195,3 +196,113 @@ describe("server-state session generation runtime", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
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: ReturnType<typeof fakeSession>["session"]) {
|
||||
const resetLocal = vi.fn(async () => {});
|
||||
const lifecycle: ClientScopeLifecycleEvent[] = [];
|
||||
let tokenSequence = 0;
|
||||
const runtime = createServerStateScopeRuntime({
|
||||
session,
|
||||
queryInvalidation: { resetLocal },
|
||||
tokenFactory: () =>
|
||||
`scope-identity-token-${String(tokenSequence++).padStart(6, "0")}`,
|
||||
});
|
||||
runtime.subscribeLifecycle((event) => lifecycle.push(event));
|
||||
return { runtime, resetLocal, lifecycle };
|
||||
}
|
||||
|
||||
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, 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(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" },
|
||||
],
|
||||
[
|
||||
"an authenticated session cannot name its subject",
|
||||
{ state: "authenticated" as const },
|
||||
{ state: "authenticated" as const },
|
||||
],
|
||||
])("still fences when %s", async (_label, initial, next) => {
|
||||
const fake = fakeSession(initial);
|
||||
const { runtime, resetLocal, 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();
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user