diff --git a/src/adapters/realtime/index.ts b/src/adapters/realtime/index.ts index a219ef49..e0093f31 100644 --- a/src/adapters/realtime/index.ts +++ b/src/adapters/realtime/index.ts @@ -35,6 +35,7 @@ export { type RealtimeReconnectSession, type RealtimeRecoveryReconnectDirective, } from "./reconnect-coordinator.ts"; +export { realtimeFailure, realtimeSuccess } from "./result.ts"; export { createLivePollHandoffCoordinator, LIVE_POLL_HANDOFF_CEILINGS, diff --git a/src/adapters/realtime/live-poll-handoff-coordinator.ts b/src/adapters/realtime/live-poll-handoff-coordinator.ts index ceb4e769..5ab77f7c 100644 --- a/src/adapters/realtime/live-poll-handoff-coordinator.ts +++ b/src/adapters/realtime/live-poll-handoff-coordinator.ts @@ -97,6 +97,11 @@ export type LivePollHandoffCoordinatorDependencies = Readonly<{ authoritativeCheckpointEstablished: true; }>; limits: LivePollHandoffLimits; + /** + * `apply` and `establishAuthoritativeCheckpoint` build their results with + * `realtimeSuccess`/`realtimeFailure`; a result that is not frozen fails + * with MAPPING_CONTRACT_VIOLATION. + */ apply(input: Readonly<{ writer: LivePollWriterKind; generation: number; diff --git a/src/adapters/realtime/reconnect-coordinator.ts b/src/adapters/realtime/reconnect-coordinator.ts index 4527428c..2e2653a3 100644 --- a/src/adapters/realtime/reconnect-coordinator.ts +++ b/src/adapters/realtime/reconnect-coordinator.ts @@ -41,6 +41,10 @@ export type RealtimeCommittedRecovery = Extract< /** * The hint is coordinator-private metadata. A terminal RealtimeResult can * therefore be returned without rewriting its failure. + * + * Build `result` with `realtimeSuccess`/`realtimeFailure`. The coordinator + * returns the exact object it validated, so a result that is not frozen ends + * the run with PROTOCOL_MISMATCH and no retry. */ export type RealtimeReconnectOutcome = | Readonly<{ @@ -89,7 +93,8 @@ export type RealtimeReconnectCloseClassification = /** * The receipt stays strongly typed until `classifyClosed`. `close` must be - * terminal and idempotent. + * terminal and idempotent. `classifyClosed` builds its results as + * RealtimeReconnectOutcome says. */ export type RealtimeReconnectSession< ClosedReceipt = RealtimeReconnectOutcome, @@ -170,6 +175,7 @@ export type RealtimeReconnectCoordinatorDependencies< RealtimeReconnectAttemptSuccess > >; + /** Build the result with `realtimeSuccess`/`realtimeFailure`. */ confirmTransportBarrier( recovery: RealtimeCommittedRecovery, ): RealtimeResult; diff --git a/src/adapters/realtime/result.ts b/src/adapters/realtime/result.ts index 9bcb900e..3c9880db 100644 --- a/src/adapters/realtime/result.ts +++ b/src/adapters/realtime/result.ts @@ -43,6 +43,14 @@ export type RealtimeDataSnapshot = Readonly<{ frozen: boolean; }>; +/** + * Build every result handed to the reconnect coordinator, the live/poll + * handoff, or an SSE or WebSocket callback with these two functions. Those + * boundaries keep using the object they validated, so they accept only a + * result frozen two levels deep and fail closed on a plain object of the same + * type. The stream coordinator and polling copy the result once and accept + * either. + */ export function realtimeSuccess( value: Value, ): Extract, { ok: true }> { diff --git a/src/adapters/realtime/sse/fetch-sse-connection.ts b/src/adapters/realtime/sse/fetch-sse-connection.ts index f1854baf..e7fcd788 100644 --- a/src/adapters/realtime/sse/fetch-sse-connection.ts +++ b/src/adapters/realtime/sse/fetch-sse-connection.ts @@ -59,6 +59,10 @@ export type FetchSseReadInput = Readonly<{ * Runs after the response and stream contract are validated but before any * event bytes are consumed. A reconnect bridge can hold this gate until the * exact recovery checkpoint's replay barrier is confirmed. + * + * `onOpen` and `onEvent` build their results with + * `realtimeSuccess`/`realtimeFailure`; a result that is not frozen fails + * closed. */ onOpen?( signal: AbortSignal, diff --git a/src/adapters/realtime/websocket/websocket-connection.ts b/src/adapters/realtime/websocket/websocket-connection.ts index 592b328e..0417c313 100644 --- a/src/adapters/realtime/websocket/websocket-connection.ts +++ b/src/adapters/realtime/websocket/websocket-connection.ts @@ -158,6 +158,11 @@ export type WebSocketConnectionDependencies = Readonly<{ endpoint: string, protocol: typeof REALTIME_WEBSOCKET_PROTOCOL, ): WebSocketFacade; + /** + * `onEvent` and `onSubscribed` build their results with + * `realtimeSuccess`/`realtimeFailure`; a result that is not frozen fails + * closed. + */ onEvent( frame: WebSocketEventFrame, signal: AbortSignal, diff --git a/tests/unit/realtime/live-poll-handoff-coordinator.test.ts b/tests/unit/realtime/live-poll-handoff-coordinator.test.ts index f3c1f9c5..49a1eacd 100644 --- a/tests/unit/realtime/live-poll-handoff-coordinator.test.ts +++ b/tests/unit/realtime/live-poll-handoff-coordinator.test.ts @@ -163,6 +163,25 @@ describe("live/poll authoritative writer handoff", () => { expect(highWatermark).toBe(1); }); + it("accepts an apply result only when it is frozen like realtimeSuccess builds it", async () => { + // Type-checks as RealtimeResult, but the handoff reuses the value + // it validated, so it requires a frozen result. + const plain: RealtimeResult = { ok: true, value: undefined }; + const results = [plain, realtimeSuccess(undefined)]; + const harness = createHarness({ + apply: vi.fn(async () => results.shift()!), + }); + const writer = harness.coordinator.currentWriter()!; + + await expect(writer.write("plain", 1)).resolves.toEqual( + realtimeFailure("MAPPING_CONTRACT_VIOLATION", "APPLY", false), + ); + await expect(writer.write("frozen", 1)).resolves.toMatchObject({ + ok: true, + value: { kind: "APPLIED", writer: "LIVE" }, + }); + }); + it("fails closed when a non-cooperative active writer fills the bounded tail", async () => { let firstSignal: AbortSignal | undefined; let firstIsCurrent: (() => boolean) | undefined; diff --git a/tests/unit/realtime/realtime-reconnect-coordinator.test.ts b/tests/unit/realtime/realtime-reconnect-coordinator.test.ts index 55826588..7a7b1b63 100644 --- a/tests/unit/realtime/realtime-reconnect-coordinator.test.ts +++ b/tests/unit/realtime/realtime-reconnect-coordinator.test.ts @@ -18,6 +18,8 @@ import { type RealtimeReconnectOutcome, type RealtimeReconnectSession, type RealtimeRecoveryReconnectDirective, + realtimeFailure as publicRealtimeFailure, + realtimeSuccess as publicRealtimeSuccess, } from "../../../src/adapters/realtime/index.ts"; import { defineReconnectPolicy, @@ -2232,3 +2234,109 @@ describe("transport failures through the reconnect coordinator", () => { }, ); }); + +describe("results that composition code hands the reconnect coordinator", () => { + // Composition code may import only the adapter barrel. Each case passes a + // value that type-checks as RealtimeReconnectOutcome. + it("retries a failure built with the barrel's realtimeFailure", async () => { + const clock = new ManualClock(); + const last = publicRealtimeFailure("CONNECT_TIMEOUT", "CONNECT"); + let attempts = 0; + const coordinator = createRealtimeReconnectCoordinator({ + policy: policy({ maxAttempts: 1 }), + environment: new MutableOnlineEnvironment(true), + clock, + random: () => 0.5, + confirmTransportBarrier: () => publicRealtimeSuccess(undefined), + attempt: () => ({ + result: + ++attempts === 1 + ? publicRealtimeFailure("CONNECT_TIMEOUT", "CONNECT") + : last, + }), + }); + + const running = coordinator.run(); + await flush(); + expect(clock.sleepCalls).toEqual([50]); + clock.advance(50); + + await expect(running).resolves.toBe(last); + expect(attempts).toBe(2); + }); + + const unfrozenFailure: RealtimeReconnectOutcome = { + result: { + ok: false, + error: { + kind: "CONNECT_TIMEOUT", + operation: "CONNECT", + retryable: true, + }, + }, + }; + const unfrozenError: RealtimeReconnectOutcome = { + result: Object.freeze({ + ok: false, + error: { + kind: "CONNECT_TIMEOUT", + operation: "CONNECT", + retryable: true, + }, + } as const), + }; + + it.each([ + ["a plain failure object", unfrozenFailure], + ["a frozen failure around a plain error", unfrozenError], + ] as const)( + "ends the run without a retry when an attempt returns %s", + async (_label, outcome) => { + const clock = new ManualClock(); + let attempts = 0; + const coordinator = createRealtimeReconnectCoordinator({ + policy: policy(), + environment: new MutableOnlineEnvironment(true), + clock, + confirmTransportBarrier: confirmationSucceeded, + attempt: () => { + attempts += 1; + return outcome; + }, + }); + + const running = coordinator.run(); + await flush(); + expect(clock.sleepCalls).toEqual([]); + await expect(running).resolves.toEqual( + realtimeFailure("PROTOCOL_MISMATCH", "CONNECT", false), + ); + expect(attempts).toBe(1); + }, + ); + + it("ends the run when classifyClosed returns a plain success object", async () => { + const clock = new ManualClock(); + const coordinator = createRealtimeReconnectCoordinator({ + policy: policy(), + environment: new MutableOnlineEnvironment(true), + clock, + confirmTransportBarrier: confirmationSucceeded, + attempt: () => + opened( + Object.freeze({ + classifyClosed: (): RealtimeReconnectOutcome => ({ + result: { ok: true, value: undefined }, + }), + close: vi.fn(), + waitClosed: closedSuccessfully, + }), + ), + }); + + await expect(coordinator.run()).resolves.toEqual( + realtimeFailure("PROTOCOL_MISMATCH", "CONNECT", false), + ); + expect(clock.sleepCalls).toEqual([]); + }); +});