Skip to content
wireframe home
Menu

Streaming, push, and sessions

Stream request bodies, send replies of any shape, and push frames without a request.

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

Plate 22 · Civic setting Service interchange. Coloured service routes cross on separate decks. Civic setting for the Common Signal series.

What the server wires up

Every connection a WireframeServer accepts owns a private ConnectionActor. Handler replies pass through fragmentation, serialization, codec wrapping, before_send, and encoding. Unprompted pushes are already codec frames: they enter at before_send and then are encoded. A handler registered with route_response returns a Response of any shape, and the connection drives it to the end before it dispatches the next request, reading at most one further request ahead. with_push_queues gives each connection its own queues, and a SessionRegistry lets other tasks find them.

A peer sends to a reader inside one session, which passes to bounded work, then to bounded queues, then to a sole writer that sends back to the peer. Cancellation and deadlines sit beside them. Beneath: reads advance while writes wait.
Plate 33 · Technical diagram Duplex session driver. One session owns its reader, its only writer, and bounded work, so reading carries on while a write or a handler waits. Proposed · RFC 0004. None of it has a runtime in 0.4.0-alpha1.

Streaming request bodies

Register a message ID with WireframeApp::streaming_route to handle a request body as it arrives. The server supplies RequestParts with the message ID, optional correlation ID, and protocol metadata, together with a RequestBodyStream. Install a MessageAssembler for protocol-defined multi-frame uploads. Without an assembler, the envelope payload arrives as one chunk.

A streaming handler returns Option<Bytes>. A payload follows the ordinary reply pipeline and carries the request’s IDs. None sends no reply. The route bypasses middleware, so put checks such as authentication in the handler.

One body streams at a time per connection. Completed requests wait behind it, and another streaming request that completes while the slot is busy is delivered later as one chunk. A slow handler can fill the body queue and pause reads. A body error can arrive after earlier chunks have been consumed, so complete any validation needed by the protocol before acknowledging an upload. See the upstream guide’s streaming handler example and failure cases.

Responses that stream

Response describes a reply of any shape: Single frame, a Vec of frames, a Stream of fallible frames, a MultiPacket channel, or Empty. into_stream turns any of them into one boxed stream, which is the form the connection actor consumes.

streaming.rs · a stream of framesWorking example
let vertices = stream::iter((1..=3).map(|n| Ok(Vertex(n))));
let response: Response<Vertex> = Response::Stream(Box::pin(vertices));

let frames: Vec<Vertex> = response.into_stream().try_collect().await.expect("frames");
assert_eq!(frames, vec![Vertex(1), Vertex(2), Vertex(3)]);

route_response registers a handler that returns one. Unlike a route handler, its future may borrow the request. Its frames are Envelope values whatever the request type, and each inherits the request’s correlation ID. Each write is awaited before the stream is polled again, so a slow peer slows the producer. A stream that yields a protocol error goes to handle_error and closes the connection without a terminator.

streaming_client.rs · a route that streamsWorking example
/// Answer a plot request with three rows.
fn plot() -> ResponseHandler<Envelope> {
    Arc::new(|_request: &Envelope| {
        Box::pin(async {
            let ops = ["move", "draw", "blank"]
                .map(|op| Ok(Envelope::new(PLOT, None, op.as_bytes().to_vec())));
            let frames: FrameStream<Envelope, ()> = stream::iter(ops).boxed();
            Response::Stream(frames)
        })
    })
}

A streamed reply ends on the wire only if the protocol says how. Install a WireframeProtocol with with_protocol whose stream_end_frame returns a terminator, or a client waits for one that never comes. The terminator is written as a complete codec frame: it skips fragmentation and serialization, keeps whatever correlation ID it was given, and still passes through before_send. The client recognizes it through Packet::is_stream_terminator.

streaming_client.rs · a protocol that ends the streamWorking example
/// Ends every streamed reply with an envelope whose ID is 0.
struct Plotter;

impl WireframeProtocol for Plotter {
    type Frame = Bytes;
    type ProtocolError = ();

    fn stream_end_frame(&self, _context: &mut ConnectionContext) -> Option<Bytes> {
        // The terminator is written as it is, so it must be a whole codec frame.
        let end = Envelope::new(END_OF_STREAM, None, vec![]);
        let payload = BincodeSerializer.serialize(&end).ok()?;
        Some(LengthDelimitedFrameCodec::new(1024).wrap_payload(Bytes::from(payload)))
    }
}

Back-pressure through a channel

Plate 09 · Concept artwork Queued frames. Frames wait their turn on the avenue, in plain sight, instead of piling up somewhere nobody is counting. Concept artwork for bounded queues. The cubes are not counted frames.

Response::with_channel returns a sender and a MultiPacket response around the matching receiver. A producer task sends frames whenever it has them. Each send waits while the channel is full, so a slow consumer slows the producer instead of growing a buffer. Dropping the last sender ends the response, and the protocol’s terminator follows.

streaming.rs · a channel-backed replyWorking example
let (sender, response) = Response::<Vertex>::with_channel(2);

let producer = tokio::spawn(async move {
    for n in 1..=5 {
        // `send` waits whenever the channel already holds two vertices.
        if sender.send(Vertex(n)).await.is_err() {
            return;
        }
    }
    // Dropping the last sender ends the response.
});

let frames: Vec<Vertex> = response.into_stream().try_collect().await.expect("frames");
producer.await.expect("the producer finished");
assert_eq!(frames.len(), 5);

Priority push queues

PushQueues holds frames a connection should send without being asked: notifications, heartbeats, broadcast traffic. The builder sets a high- and a low-priority capacity, an optional rate limit, and an optional dead-letter queue. Both capacities default to 1, so set them. The rate limit defaults to 100 pushes a second, accepts up to 10,000, and is shared by both queues; unlimited() removes it.

Producers push through a cloneable PushHandle: push_high_priority and push_low_priority wait for room and then for the rate limiter. try_push shares the limiter but never waits. It returns PushError::RateLimited when there is room but no permit, and otherwise applies a PushPolicy to a full queue, optionally warning and forwarding the frame to the dead-letter queue. DropIfFull without a dead-letter queue loses frames and tells the producer it succeeded; wireframe_push_drops_total is how you find out.

On a server, with_push_queues takes the builder as a template, cloned for each connection, so one busy connection never delays another. Pushes are codec frames, Bytes by default, written between replies and between the frames of a streamed one, high priority first, each through before_send. A push too large for the codec fails at once with PushError::FrameTooLarge. A protocol receives each connection’s handle in on_connection_setup; the registry below reaches it from anywhere else.

streaming.rs · a server that speaks firstWorking example
let registry = Arc::new(SessionRegistry::<Bytes>::new());
let app: WireframeApp = WireframeApp::new()?
    .with_push_queues(
        PushQueues::<Bytes>::builder()
            .high_capacity(8)
            .low_capacity(32),
    )
    .with_session_registry(Arc::clone(&registry));
let server = WireframeServer::from_app(app).bind("127.0.0.1:0".parse()?)?;
let addr = server.local_addr().expect("a bound address");
let shutdown = server.spawn().await?;

// The client sends nothing. It waits to be told.
let mut client = WireframeClient::builder().connect(addr).await?;
while registry.active_ids().is_empty() {
    tokio::time::sleep(Duration::from_millis(5)).await;
}

// A push is a codec frame, so serialize the envelope and wrap it.
let news = Envelope::new(NEWS, None, b"plot ready".to_vec());
let payload = Bytes::from(
    BincodeSerializer
        .serialize(&news)
        .expect("an envelope encodes"),
);
let frame = LengthDelimitedFrameCodec::new(1024).wrap_payload(payload);
for (_id, handle) in registry.active_handles() {
    handle.push_low_priority(frame.clone()).await?;
}

let received: Envelope = client.receive_envelope().await?;
assert_eq!(received.payload_bytes(), b"plot ready");

An accepted push is not a delivery receipt. When the server stops, queued frames may be discarded and later pushes fail with PushError::Closed. If a message must arrive, have the protocol acknowledge it.

A push handle feeds a full bounded queue, labelled push: waits for room, then a rate limit of 100 per second, labelled then a permit, and on to the actor. Below, try_push: no wait branches to rate limited, return error, drop, and warn and drop; both drops lead to dead letters, if configured.
Plate 32 · Technical diagram Push queues. A push waits for room and then for the rate limiter. A try_push never waits: without a permit it is refused, and against a full queue its policy returns an error, drops, or warns and drops; a dropped frame goes to the dead-letter queue if there is one. In 0.4.0-alpha1, on every server connection through with_push_queues.

Find a connection later

Plate 18 · Civic setting Civic sphere. A geodesic shell encloses an illuminated skyline, with signals arriving from outside. Civic setting for the Common Signal series.

SessionRegistry maps a ConnectionId to a connection’s PushHandle so that other tasks can reach it, holding each handle weakly so it never keeps a connection alive. Server connections add themselves before on_connection_setup runs and leave when their task ends, however it ends. Share one with with_session_registry, or take the application’s own from session_registry() before handing the application to the server. Identifiers start at 1 and are never reused; read a connection’s from ConnectionContext::connection_id or active_handles rather than choosing one.

A server’s registry holds handles for the codec’s frame type, Bytes by default, because a push is a codec frame rather than an envelope. Outside a server, a registry of any frame type works the same way. insert returns false rather than displace a live entry, and dead entries are pruned on lookup, by active_handles, or by prune().

streaming.rs · a weak registryWorking example
let registry: SessionRegistry<u8> = SessionRegistry::default();
let id = ConnectionId::new(42);
assert!(registry.insert(id, &handle), "the identifier was free");
assert!(registry.get(&id).is_some());

drop((queues, handle));
assert!(
    registry.get(&id).is_none(),
    "a closed connection leaves no handle behind"
);

The connection actor

ConnectionActor drains a connection’s push queues and its current response into one ordered output, polling a cancellation token so it stops promptly on shutdown. High-priority frames go first, but a low-priority frame gets through after at most eight high-priority ones, so a busy high queue cannot starve the low one. A server connection uses that default; an actor driven by hand can change it, and add a time slice, through FairnessConfig.

Five sources, numbered in priority order, shutdown, high priority, low priority, multi-packet, and response stream, feed a box labelled biased select, which sends one ordered output. Beneath: fairness, one low after eight high.
Plate 31 · Technical diagram The connection actor. One task per connection takes from five sources in a fixed order and writes one ordered output. Shutdown is heard first; fairness lets a low-priority frame through after eight high-priority ones. In 0.4.0-alpha1, every server connection runs one, with the default fairness.

Drive one yourself only for a transport Wireframe does not manage. run collects frames into a Vec the caller supplies, and writing them out is the caller’s job, so back-pressure reaches the socket only if that write path provides it. An actor driven by hand runs the hooks given to ConnectionActor::with_hooks. On a server connection, every WireframeProtocol hook installed with with_protocol runs: on_connection_setup, before_send, on_command_end, stream_end_frame, handle_error, and on_eof.

streaming.rs · an actor for a transport of your ownWorking example
let (queues, handle) = PushQueues::<Envelope>::builder()
    .high_capacity(8)
    .low_capacity(8)
    .build()
    .expect("valid capacities");

handle
    .push_low_priority(Envelope::new(30, None, vec![]))
    .await
    .expect("queued");
handle
    .push_high_priority(Envelope::new(10, None, vec![]))
    .await
    .expect("queued");

let reply = stream::iter(vec![Ok(Envelope::new(20, Some(1), vec![]))]).boxed();
let token = CancellationToken::new();
let mut actor: ConnectionActor<Envelope, ()> =
    ConnectionActor::new(queues, handle, Some(reply), token);

let mut out = Vec::new();
actor.run(&mut out).await.expect("the actor drains");
let mut ids: Vec<u32> = out.iter().map(Envelope::id).collect();
ids.sort_unstable();
assert_eq!(ids, vec![10, 20, 30]);