Skip to content
wireframe home
Menu

Routes, envelopes, and handlers

A message ID picks the handler. The envelope carries everything else.

wireframe 0.4.0-alpha1 · samples verified 2026-12-02

Two translucent wireframe envelopes stand before equipment cabinets. The first carries a tag reading DATA-ID and ROUTE.
Plate 07 · Concept artwork The envelope. An envelope carries the routing tag that its contents travel under. Concept artwork. The tag’s labels are the artwork’s, not wireframe field names.

Register routes

A route is a u32 message ID and the handler that receives messages carrying it. WireframeApp::route takes both and returns the builder, so routes chain. A handler’s type is Handler<Envelope>: an Arc around a closure that takes &Envelope and returns a pinned, boxed future of (). WireframeApp::route_response registers a handler that returns its reply instead, as a Response; see responses that stream.

routing.rs · two routesWorking example
const LOGIN: u32 = 1;
const TELEMETRY: u32 = 2;

fn handler(name: &'static str) -> Handler<Envelope> {
    Arc::new(move |env: &Envelope| {
        let id = env.id();
        Box::pin(async move { println!("{name} handled message {id}") })
    })
}

fn scope() -> wireframe::Result<WireframeApp> {
    WireframeApp::new()?
        .route(LOGIN, handler("login"))?
        .route(TELEMETRY, handler("telemetry"))
}

Each ID has one handler, whether registered with route or route_response. Registering an ID a second time is an error at setup, not a silent replacement, so a dispatch table can never be ambiguous:

routing.rs · one handler per IDWorking example
let app = scope().expect("two distinct routes");
let refused = app.route(LOGIN, handler("impostor"));
assert!(matches!(
    refused,
    Err(WireframeError::DuplicateRoute(LOGIN))
));

The bundled envelope

Unless told otherwise, an application decodes every frame into Envelope: a message ID, an optional correlation ID, and the payload bytes. The router reads only the ID. The payload is opaque until something decodes it, usually with Message::from_bytes in middleware.

TermLayerWhat it is
FrameTransportThe unit a FrameCodec cuts from the byte stream
EnvelopeRoutingThe decoded wrapper: id, correlation_id, payload
PacketRoutingThe trait an envelope type implements
MessageDomainThe typed value encoded in the payload

A custom envelope

To give handlers a type of their own rather than Envelope, implement Packet, which converts to and from PacketParts, and CorrelatableFrame, which exposes the correlation ID. The example below presents a 16-bit opcode where Envelope has a 32-bit ID; the router still sees a u32.

This changes what handlers see, not what travels on the wire. A connection still decodes the serializer’s Envelope, rebuilds the custom type from its parts for the handler, and sends the reply as an Envelope. A different layout on the wire needs a custom codec as well.

routing.rs · a custom envelopeWorking example
/// What handlers see in place of `Envelope`: a 16-bit opcode, a tag, and the
/// payload. The wire still carries the serializer's `Envelope`.
#[derive(bincode::Encode, bincode::BorrowDecode, Debug, PartialEq)]
struct Stroke {
    opcode: u16,
    tag: Option<u64>,
    payload: Vec<u8>,
}

impl CorrelatableFrame for Stroke {
    fn correlation_id(&self) -> Option<u64> {
        self.tag
    }
    fn set_correlation_id(&mut self, tag: Option<u64>) {
        self.tag = tag;
    }
}

impl Packet for Stroke {
    fn id(&self) -> u32 {
        u32::from(self.opcode)
    }

    fn into_parts(self) -> PacketParts {
        PacketParts::new(u32::from(self.opcode), self.tag, self.payload)
    }

    fn from_parts(parts: PacketParts) -> Self {
        Self {
            opcode: u16::try_from(parts.id()).unwrap_or(u16::MAX),
            tag: parts.correlation_id(),
            payload: parts.into_payload(),
        }
    }
}

The envelope type is the application’s third type parameter. Handlers then receive the custom type:

routing.rs · routing on itWorking example
type StrokeApp = WireframeApp<BincodeSerializer, (), Stroke>;

fn stroke_scope(received: Arc<Mutex<Option<Stroke>>>) -> wireframe::Result<StrokeApp> {
    let draw: Handler<Stroke> = Arc::new(move |stroke: &Stroke| {
        *received.lock().expect("record stroke") = Some(Stroke {
            opcode: stroke.opcode,
            tag: stroke.tag,
            payload: stroke.payload.clone(),
        });
        Box::pin(async {})
    });
    StrokeApp::new()?.route(107, draw)
}

The sample drives this application with the testkit, one byte at a time. An Envelope goes in, the handler sees a Stroke, and an Envelope comes back with its correlation ID intact. Because the handler adds nothing, the reply is the request.

Correlation IDs

The correlation ID ties a reply to its request. A route reply is rebuilt with the request’s message ID and passed through PacketParts::inherit_correlation: if middleware left the correlation ID unset, the request’s is copied across, and if middleware set a different one, the request’s wins and a warning is logged. A route_response handler keeps its own message IDs, but every frame it sends, streamed or not, takes the request’s correlation ID on the same terms; if the request carried none, frames keep their own. When an envelope arrives without a correlation ID, a codec that carries one in its frame header supplies it instead.

A None correlation ID means an unsolicited frame, such as a server push. Use None rather than Some(0).

On the client, call_correlated generates the ID and rejects a reply that does not carry it back. See the client runtime.

Unrouted and malformed traffic

The router answers only what it can route:

  • A message whose ID has no route is logged at warning level and dropped. The peer gets no reply.
  • A frame that does not decode as an envelope counts as a deserialization failure. Ten failures with no message dispatched in between close the connection: the count resets only once decoding, reassembly, and assembly have all succeeded.
  • A frame must hold exactly one envelope, so trailing bytes are a decoding failure. The bundled decoders also refuse a container length over a fixed 16 MiB, whatever the peer declares.
  • Routes are fixed when the application is built. Adding one later means building another application.