WebSocketConnection
Adapts any Ktor DefaultWebSocketSession into a kuilt Connection — byte-transparent binary framing, single-collection incoming, idempotent close.
Works for both the client path (io.ktor.client.plugins.websocket.DefaultClientWebSocketSession) and the server path (io.ktor.server.websocket.DefaultWebSocketServerSession) — both extend DefaultWebSocketSession.
Primary use — in-process client spoke for testApplication tests. Open a client WebSocket session and wrap it into a kuilt Connection to build a spoke that handshakes against a KtorConnectionSource-mounted hub route:
testApplication {
val source = KtorConnectionSource(application, "/hub")
val client = createClient { install(WebSockets) }
client.webSocket("/hub") {
val clientSeam = meshSeam(PeerId("client"), listOf(WebSocketConnection(this)), dispatcher)
// clientSeam.peers now contains the hub's PeerId
}
}Wire format: byte-transparent. Each binary WebSocket frame's payload is the whole message, delivered verbatim; no framing prefix, no in-band handshake. A non-binary application frame is a protocol error and completes incoming exceptionally, which tears the seam down.
incoming: the session's binary frames, mapped to ByteArray. Single-collection (the seam collects it exactly once). Close/EOF/error end the channel, completing the flow so the seam transitions to Torn.
send: a session that has closed throws IOException with the session's own exception as its cause. Ktor reports a closed session as a CancellationException: Netty and CIO sessions cancel their outgoing queue when the socket closes, and an OkHttp session closes its queue with one. A caller nobody cancelled must not hear that as a cancellation (see Connection.send), so this tells the two apart by asking whether the caller's own job is cancelled.
close: closes the underlying session. Idempotent — Ktor's io.ktor.websocket.close is a no-op once the session is already closing.
flush: the answer depends on the Ktor engine under the session.
A server session, and a client session on the CIO, Darwin or browser engine, answers FlushOutcome.Drained. That rests on queue order and nothing else: a close goes down the session's own queue behind the frames ahead of it.
session.flushskips that queue, so a frame can still be in it when this answers. Closing theHttpClient, cancelling the session or exiting the process instead of closing this connection can still lose such a frame (read from Ktor's source, not run).OkHttp answers FlushOutcome.Unsupported. Its session ignores what
WebSocket.sendreturns, so a frame past OkHttp's 16 MiB send queue is dropped with no error, and itsflushis empty. Measured: 3,000 frames of 16 KiB lost frames 3 runs of 3, with every flush sayingDrained.Any other engine answers FlushOutcome.Unsupported too, since nobody has read what a returning send means on it.
All three answer FlushOutcome.Failed once this connection has closed, or the session says it has.