// client-program — pure Mealy machine for SSE client connection lifecycle. // // The client program encodes every state transition and effect as data. // The imperative shell (client-transport.ts) interprets effects as I/O. // Tests assert on data — no EventSource, no timing, never flaky. // // An attempt runs from opening the event stream until the exchange // establishes the channel. The connection key, the stream's first event, // is a transport gate inside the attempt: only with it can the client POST, // so only then does it create its channel and open the handshake. The // attempt rule (`attemptRule`, @kyneta/transport) is shared with the other // clients: every failure before establishment, including a refusal, fails // the attempt and advances the attempt count, and one connect deadline // bounds the whole span. What leaving a state must undo is derived from the // state (`exitEffects`). // // Algebra: Program // Interpreter: client-transport.ts #executeEffect() import type { Program } from "@kyneta/machine" import type { ReconnectOptions } from "@kyneta/transport" import { attemptRule, DEFAULT_HANDSHAKE_TIMEOUT_MS, DEFAULT_RECONNECT, } from "@kyneta/transport" import type { ConnectionKey } from "./connection-key.js" import type { DisconnectReason, SseClientState } from "./types.js" // --------------------------------------------------------------------------- // Messages // --------------------------------------------------------------------------- export type SseClientMsg = | { type: "start" } | { type: "connection-keyed"; key: ConnectionKey } | { type: "event-source-error" } | { type: "channel-established" } | { type: "refused" } | { type: "connect-timed-out"; attempt: number } | { type: "reconnect-timer-fired" } | { type: "stop" } // --------------------------------------------------------------------------- // Effects (data — interpreted by the imperative shell) // --------------------------------------------------------------------------- export type SseClientEffect = | { type: "create-event-source"; url: string; attempt: number } | { type: "close-event-source" } | { type: "add-channel-and-establish"; key: ConnectionKey } | { type: "remove-channel" } | { type: "start-connect-timer"; attempt: number; delayMs: number } | { type: "cancel-connect-timer" } | { type: "start-reconnect-timer"; delayMs: number } | { type: "cancel-reconnect-timer" } | { type: "abort-pending-posts" } // --------------------------------------------------------------------------- // Program factory // --------------------------------------------------------------------------- export interface SseClientProgramOptions { url: string reconnect?: Partial /** * Longest an attempt may take, from opening the stream until the exchange * establishes the channel. Default: `DEFAULT_HANDSHAKE_TIMEOUT_MS`. */ connectTimeoutMs?: number /** Source of `[0, 1)` random values for jitter. Default: `Math.random` */ randomFn?: () => number } type Step = [SseClientState, ...SseClientEffect[]] /** Everything leaving `state` must undo. */ export function exitEffects(state: SseClientState): SseClientEffect[] { switch (state.status) { case "connecting": return [{ type: "cancel-connect-timer" }, { type: "close-event-source" }] case "connected": return [ { type: "cancel-connect-timer" }, { type: "remove-channel" }, { type: "close-event-source" }, { type: "abort-pending-posts" }, ] case "established": return [ { type: "remove-channel" }, { type: "close-event-source" }, { type: "abort-pending-posts" }, ] case "reconnecting": return [{ type: "cancel-reconnect-timer" }] case "disconnected": return [] } } /** * Create the SSE client connection lifecycle program — a pure Mealy machine. * * The returned `Program` * encodes every state transition and effect as inspectable data. The imperative * shell interprets `SseClientEffect` as actual I/O. */ export function createSseClientProgram( options: SseClientProgramOptions, ): Program { const { url, connectTimeoutMs = DEFAULT_HANDSHAKE_TIMEOUT_MS, randomFn = Math.random, } = options const reconnect: ReconnectOptions = { ...DEFAULT_RECONNECT, ...options.reconnect, } const rule = attemptRule({ reconnect, randomFn, exitEffects, }) function beginAttempt(attempt: number): Step { return [ { status: "connecting", attempt }, { type: "create-event-source", url, attempt }, { type: "start-connect-timer", attempt, delayMs: connectTimeoutMs }, ] } return { init: [{ status: "disconnected" }], update(msg, model): Step { switch (msg.type) { case "start": if (model.status !== "disconnected") return [model] return beginAttempt(1) case "connection-keyed": if (model.status !== "connecting") return [model] return [ { status: "connected", attempt: model.attempt, key: msg.key }, { type: "add-channel-and-establish", key: msg.key }, ] case "channel-established": if (model.status !== "connected") return [model] return [ { status: "established", key: model.key }, { type: "cancel-connect-timer" }, ] case "event-source-error": return rule.fail(model, { type: "error", error: new Error("EventSource connection error"), }) case "refused": return rule.fail(model, { type: "refused" }) case "connect-timed-out": if (!rule.isCurrent(model, msg.attempt)) return [model] return rule.fail(model, { type: "error", error: new Error(`connect timed out after ${connectTimeoutMs}ms`), }) case "reconnect-timer-fired": if (model.status !== "reconnecting") return [model] return beginAttempt(model.attempt) case "stop": return rule.stop(model) } }, } }