A type added by a newer backend ended the connection as MALFORMED_EVENT and left the stream CURRENT. It is now PROTOCOL_MISMATCH/REGISTRY, and any decode failure after the stream lookup marks that stream UNKNOWN (design 13.1). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
402 lines
12 KiB
TypeScript
402 lines
12 KiB
TypeScript
import { describe, expect, it, vi } from "vitest";
|
|
|
|
import type {
|
|
RealtimeAcceptDisposition,
|
|
RealtimeRecoveryCheckpoint,
|
|
} from "../../../src/application/ports/realtime/event-authority.ts";
|
|
import type {
|
|
RealtimeResult,
|
|
} from "../../../src/application/ports/realtime/shared.ts";
|
|
import {
|
|
createRealtimeEventConsumer,
|
|
} from "../../../src/adapters/realtime/event-consumer.ts";
|
|
import type {
|
|
RealtimeEventCodec,
|
|
ValidatedRealtimeEventDto,
|
|
} from "../../../src/adapters/realtime/event-codec.ts";
|
|
import {
|
|
realtimeFailure,
|
|
realtimeSuccess,
|
|
} from "../../../src/adapters/realtime/result.ts";
|
|
import {
|
|
createRealtimeStreamCoordinator,
|
|
type RealtimeStreamCoordinator,
|
|
} from "../../../src/adapters/realtime/stream-coordinator.ts";
|
|
import {
|
|
createFetchSseConnection,
|
|
} from "../../../src/adapters/realtime/sse/fetch-sse-connection.ts";
|
|
import {
|
|
STREAM_ID,
|
|
TEST_MAPPERS,
|
|
createTestRealtimeCodec,
|
|
createTestRealtimeRegistry,
|
|
realtimeEventJson,
|
|
} from "./fixture.ts";
|
|
|
|
function setup(
|
|
recoveryMode:
|
|
| "CURSOR"
|
|
| "SNAPSHOT_ONLY"
|
|
| "SESSION_REBUILD",
|
|
resumeCursor: string | null,
|
|
) {
|
|
const dto = {
|
|
envelope: {
|
|
recoveryMode,
|
|
resumeCursor,
|
|
streamId: "REFERENCE_STREAM",
|
|
},
|
|
} as ValidatedRealtimeEventDto;
|
|
const codec: RealtimeEventCodec = {
|
|
decode: vi.fn(() => realtimeSuccess(dto)),
|
|
};
|
|
const accept = vi.fn<
|
|
(
|
|
event: ValidatedRealtimeEventDto,
|
|
signal?: AbortSignal,
|
|
) => Promise<RealtimeResult<RealtimeAcceptDisposition>>
|
|
>(() =>
|
|
Promise.resolve(
|
|
realtimeSuccess({
|
|
outcome: "DROPPED" as const,
|
|
reason: "DUPLICATE_EVENT" as const,
|
|
}),
|
|
),
|
|
);
|
|
const consumer = createRealtimeEventConsumer({
|
|
codec,
|
|
coordinator: {
|
|
accept,
|
|
} as Pick<RealtimeStreamCoordinator, "accept">,
|
|
});
|
|
return { consumer, accept, codec };
|
|
}
|
|
|
|
describe("realtime transport event consumer", () => {
|
|
it("requires exact equality between SSE id and CURSOR envelope", async () => {
|
|
const matching = setup("CURSOR", "cursor.0001");
|
|
await expect(
|
|
matching.consumer.consume("{}", {
|
|
kind: "SSE_DIRECT_CURSOR",
|
|
eventId: "cursor.0001",
|
|
}),
|
|
).resolves.toMatchObject({ ok: true });
|
|
expect(matching.accept).toHaveBeenCalledTimes(1);
|
|
|
|
const advanced = setup("CURSOR", "cursor.0002");
|
|
await expect(
|
|
advanced.consumer.consume("{}", {
|
|
kind: "SSE_DIRECT_CURSOR",
|
|
eventId: "cursor.0001",
|
|
}),
|
|
).resolves.toEqual(
|
|
realtimeFailure("PROTOCOL_MISMATCH", "RECEIVE"),
|
|
);
|
|
expect(advanced.accept).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("forbids SSE id semantics for non-CURSOR recovery", async () => {
|
|
const runtime = setup("SNAPSHOT_ONLY", null);
|
|
await expect(
|
|
runtime.consumer.consume("{}", {
|
|
kind: "SSE_NO_CURSOR",
|
|
}),
|
|
).resolves.toMatchObject({ ok: true });
|
|
|
|
await expect(
|
|
runtime.consumer.consume("{}", {
|
|
kind: "SSE_DIRECT_CURSOR",
|
|
eventId: "cursor.0001",
|
|
}),
|
|
).resolves.toEqual(
|
|
realtimeFailure("PROTOCOL_MISMATCH", "RECEIVE"),
|
|
);
|
|
});
|
|
|
|
it("serializes an encapsulated WebSocket envelope through the codec", async () => {
|
|
const runtime = setup("SESSION_REBUILD", null);
|
|
await expect(
|
|
runtime.consumer.consumeEncapsulated(
|
|
Object.freeze({ protocol: "REALTIME_EVENT_V1" }),
|
|
),
|
|
).resolves.toMatchObject({ ok: true });
|
|
expect(runtime.codec.decode).toHaveBeenCalledWith(
|
|
'{"protocol":"REALTIME_EVENT_V1"}',
|
|
);
|
|
});
|
|
|
|
it("projects common dispositions into the canonical transport outcome", async () => {
|
|
const runtime = setup("SNAPSHOT_ONLY", null);
|
|
|
|
await expect(
|
|
runtime.consumer.consumeForTransport("{}", {
|
|
kind: "SSE_NO_CURSOR",
|
|
}),
|
|
).resolves.toEqual({
|
|
ok: true,
|
|
value: { kind: "CONTINUE" },
|
|
});
|
|
|
|
const checkpoint = Object.freeze({
|
|
recoveryMode: "SNAPSHOT_ONLY" as const,
|
|
streamEpoch: "stream-epoch.0001",
|
|
lastAppliedSequence: "0",
|
|
resumeCursor: null,
|
|
}) as RealtimeRecoveryCheckpoint;
|
|
runtime.accept.mockResolvedValueOnce(
|
|
realtimeSuccess({
|
|
outcome: "RECOVERED",
|
|
reason: "INITIALIZE",
|
|
resumeState: checkpoint,
|
|
}),
|
|
);
|
|
await expect(
|
|
runtime.consumer.consumeForTransport("{}", {
|
|
kind: "SSE_NO_CURSOR",
|
|
}),
|
|
).resolves.toEqual({
|
|
ok: true,
|
|
value: {
|
|
kind: "RECOVERY_COMMITTED",
|
|
streamId: "REFERENCE_STREAM",
|
|
checkpoint,
|
|
},
|
|
});
|
|
|
|
runtime.accept.mockResolvedValueOnce(
|
|
realtimeSuccess({
|
|
outcome: "DROPPED",
|
|
reason: "RECOVERY_IN_PROGRESS",
|
|
}),
|
|
);
|
|
await expect(
|
|
runtime.consumer.consumeForTransport("{}", {
|
|
kind: "SSE_NO_CURSOR",
|
|
}),
|
|
).resolves.toEqual(
|
|
realtimeFailure("PROTOCOL_MISMATCH", "RECEIVE"),
|
|
);
|
|
|
|
runtime.accept.mockResolvedValueOnce(
|
|
realtimeSuccess({
|
|
outcome: "DROPPED",
|
|
reason: "SCOPE_FENCED",
|
|
}),
|
|
);
|
|
await expect(
|
|
runtime.consumer.consumeForTransport("{}", {
|
|
kind: "SSE_NO_CURSOR",
|
|
}),
|
|
).resolves.toEqual(
|
|
realtimeFailure("SCOPE_FENCED", "RECEIVE"),
|
|
);
|
|
});
|
|
|
|
it("threads transport cancellation into the common authority", async () => {
|
|
const runtime = setup("SNAPSHOT_ONLY", null);
|
|
const active = new AbortController();
|
|
|
|
await runtime.consumer.consume(
|
|
"{}",
|
|
{ kind: "SSE_NO_CURSOR" },
|
|
active.signal,
|
|
);
|
|
expect(runtime.accept).toHaveBeenLastCalledWith(
|
|
expect.anything(),
|
|
active.signal,
|
|
);
|
|
|
|
const aborted = new AbortController();
|
|
aborted.abort();
|
|
await expect(
|
|
runtime.consumer.consume(
|
|
"{}",
|
|
{ kind: "SSE_NO_CURSOR" },
|
|
aborted.signal,
|
|
),
|
|
).resolves.toEqual(
|
|
realtimeFailure("ABORTED", "RECEIVE"),
|
|
);
|
|
expect(runtime.accept).toHaveBeenCalledTimes(1);
|
|
});
|
|
});
|
|
|
|
describe("SSE transport, consumer and stream coordinator together", () => {
|
|
it("keeps reading after a SNAPSHOT_ONLY recovery that needs no transport barrier", async () => {
|
|
const registry = createTestRealtimeRegistry({
|
|
recovery: {
|
|
mode: "SNAPSHOT_ONLY",
|
|
snapshotOperationId: "GET_REFERENCE_REALTIME_SNAPSHOT",
|
|
checkpointCodecId: "ReferenceRealtimeCheckpoint",
|
|
barrier: "NONE",
|
|
},
|
|
delivery: "INVALIDATION_HINT",
|
|
stateBearing: false,
|
|
});
|
|
const snapshots = ["0", "3"];
|
|
const recoveries: string[] = [];
|
|
const apply = vi.fn(async () => realtimeSuccess(undefined));
|
|
const coordinator = createRealtimeStreamCoordinator({
|
|
registry,
|
|
mappers: TEST_MAPPERS,
|
|
authority: {
|
|
effects: { apply },
|
|
recovery: {
|
|
async recover(request) {
|
|
recoveries.push(request.reason);
|
|
const sequence = snapshots.shift() ?? "0";
|
|
return realtimeSuccess({
|
|
kind: "SNAPSHOT_RESET",
|
|
checkpoint: {
|
|
recoveryMode: "SNAPSHOT_ONLY",
|
|
streamEpoch: "stream-epoch-0001",
|
|
lastAppliedSequence: sequence,
|
|
resumeCursor: null,
|
|
snapshotRevision: `snapshot-revision-${sequence}`,
|
|
},
|
|
});
|
|
},
|
|
},
|
|
},
|
|
scope: {
|
|
generation: 7,
|
|
scopeBinding: "scope-binding-0001",
|
|
isCurrent: () => true,
|
|
},
|
|
now: () => 10_000,
|
|
});
|
|
const consumer = createRealtimeEventConsumer({
|
|
codec: createTestRealtimeCodec(registry),
|
|
coordinator,
|
|
});
|
|
await expect(
|
|
coordinator.recover(STREAM_ID, "INITIALIZE"),
|
|
).resolves.toMatchObject({ ok: true });
|
|
|
|
const frame = (sequence: string) =>
|
|
`data: ${realtimeEventJson({
|
|
eventId: `event-0000000${sequence}`,
|
|
sequence,
|
|
recoveryMode: "SNAPSHOT_ONLY",
|
|
resumeCursor: null,
|
|
})}\n\n`;
|
|
const body = [frame("1"), frame("3"), frame("4")].join("");
|
|
const connection = createFetchSseConnection({
|
|
endpoint: "https://app.example.test/events",
|
|
applicationOrigin: "https://app.example.test",
|
|
recoveryMode: "SNAPSHOT_ONLY",
|
|
fetcher: async () =>
|
|
new Response(body, {
|
|
status: 200,
|
|
headers: { "Content-Type": "text/event-stream" },
|
|
}),
|
|
});
|
|
|
|
// Sequence 3 is a gap: the coordinator recovers to snapshot 3, and the
|
|
// stream must keep reading so sequence 4 still applies.
|
|
const closed = await connection.read({
|
|
resumeCursor: null,
|
|
onEvent: (event, signal) =>
|
|
consumer.consumeForTransport(
|
|
event.data,
|
|
{ kind: "SSE_NO_CURSOR" },
|
|
signal,
|
|
),
|
|
});
|
|
|
|
expect(closed).toMatchObject({ ok: true, value: { kind: "EOF" } });
|
|
expect(recoveries).toEqual(["INITIALIZE", "SEQUENCE_GAP"]);
|
|
expect(apply).toHaveBeenCalledTimes(2);
|
|
expect(coordinator.getResumeState(STREAM_ID)).toMatchObject({
|
|
lastAppliedSequence: "4",
|
|
});
|
|
expect(coordinator.inspect(STREAM_ID).awaitingTransportBarrier).toBe(
|
|
false,
|
|
);
|
|
});
|
|
|
|
it("ends on an unregistered event type as a registry mismatch and leaves freshness UNKNOWN", async () => {
|
|
const registry = createTestRealtimeRegistry({
|
|
recovery: {
|
|
mode: "SNAPSHOT_ONLY",
|
|
snapshotOperationId: "GET_REFERENCE_REALTIME_SNAPSHOT",
|
|
checkpointCodecId: "ReferenceRealtimeCheckpoint",
|
|
barrier: "NONE",
|
|
},
|
|
delivery: "INVALIDATION_HINT",
|
|
stateBearing: false,
|
|
});
|
|
const apply = vi.fn(async () => realtimeSuccess(undefined));
|
|
const coordinator = createRealtimeStreamCoordinator({
|
|
registry,
|
|
mappers: TEST_MAPPERS,
|
|
authority: {
|
|
effects: { apply },
|
|
recovery: {
|
|
recover: async () =>
|
|
realtimeSuccess({
|
|
kind: "SNAPSHOT_RESET",
|
|
checkpoint: {
|
|
recoveryMode: "SNAPSHOT_ONLY",
|
|
streamEpoch: "stream-epoch-0001",
|
|
lastAppliedSequence: "0",
|
|
resumeCursor: null,
|
|
snapshotRevision: "snapshot-revision-0",
|
|
},
|
|
}),
|
|
},
|
|
},
|
|
scope: {
|
|
generation: 7,
|
|
scopeBinding: "scope-binding-0001",
|
|
isCurrent: () => true,
|
|
},
|
|
now: () => 10_000,
|
|
});
|
|
const consumer = createRealtimeEventConsumer({
|
|
codec: createTestRealtimeCodec(registry),
|
|
coordinator,
|
|
});
|
|
await expect(
|
|
coordinator.recover(STREAM_ID, "INITIALIZE"),
|
|
).resolves.toMatchObject({ ok: true });
|
|
|
|
// A newer backend added an event type this bundle does not know.
|
|
const frame = (sequence: string, eventType?: string) =>
|
|
`data: ${realtimeEventJson({
|
|
eventId: `event-0000000${sequence}`,
|
|
sequence,
|
|
recoveryMode: "SNAPSHOT_ONLY",
|
|
resumeCursor: null,
|
|
...(eventType === undefined ? {} : { eventType }),
|
|
})}\n\n`;
|
|
const body = frame("1") + frame("2", "ADDED_BY_NEWER_BACKEND");
|
|
const connection = createFetchSseConnection({
|
|
endpoint: "https://app.example.test/events",
|
|
applicationOrigin: "https://app.example.test",
|
|
recoveryMode: "SNAPSHOT_ONLY",
|
|
fetcher: async () =>
|
|
new Response(body, {
|
|
status: 200,
|
|
headers: { "Content-Type": "text/event-stream" },
|
|
}),
|
|
});
|
|
|
|
const closed = await connection.read({
|
|
resumeCursor: null,
|
|
onEvent: (event, signal) =>
|
|
consumer.consumeForTransport(
|
|
event.data,
|
|
{ kind: "SSE_NO_CURSOR" },
|
|
signal,
|
|
),
|
|
});
|
|
|
|
expect(apply).toHaveBeenCalledOnce();
|
|
expect(closed).toEqual(
|
|
realtimeFailure("PROTOCOL_MISMATCH", "REGISTRY", false),
|
|
);
|
|
expect(coordinator.inspect(STREAM_ID).freshness).toBe("UNKNOWN");
|
|
});
|
|
});
|