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>
309 lines
10 KiB
TypeScript
309 lines
10 KiB
TypeScript
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", () => {
|
|
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"));
|
|
});
|
|
|
|
it("remains failed when a mandatory participant cannot close", async () => {
|
|
let sessionListener: () => void = () => {};
|
|
const resetLocal = vi.fn(async () => {});
|
|
const runtime = createServerStateScopeRuntime({
|
|
session: {
|
|
subscribe(listener) {
|
|
sessionListener = listener;
|
|
return () => {};
|
|
},
|
|
},
|
|
queryInvalidation: {
|
|
resetLocal,
|
|
},
|
|
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);
|
|
});
|
|
|
|
it("remains failed when local cache reset rejects", async () => {
|
|
let sessionListener: () => void = () => {};
|
|
const runtime = createServerStateScopeRuntime({
|
|
session: {
|
|
subscribe(listener) {
|
|
sessionListener = listener;
|
|
return () => {};
|
|
},
|
|
},
|
|
queryInvalidation: {
|
|
resetLocal: async () => {
|
|
throw new Error("reset failed");
|
|
},
|
|
},
|
|
tokenFactory: () => "scope-reset-token-0000001",
|
|
});
|
|
|
|
sessionListener();
|
|
|
|
await vi.waitFor(() =>
|
|
expect(runtime.getPhase() as string).toBe("FAILED"),
|
|
);
|
|
expect(runtime.getSnapshot().isCurrent()).toBe(false);
|
|
});
|
|
|
|
it("activates the next generation after reset and fails closed on activation error", async () => {
|
|
let sessionListener: () => void = () => {};
|
|
const steps: string[] = [];
|
|
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");
|
|
},
|
|
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"),
|
|
);
|
|
});
|
|
});
|
|
|
|
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);
|
|
});
|
|
});
|