// server-transport — SSE server transport for @kyneta/exchange. // // Manages SSE connections from clients, encoding/decoding via the // kyneta text wire format. Framework-agnostic — works with any HTTP // framework through the SseConnection's setSendFunction() callback. // // Usage with Express: // import { SseServerTransport } from "@kyneta/sse-transport/server" // import { createSseExpressRouter } from "@kyneta/sse-transport/express" // // const serverTransport = new SseServerTransport() // app.use("/sse", createSseExpressRouter(serverTransport)) // // Usage with Hono: see the README's recipe, which registers a connection, // sends its key as the stream's first event, and routes POSTs by the // `X-Kyneta-Connection` header with `connectionFor()`. import type { ChannelId, ChannelMsg, GeneratedChannel } from "@kyneta/transport" import { DEFAULT_MAX_MESSAGE_SIZE, Transport } from "@kyneta/transport" import { DEFAULT_FRAGMENT_THRESHOLD, SseConnection } from "./connection.js" import { mintConnectionKey } from "./connection-key.js" // --------------------------------------------------------------------------- // Options // --------------------------------------------------------------------------- /** * Options for the SSE server transport. */ export interface SseServerTransportOptions { /** * Fragment threshold in characters. Messages larger than this are fragmented * into multiple SSE events. * Set to 0 to disable fragmentation. * Default: 60000 (60K chars) */ fragmentThreshold?: number /** * Largest inbound message payload, in bytes. Default: * `DEFAULT_MAX_MESSAGE_SIZE`. */ maxMessageSize?: number } // --------------------------------------------------------------------------- // SseServerTransport // --------------------------------------------------------------------------- /** * SSE server transport. * * Framework-agnostic — works with any HTTP framework through the * `SseConnection.setSendFunction()` callback. Use `registerConnection()` * to integrate with your framework's SSE endpoint handler. * * Each event stream becomes an `SseConnection` with one channel bound to * it: the channel's `send` and `close` act on that connection directly. * The only index, by the server-minted `ConnectionKey`, routes POSTs. * * The connection handshake: * 1. Client opens EventSource (GET /events) * 2. Server calls `registerConnection()` → mints a key, creates a channel, * and sends the key as the stream's first event * 3. Client reads the key → sends establish (POST, naming the key) * 4. Server admits the client → answers establish (SSE) * * The server does NOT call `establishChannel()`: its channels are acceptors, * answering the client's establish. */ export class SseServerTransport extends Transport { /** By key, which only `registerConnection` mints. */ readonly #connections = new Map< string, { readonly connection: SseConnection; readonly channelId: ChannelId } >() readonly #fragmentThreshold: number /** Largest inbound message payload, in bytes. */ readonly maxMessageSize: number constructor(options?: SseServerTransportOptions) { super({ transportType: "sse-server" }) this.#fragmentThreshold = options?.fragmentThreshold ?? DEFAULT_FRAGMENT_THRESHOLD this.maxMessageSize = options?.maxMessageSize ?? DEFAULT_MAX_MESSAGE_SIZE } // ========================================================================== // Transport abstract method implementations // ========================================================================== protected generate(connection: SseConnection): GeneratedChannel { return { transportType: this.transportType, send: (msg: ChannelMsg) => connection.send(msg), close: () => { // Ends the response; the request's close then finds it unregistered. connection.disconnect() this.unregisterConnection(connection) }, } } async onStart(): Promise { // Starts passively: connections arrive via registerConnection() } async onStop(): Promise { for (const { connection } of this.#connections.values()) { connection.disconnect() connection.dispose() } this.#connections.clear() } // ========================================================================== // Connection management // ========================================================================== /** * Register a new event stream: mint its key and create its channel. * * The caller must send `connection.key` as the stream's first event * (`event: kyneta-connection`), and route POSTs naming that key with * `connectionFor()`. Returns `undefined` when the transport is not * accepting (stopping or stopped); the caller should refuse the request. */ registerConnection(): SseConnection | undefined { if (!this.accepting) return undefined const connection = new SseConnection(mintConnectionKey(), { fragmentThreshold: this.#fragmentThreshold, maxMessageSize: this.maxMessageSize, onFrame: ev => this.frameObserver?.(ev), }) // An acceptor: the client opens the handshake once it has its key. const channel = this.addChannel(connection, { role: "acceptor" }) connection._setChannel(channel) this.#connections.set(connection.key, { connection, channelId: channel.channelId, }) return connection } /** * Forget a closed connection and remove its channel. Idempotent. Call it * when the event stream's request closes. */ unregisterConnection(connection: SseConnection): void { const entry = this.#connections.get(connection.key) if (entry?.connection !== connection) return this.#connections.delete(connection.key) connection.dispose() this.removeChannel(entry.channelId) } /** * The connection a POST names by its `X-Kyneta-Connection` header, if * that key is live. */ connectionFor(key: string): SseConnection | undefined { return this.#connections.get(key)?.connection } /** * Get the number of open connections. */ get connectionCount(): number { return this.#connections.size } }