framed
Adapt a kotlinx-io Source/Sink byte-stream into a message Connection using a 4-byte big-endian length prefix per frame.
Framing: each
sendwrites a 4-byte int (big-endian) followed by frame.size bytes.Reassembly: Source.readByteArray blocks the collecting coroutine until all bytes arrive — the stream side is pull-based. Real transports (TCP) collect on an IO dispatcher.
Oversize protection (symmetric): both directions are checked against maxFrameSize. An oversize
sendthrows FrameTooLargeException before writing; on read, a hostile prefix throws FrameTooLargeException before any allocation.Clean EOF only at a frame boundary: a stream that ends exactly between two frames closes incoming normally. A stream that ends anywhere else — inside a length prefix as well as inside a body — is a truncated stream and propagates as EOFException. A close at a frame boundary is the wire's only graceful leave, so a cut stream must never read as one.
A dead transport is a failure, not a cancellation: a sink that throws a CancellationException at a caller nobody cancelled reaches that caller as an IOException (see Connection.send). A Ktor socket's write channel does this once the socket's job is cancelled.
Assumption: the provided Source is backed by a hot (buffered) stream (e.g. a Ktor read channel or an in-memory kotlinx.io.Buffer). Cold/non-buffered sources that do not allow multiple independent reads would need a single-reader adapter.