@kyneta/sse-transport
v5.0.0
Published
SSE (Server-Sent Events) network adapter for @kyneta/exchange — client, server, and Express integration
Readme
@kyneta/sse-transport
SSE (Server-Sent Events) transport for @kyneta/exchange — client, server, and Express integration. Provides real-time sync using SSE for server→client messages, as @kyneta/wire text frames, and HTTP POST for client→server messages, as binary CBOR frames.
Subpath Exports
| Export | Entry point | Environment |
|--------|-------------|-------------|
| @kyneta/sse-transport/client | ./dist/client.js | Browser, Bun, Node.js |
| @kyneta/sse-transport/server | ./dist/server.js | Bun, Node.js |
| @kyneta/sse-transport/express | ./dist/express.js | Node.js (Express) |
Server Setup
Express (recommended)
Use createSseExpressRouter for zero-boilerplate integration with Express:
import { Exchange } from "@kyneta/exchange"
import { SseServerTransport } from "@kyneta/sse-transport/server"
import { createSseExpressRouter } from "@kyneta/sse-transport/express"
import express from "express"
const app = express()
const serverTransport = new SseServerTransport()
const exchange = new Exchange({
principal: "server",
type: "service",
transports: [serverTransport],
})
app.use("/sse", createSseExpressRouter(serverTransport, {
syncPath: "/sync",
eventsPath: "/events",
heartbeatInterval: 30000,
}))
app.listen(3000)Hono
For Hono or other frameworks, use SseServerTransport.registerConnection and SseConnection.handlePostBody directly. The events route must send the connection's key as the stream's first event, and the POST route must route by the key alone:
import {
CONNECTION_KEY_EVENT,
CONNECTION_KEY_HEADER,
SseServerTransport,
} from "@kyneta/sse-transport/server"
import { Hono } from "hono"
import { streamSSE } from "hono/streaming"
const sseTransport = new SseServerTransport()
const app = new Hono()
app.get("/sse/events", async (c) => {
// undefined while the transport is stopping or stopped
const connection = sseTransport.registerConnection()
if (!connection) return c.text("unavailable", 503)
return streamSSE(c, async (stream) => {
// sendFn receives pre-encoded text frame strings
connection.setSendFunction((textFrame) => {
stream.writeSSE({ data: textFrame })
})
// Called when the exchange refuses or times out the client
connection.setDisconnectHandler(() => stream.close())
stream.onAbort(() => {
sseTransport.unregisterConnection(connection)
})
// The key is a secret: send it on the stream only, never log it
await stream.writeSSE({ event: CONNECTION_KEY_EVENT, data: connection.key })
await new Promise(() => {}) // keep alive
})
})
app.post("/sse/sync", async (c) => {
const key = c.req.header(CONNECTION_KEY_HEADER)
const connection = key ? sseTransport.connectionFor(key) : undefined
if (!connection) return c.json({ error: "Unknown connection" }, 404)
const body = new Uint8Array(await c.req.arrayBuffer())
const result = connection.handlePostBody(body)
if (result.type === "messages") {
for (const msg of result.messages) {
connection.receive(msg)
}
}
return c.json(result.response.body, result.response.status)
})Cap the POST body at one frame of the transport's message cap, maxBinaryFrameSize(sseTransport.maxMessageSize) from @kyneta/transport, as the Express router does.
Client Setup
Browser
Use createSseClient for browser-to-server connections:
import { Exchange } from "@kyneta/exchange"
import { createSseClient } from "@kyneta/sse-transport/client"
const exchange = new Exchange({
principal: "alice",
transports: [createSseClient({
postUrl: "/sse/sync",
eventSourceUrl: "/sse/events",
reconnect: { enabled: true },
})],
})Connection Lifecycle
The client connection lifecycle is a Program<SseClientMsg, SseClientState, SseClientEffect> from @kyneta/machine — a pure Mealy machine with data effects. An attempt runs from opening the EventSource until the exchange establishes the channel; the connection key, the stream's first event, opens the channel along the way.
The SseClientTransport class is a thin imperative shell that interprets data effects as I/O (FC/IS design). The program itself is deterministically testable with pure data tests (no EventSource, no timing, never flaky).
disconnected → connecting → connected → established
↓ ↓ ↓
reconnecting ← ─ ┴ ─ ─ ─ ─ ─ ─ ┘
↓
connecting (retry)
↓
disconnected (max retries)| State | Description |
|-------|-------------|
| disconnected | No active connection. Optional reason field describes why. |
| connecting | EventSource being created, waiting for the key. Tracks attempt number. |
| connected | Key received; the channel's handshake is in flight. Tracks attempt and key. |
| established | The exchange established the channel — protocol messages flow. |
| reconnecting | Connection lost, scheduling next attempt. Tracks attempt and nextAttemptMs. |
An attempt counts as a success only once the exchange establishes the channel. Every failure before that — an error, the connect deadline, or a refusal by either side — fails the attempt, so a client the server refuses backs off toward reconnect.maxAttempts rather than retrying at once.
Connection Handshake
- Client creates
EventSource, transitions toconnecting - The server's first event carries the connection key; the client transitions to
connected - Client creates its channel, bound to that key, and calls
establishChannel() - The client POSTs
establishnaming the key; the server answers over SSE once it has admitted the client - The exchange establishes the channel; the client transitions to
established
The key is a capability: a POST is routed only by it, and only the client reading the stream learns it. It never appears in a URL, so the URLs are plain strings.
EventSource Error Handling
On EventSource.onerror, the program produces a close-event-source effect and transitions to reconnecting (or disconnected if retries are exhausted). The imperative shell closes the EventSource immediately, preventing the browser's built-in EventSource reconnection from running. This gives the program full control over backoff timing and attempt counting — reconnect delays are computed purely as data effects (start-reconnect-timer).
POST Retry
Client→server messages are sent via HTTP POST, one POST per wire frame. Each POST is retried with exponential backoff at the transport level, which is an imperative-shell concern, not part of the connection lifecycle program:
- Network errors, 5xx responses, and attempts that exceed
postRetry.attemptTimeoutMsare retried, up topostRetry.maxAttemptsattempts in total. - 4xx responses are not retried: the server refused the request, and would refuse it again.
- A POST that gives up is logged once, as
[sse-client] POST failed: …. - When the event stream drops, or the transport stops, in-flight POSTs are aborted silently. No
AbortErrorreaches the page as an unhandled rejection.
exchange.flush() and exchange.shutdown() wait for in-flight POSTs to complete, for at most flushTimeoutMs. With the defaults, a stalled server delays shutdown() by about 2 seconds, and a POST lives at most about 34 seconds (3 attempts of up to 10 s, plus backoff).
Observing State
The public observation API is powered by createObservableProgram from @kyneta/machine:
import { createSseClient } from "@kyneta/sse-transport/client"
const transport = createSseClient({
postUrl: "/sse/sync",
eventSourceUrl: "/sse/events",
lifecycle: {
onStateChange: ({ from, to }) => console.log(`${from.status} → ${to.status}`),
onDisconnect: (reason) => console.log("disconnected:", reason.type),
onReconnecting: (attempt, nextMs) => console.log(`retry #${attempt} in ${nextMs}ms`),
onEstablished: () => console.log("established"),
onReconnected: () => console.log("established again"),
},
})
// Or subscribe to transitions programmatically
const unsub = transport.subscribeToTransitions(({ from, to }) => {
console.log(`${from.status} → ${to.status}`)
})
await transport.waitForStatus("established", { timeoutMs: 5000 })
transport.isEstablished // trueWire Format
Asymmetric wire encoding — text frames downstream (SSE), binary CBOR upstream (POST):
| Direction | Transport | Wire format |
|-----------|-----------|-------------|
| Client → Server | HTTP POST (application/octet-stream) | Binary CBOR frame |
| Server → Client | SSE data: event | Text frame (["2c", seq, <payload>]) |
Text Frames
Every message is wrapped in a text frame — a JSON array with a 2-character prefix followed by the per-direction seq:
Complete frame: ["2c", 42, {"type":"present","docs":[{"docId":"doc-1"}]}]
Fragment frame: ["2f", 42, 0, 3, 1500, "{\"type\":\"offer\"..."]The "2c" prefix means "version 2, complete, no hash". seq is the per-direction message id (it groups a message's fragments). Fragments use "2f" and carry seq, index, total, totalSize, and a JSON substring chunk.
Configuration
Client Options
| Option | Default | Description |
|--------|---------|-------------|
| postUrl | — | POST URL. |
| eventSourceUrl | — | SSE URL. |
| reconnect.enabled | true | Enable automatic reconnection. |
| reconnect.maxAttempts | 10 | Maximum reconnection attempts. |
| reconnect.baseDelay | 1000 | Base delay in ms for exponential backoff. |
| reconnect.maxDelay | 30000 | Maximum delay cap in ms. |
| connectTimeoutMs | 10000 | Longest one attempt may take, through the key and the handshake. |
| postRetry.maxAttempts | 3 | Maximum POST attempts, including the first. |
| postRetry.baseDelay | 1000 | Base delay in ms for POST retry backoff. |
| postRetry.maxDelay | 10000 | Maximum POST retry delay in ms. |
| postRetry.attemptTimeoutMs | 10000 | One POST attempt is abandoned, and counts as failed, after this many ms. |
| flushTimeoutMs | 2000 | Longest flush(), and so exchange.shutdown(), waits for in-flight POSTs. |
| fragmentThreshold | 60000 | Character threshold for text fragmentation. |
| maxMessageSize | DEFAULT_MAX_MESSAGE_SIZE (50 MiB) | Largest inbound message, in code points. |
| lifecycle | — | onStateChange, onDisconnect, onReconnecting, onEstablished, onReconnected. |
Server Options
| Option | Default | Description |
|--------|---------|-------------|
| fragmentThreshold | 60000 | Character threshold for text fragmentation. |
| maxMessageSize | DEFAULT_MAX_MESSAGE_SIZE (50 MiB) | Largest inbound message, in bytes. The Express router caps each POST at one frame of it. |
While the server transport is stopping or stopped, registerConnection returns undefined, and the Express router answers the events request with 503. The client treats that as a failed connect and backs off.
Express Router Options
| Option | Default | Description |
|--------|---------|-------------|
| syncPath | "/sync" | Path for POST endpoint. |
| eventsPath | "/events" | Path for SSE endpoint. |
| heartbeatInterval | 30000 | Heartbeat interval in ms. |
The events route sends the connection's key as the stream's first event (event: kyneta-connection); the POST route reads it from X-Kyneta-Connection and answers 404 for an unknown key.
Heartbeat
The Express router sends SSE comment heartbeats (: heartbeat\n\n) at the configured interval. SSE comments are silently ignored by EventSource clients. This keeps connections alive through proxies and load balancers that terminate idle connections.
Custom Framework Integration
SseConnection.handlePostBody is a framework-agnostic handler for POST requests:
// In your framework's request handler, with the body as a Uint8Array
const result = connection.handlePostBody(body)
if (result.type === "messages") {
for (const msg of result.messages) {
connection.receive(msg)
}
}
// Send response
response.status(result.response.status).json(result.response.body)Response Types
| Result Type | HTTP Status | Meaning |
|-------------|-------------|---------|
| messages | 200 | Message(s) decoded successfully |
| pending | 202 | Fragment received, waiting for more |
| error | 400 | Decode or reassembly error |
The sendFn Pattern
SseConnection.send() handles encoding and fragmentation internally. The injected sendFn receives pre-encoded text frame strings — the framework integration just wraps them in transport syntax:
// Express
connection.setSendFunction((textFrame) => {
res.write(`data: ${textFrame}\n\n`)
})
// Hono
connection.setSendFunction((textFrame) => {
stream.writeSSE({ data: textFrame })
})Architecture
┌──────────────────────────────────────────────────────────┐
│ Client │
│ ┌──────────────────┐ ┌───────────────────┐ │
│ │ SseClientTransport │ │ EventSource │ │
│ │ (binary POST) │─────▶│ (text receive) │ │
│ └──────────────────┘ └───────────────────┘ │
└──────────────────────────────────────────────────────────┘
│ ▲
│ HTTP POST │ SSE
│ (binary wire frame) │ (text wire frame)
▼ │
┌──────────────────────────────────────────────────────────┐
│ Server │
│ ┌──────────────────┐ ┌───────────────────┐ │
│ │ Express Router │ │ SSE Writer │ │
│ │ (handlePostBody) │───────▶│ (sendFn) │ │
│ └──────────────────┘ └───────────────────┘ │
│ │ ▲ │
│ ▼ │ │
│ ┌───────────────────────────────────────────────────┐ │
│ │ SseServerTransport │ │
│ │ ┌────────────────────────────────────────────┐ │ │
│ │ │ SseConnection (per stream, by key) │ │ │
│ │ │ - Pipeline (asymmetric encode/decode) │ │ │
│ │ │ - Pipeline handles send/receive framing │ │ │
│ │ │ - Channel reference │ │ │
│ │ └────────────────────────────────────────────┘ │ │
│ └───────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────┘Peer Dependencies
{
"dependencies": {
"@kyneta/random": "workspace:^"
},
"peerDependencies": {
"@kyneta/machine": "workspace:^",
"@kyneta/transport": "workspace:^"
}
}Express is an optional peer dependency — only needed if using @kyneta/sse-transport/express.
License
MIT
