The defaults
A new application frames with LengthDelimitedFrameCodec: a 4-byte big-endian length prefix, then the payload, with frames over 1,024 bytes refused. Everything inside the frame is bincode, and the connection loop wakes every 100 ms to clear stale partial messages.
buffer_capacity raises or lowers the frame limit for the length-delimited codec. codec() returns the installed codec, which is how the sample checks the change took effect:
let app: WireframeApp = WireframeApp::new().expect("builder");
assert_eq!(app.codec().max_frame_length(), 1024);
let roomier: WireframeApp = WireframeApp::new()
.expect("builder")
.buffer_capacity(64 * 1024)
.read_timeout_ms(250);
assert_eq!(roomier.codec().max_frame_length(), 64 * 1024);
Write a FrameCodec
A protocol with its own framing implements FrameCodec. The trait owns a Tokio Decoder and Encoder for its frame type and tells wireframe four things about a frame: where its payload is, how to wrap an outgoing payload, where a correlation ID lives if the header carries one, and how large a frame may be.
The example below is a small invented protocol: two bytes of length, four bytes of tag, then the payload. The decoder waits until a whole frame has arrived, refuses one that exceeds the limit, and splits the payload off without copying it.
/// Two bytes of length, four bytes of tag, then the payload.
const HEADER_LEN: usize = 6;
#[derive(Debug, Clone)]
pub struct TaggedFrame {
pub tag: u32,
pub payload: Bytes,
}
#[derive(Clone)]
pub struct TagCodec {
max_frame_length: usize,
outgoing_tag: u32,
}
impl TagCodec {
pub fn new(max_frame_length: usize) -> Self {
Self {
max_frame_length: max_frame_length.min(usize::from(u16::MAX)),
outgoing_tag: 0,
}
}
}
pub struct TagDecoder {
max_frame_length: usize,
}
impl Decoder for TagDecoder {
type Item = TaggedFrame;
type Error = io::Error;
fn decode(&mut self, src: &mut BytesMut) -> io::Result<Option<TaggedFrame>> {
if src.len() < HEADER_LEN {
return Ok(None);
}
let len = usize::from(u16::from_be_bytes([src[0], src[1]]));
if len > self.max_frame_length {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"frame too large",
));
}
if src.len() < HEADER_LEN + len {
src.reserve(HEADER_LEN + len - src.len());
return Ok(None);
}
src.advance(2);
let tag = src.get_u32();
let payload = src.split_to(len).freeze();
Ok(Some(TaggedFrame { tag, payload }))
}
}
pub struct TagEncoder {
max_frame_length: usize,
}
impl Encoder<TaggedFrame> for TagEncoder {
type Error = io::Error;
fn encode(&mut self, frame: TaggedFrame, dst: &mut BytesMut) -> io::Result<()> {
// The decoder refuses anything longer, so never write it.
if frame.payload.len() > self.max_frame_length {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"frame too large",
));
}
let len = u16::try_from(frame.payload.len())
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "payload too large"))?;
dst.reserve(HEADER_LEN + frame.payload.len());
dst.put_u16(len);
dst.put_u32(frame.tag);
dst.extend_from_slice(&frame.payload);
Ok(())
}
}
impl FrameCodec for TagCodec {
type Frame = TaggedFrame;
type Decoder = TagDecoder;
type Encoder = TagEncoder;
fn decoder(&self) -> TagDecoder {
TagDecoder {
max_frame_length: self.max_frame_length,
}
}
fn encoder(&self) -> TagEncoder {
TagEncoder {
max_frame_length: self.max_frame_length,
}
}
fn frame_payload(frame: &TaggedFrame) -> &[u8] {
&frame.payload
}
fn frame_payload_bytes(frame: &TaggedFrame) -> Bytes {
frame.payload.clone()
}
fn wrap_payload(&self, payload: Bytes) -> TaggedFrame {
TaggedFrame {
tag: self.outgoing_tag,
payload,
}
}
fn correlation_id(frame: &TaggedFrame) -> Option<u64> {
let _ = frame;
None
}
fn max_frame_length(&self) -> usize {
self.max_frame_length
}
}
frame_payload_bytes is optional. Its default copies the payload slice; overriding it to clone a Bytes hands the payload on with a reference-count increment instead. The tag carries framing metadata. wrap_payload receives the payload bytes and sets outgoing tags to zero. Correlate requests and replies through their envelopes. A codec that does carry a correlation ID in its header may expose it through correlation_id; wireframe consults that only when the decoded envelope has none of its own.
Install it
with_codec swaps the codec and changes the application’s type. wireframe clones the codec for each connection, so a codec that keeps state, such as a sequence counter, should make sure a clone starts fresh.
let codec = TagCodec::new(4096);
let echo: Handler<Envelope> = Arc::new(|_: &Envelope| Box::pin(async {}));
let app: WireframeApp<_, _, Envelope, TagCodec> = WireframeApp::<BincodeSerializer>::new()
.expect("builder")
.with_codec(codec.clone())
.route(1, echo)
.expect("a route");
The sample then feeds an encoded request through the testkit one byte at a time. The decoder returns nothing until a whole frame has arrived, and the reply comes back intact.
wireframe ships three worked codecs in its repository, for Hotline, MySQL, and the Redis serialization protocol (RESP). They are listed on the examples page. The Hotline and MySQL codecs are also reachable from wireframe::codec::examples, though that module is hidden from the API reference.
Read a preamble first
Some protocols open with a handshake before any frame: a magic number, a version, a client name. The server reads it with with_preamble::<T>(), where T is any bincode type, decoding at most 1 KiB with big-endian, fixed-width integers. Bytes read past the preamble are replayed into the framing layer, so nothing is lost.
The read always has a deadline: 10 seconds by default. preamble_timeout replaces it, disable_preamble_timeout removes it, and Duration::ZERO clamps to 1 ms. Without with_preamble, or with a type that encodes to no bytes, nothing is read: the connection goes straight to the application, and a client may stay silent until the server pushes to it. A non-empty preamble is read before the server writes anything, so there the server never speaks first. Call with_preamble before registering preamble hooks, because it clears any set earlier.
#[derive(bincode::Encode, bincode::BorrowDecode, Debug, Clone, PartialEq)]
struct Hello {
magic: [u8; 4],
version: u16,
}
const MAGIC: [u8; 4] = *b"BEAM";
let server = WireframeServer::new(|| -> WireframeApp {
let echo: Handler<Envelope> = Arc::new(|_: &Envelope| Box::pin(async {}));
WireframeApp::default().route(1, echo).expect("route 1")
})
.with_preamble::<Hello>()
.preamble_timeout(Duration::from_secs(2))
.on_preamble_decode_success(move |hello: &Hello, stream| {
if let Some(tx) = seen_tx.lock().expect("lock").take() {
let _ = tx.send(hello.clone());
}
let accepted = hello.magic == MAGIC;
async move {
stream.write_all(&[u8::from(accepted)]).await?;
if accepted {
Ok(())
} else {
// An error here closes the connection, so write first.
Err(std::io::Error::other("unknown protocol"))
}
}
.boxed()
})
.bind("127.0.0.1:0".parse().expect("a socket address"))
.map_err(std::io::Error::other)?;
The success handler receives the decoded preamble and the raw TCP stream, so it can reply before framing starts. The handler above always answers, then refuses an unknown magic number by returning an error. The client sends its preamble with with_preamble as soon as it connects, and must read that answer itself, in on_preamble_success: an unread byte would be taken for the start of the first frame. The callback returns any bytes it read past the answer, so that framing can replay them.
let mut client = WireframeClient::builder()
.with_preamble(Hello {
magic: MAGIC,
version: 3,
})
.on_preamble_success(|_hello, stream| {
async move {
// The server answers with one byte before any frame.
let mut answer = [0; 1];
stream.read_exact(&mut answer).await?;
if answer != [1] {
return Err(std::io::Error::new(
std::io::ErrorKind::ConnectionRefused,
"the server refused the preamble",
));
}
// Nothing was read past the answer, so nothing to replay.
Ok(Vec::new())
}
.boxed()
})
.connect(addr)
.await
.expect("connect");
Codec errors
A decoder error closes the connection unless a recovery hook says otherwise. For the default codec that includes a frame over the limit. A frame that decodes but whose payload is not a valid envelope is different: it counts towards the limit of ten deserialization failures described in the routing guide. The bundled bincode decoders also limit the work a peer can demand with a declared length: a fixed 16 MiB for messages and 1 KiB for preambles. That is separate from the frame limit, and custom decoders need their own validation.

