// client-transport — SSE client transport for @kyneta/exchange. // // Thin imperative shell around the pure client program (client-program.ts). // The program produces data effects; this module interprets them as I/O. // // FC/IS design: // - client-program.ts: pure Mealy machine (functional core) // - client-transport.ts: effect executor (imperative shell) // // Uses two HTTP channels: // - EventSource (GET) for server→client text frames // - fetch POST for client→server binary frames // // Features: // - Pure Mealy machine for connection lifecycle (client-program.ts) // - Exponential backoff reconnection with jitter // - POST retry with exponential backoff (post-retry.ts), each POST a task // in the transport's scope // - Pipeline-managed fragmentation and reassembly // - Observable connection state via subscribeToTransitions() // // The connection handshake: // 1. Client creates EventSource // 2. The stream's first event carries the connection key → client creates a // channel bound to that key and calls establishChannel() // 3. Synchronizer exchanges establish messages via POST (naming the key) // and SSE // // On EventSource.onerror, the transport closes the EventSource immediately and // takes over reconnection via the program's backoff logic, rather than // letting the browser's built-in EventSource reconnection run. import type { ObservableHandle, StateTransition, TransitionListener, } from "@kyneta/machine" import { createObservableProgram } from "@kyneta/machine" import type { Channel, ChannelMsg, EstablishedChannel, GeneratedChannel, ReconnectOptions, } from "@kyneta/transport" import { forwardClientLifecycle, Pipeline, Transport } from "@kyneta/transport" import { createSseClientProgram, type SseClientEffect, type SseClientMsg, } from "./client-program.js" import { CONNECTION_KEY_EVENT, type ConnectionKey, parseConnectionKey, } from "./connection-key.js" import { DEFAULT_POST_RETRY, type PostRetryOptions, postWithRetry, } from "./post-retry.js" import type { DisconnectReason, SseClientLifecycleEvents, SseClientState, } from "./types.js" // Re-export state types for convenience export type { DisconnectReason, SseClientLifecycleEvents, SseClientState } // --------------------------------------------------------------------------- // Options // --------------------------------------------------------------------------- /** * Default fragment threshold in characters. * 60K chars provides a safety margin below typical 100KB body-parser limits, * accounting for JSON overhead and potential base64 expansion. */ const DEFAULT_FRAGMENT_THRESHOLD = 60_000 /** * Options for the SSE client transport. */ export interface SseClientOptions { /** URL for POST requests (client→server). */ postUrl: string /** URL for SSE EventSource (server→client). */ eventSourceUrl: string /** Reconnection options for EventSource. */ reconnect?: Partial /** * Longest an attempt may take, from opening the stream until the exchange * establishes the channel, through the key event and the handshake. * Default: `DEFAULT_HANDSHAKE_TIMEOUT_MS`. */ connectTimeoutMs?: number /** POST retry options. */ postRetry?: Partial /** * Longest `flush()`, and so `exchange.shutdown()`, waits for in-flight * POSTs, in ms. Default: 2000. */ flushTimeoutMs?: number /** Fragment threshold in characters. Default: 60000 (60K chars). */ fragmentThreshold?: number /** * Largest inbound message payload, in code points. Default: * `DEFAULT_MAX_MESSAGE_SIZE`. */ maxMessageSize?: number /** Lifecycle event callbacks. */ lifecycle?: SseClientLifecycleEvents } // --------------------------------------------------------------------------- // State transition type alias // --------------------------------------------------------------------------- /** * State transition event for SSE client states. */ export type SseClientStateTransition = StateTransition // --------------------------------------------------------------------------- // SseClientTransport // --------------------------------------------------------------------------- /** * SSE client transport for @kyneta/exchange. * * Uses two HTTP channels: * - **EventSource** (GET, long-lived) for server→client text frames * - **fetch POST** for client→server binary frames * * Internally, the connection lifecycle is a `Program` — * a pure Mealy machine whose transitions are deterministically testable. * This class is the imperative shell that interprets data effects as I/O. * * @example * ```typescript * import { createSseClient } from "@kyneta/sse-transport/client" * * const exchange = new Exchange({ * principal: "browser-client", * transports: [createSseClient({ * postUrl: "/sync", * eventSourceUrl: "/events", * reconnect: { enabled: true }, * })], * }) * ``` */ export class SseClientTransport extends Transport { #options: SseClientOptions // Observable program handle — created in onStart(), drives all state #handle: ObservableHandle // Executor-local I/O state — not in the program model #eventSource?: EventSource #serverChannel?: Channel #reconnectTimer?: ReturnType #connectTimer?: ReturnType // Asymmetric wire pipeline: send binary (POST), receive text (SSE) #pipeline: Pipeline<"binary", "text"> readonly #postRetry: PostRetryOptions constructor(options: SseClientOptions) { super({ transportType: "sse-client", flushTimeoutMs: options.flushTimeoutMs, }) this.#options = options this.#postRetry = { ...DEFAULT_POST_RETRY, ...options.postRetry } this.#pipeline = new Pipeline({ send: "binary", receive: "text", opts: { threshold: options.fragmentThreshold ?? DEFAULT_FRAGMENT_THRESHOLD, maxMessageSize: options.maxMessageSize, reassemblyTimeoutMs: 10_000, onError: (e, dir) => console.warn(`[SseClientTransport] wire error (${dir}):`, e), // Lazy: pipeline built in the constructor (pre-`_initialize`). onFrame: ev => this.frameObserver?.(ev), }, }) const program = createSseClientProgram({ url: options.eventSourceUrl, reconnect: options.reconnect, connectTimeoutMs: options.connectTimeoutMs, }) this.#handle = createObservableProgram(program, (effect, dispatch) => { this.#executeEffect(effect, dispatch) }) forwardClientLifecycle( listener => this.#handle.subscribeToTransitions(listener), options.lifecycle, ) } // ========================================================================== // Effect executor — interprets data effects as I/O // ========================================================================== #executeEffect( effect: SseClientEffect, dispatch: (msg: SseClientMsg) => void, ): void { switch (effect.type) { case "create-event-source": { this.#doCreateEventSource(effect.url, dispatch) break } case "close-event-source": { // Forgotten first, so events it fires while closing are stale. const eventSource = this.#eventSource this.#eventSource = undefined eventSource?.close() break } case "add-channel-and-establish": { // The channel is bound to the key it was created with: every POST // it makes names this connection, whatever comes later. this.#serverChannel = this.addChannel(effect.key, { role: "initiator", }) this.establishChannel(this.#serverChannel.channelId) break } case "remove-channel": { if (this.#serverChannel) { this.removeChannel(this.#serverChannel.channelId) this.#serverChannel = undefined } break } case "start-reconnect-timer": { this.#reconnectTimer = setTimeout(() => { this.#reconnectTimer = undefined dispatch({ type: "reconnect-timer-fired" }) }, effect.delayMs) break } case "cancel-reconnect-timer": { clearTimeout(this.#reconnectTimer) this.#reconnectTimer = undefined break } case "start-connect-timer": { clearTimeout(this.#connectTimer) const { attempt } = effect this.#connectTimer = setTimeout(() => { this.#connectTimer = undefined dispatch({ type: "connect-timed-out", attempt }) }, effect.delayMs) break } case "cancel-connect-timer": { clearTimeout(this.#connectTimer) this.#connectTimer = undefined break } case "abort-pending-posts": { // POSTs are the only tasks this transport spawns, so cancelling the // whole scope cancels exactly the pending POSTs. this.cancelTasks() break } } } /** * Create an EventSource and wire up event handlers. The attempt waits * for the key event; a malformed key is ignored, and the connect * deadline fails the attempt. */ #doCreateEventSource( url: string, dispatch: (msg: SseClientMsg) => void, ): void { try { const eventSource = new EventSource(url) this.#eventSource = eventSource // Events from an EventSource the program has abandoned are ignored. const current = () => this.#eventSource === eventSource eventSource.addEventListener( CONNECTION_KEY_EVENT, (event: MessageEvent) => { if (!current()) return const key = parseConnectionKey(String(event.data)) if (key) dispatch({ type: "connection-keyed", key }) }, ) eventSource.onmessage = (event: MessageEvent) => { if (current()) this.#handleMessage(event) } eventSource.onerror = () => { if (current()) dispatch({ type: "event-source-error" }) } } catch (_error) { // EventSource constructor threw (e.g. invalid URL) — treat as error dispatch({ type: "event-source-error" }) } } // ========================================================================== // State observation — delegated to the observable handle // ========================================================================== /** * Get the current connection state. */ getState(): SseClientState { return this.#handle.getState() } /** * Subscribe to state transitions. */ subscribeToTransitions( listener: TransitionListener, ): () => void { return this.#handle.subscribeToTransitions(listener) } /** * Wait for a specific state. */ waitForState( predicate: (state: SseClientState) => boolean, options?: { timeoutMs?: number }, ): Promise { return this.#handle.waitForState(predicate, options) } /** * Wait for a specific status. */ waitForStatus( status: SseClientState["status"], options?: { timeoutMs?: number }, ): Promise { return this.#handle.waitForStatus(status, options) } /** Whether the exchange has established this client's channel. */ get isEstablished(): boolean { return this.#handle.getState().status === "established" } // ========================================================================== // Transport abstract method implementations // ========================================================================== protected generate(key: ConnectionKey): GeneratedChannel { // A new channel is a new connection: stale fragments and alias state // from the previous one must not carry over. this.#pipeline.reset() return { transportType: this.transportType, send: (msg: ChannelMsg) => { // readyState: 0=CONNECTING, 1=OPEN, 2=CLOSED if (!this.#eventSource || this.#eventSource.readyState === 2) { return } // Pipeline<"binary"> send: ChannelMsg → Uint8Array frame(s) for (const r of this.#pipeline.send(msg)) { if (!r.ok) continue const frame = r.value this.spawn("POST", signal => postWithRetry( this.#options.postUrl, frame, key, signal, this.#postRetry, ), ) } }, // `refused` fails the attempt, and the program's exit effects remove // the channel and close the EventSource, whose `close()` fires no // event of its own. close: () => { const state = this.#handle.getState() if ( (state.status === "connected" || state.status === "established") && state.key === key ) { this.#handle.dispatch({ type: "refused" }) } }, } } protected override onChannelEstablished(channel: EstablishedChannel): void { if (channel.channelId === this.#serverChannel?.channelId) { this.#handle.dispatch({ type: "channel-established" }) } } async onStart(): Promise { this.#handle.dispatch({ type: "start" }) } async onStop(): Promise { // Reset, not dispose: a stopped transport may be started again. this.#pipeline.reset() this.#handle.dispatch({ type: "stop" }) } // ========================================================================== // Inbound message handling // ========================================================================== /** * Handle incoming SSE message. * * Each SSE `data:` event contains a text wire frame string. * Feed it through Pipeline<"text">.receive() to decode and * resolve aliases, then deliver ChannelMsgs. */ #handleMessage(event: MessageEvent): void { if (!this.#serverChannel) { return } const data = typeof event.data === "string" ? event.data : String(event.data) for (const r of this.#pipeline.receive(data)) { if (r.ok) this.#handleChannelMessage(r.value) } } /** * Deliver a decoded ChannelMsg to the server channel. */ #handleChannelMessage(msg: ChannelMsg): void { this.#serverChannel?.onReceive(msg) } } // --------------------------------------------------------------------------- // Factory function // --------------------------------------------------------------------------- /** * Create an SSE client transport for browser-to-server connections. * * @example * ```typescript * import { createSseClient } from "@kyneta/sse-transport/client" * * const exchange = new Exchange({ * transports: [createSseClient({ * postUrl: "/sync", * eventSourceUrl: "/events", * reconnect: { enabled: true }, * })], * }) * ``` */ export function createSseClient(options: SseClientOptions): SseClientTransport { return new SseClientTransport(options) }