Skip to content
wireframe home
Menu

The client runtime

The client uses the server’s codec, serializer, and envelope, so both ends of a protocol share one definition.

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

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.

Build and connect

WireframeClient::builder() starts from the server’s defaults: a 4-byte big-endian length prefix, 1,024-byte frames, and the bincode serializer. The builder changes them before connecting. codec_config must agree with the server’s buffer_capacity: if small requests work and larger ones fail, the two limits disagree. The client shares the server’s definitions with one exception: it has no fragmentation support, so against a fragmenting server it sees FRAG payloads.

client.rs · configure, connect, callWorking example
let mut client = WireframeClient::builder()
    .codec_config(ClientCodecConfig::default().max_frame_length(1024))
    .socket_options(SocketOptions::default().nodelay(true))
    .before_send(move |_bytes: &mut Vec<u8>| {
        counter.fetch_add(1, Ordering::Relaxed);
    })
    .connect(addr)
    .await
    .expect("connect");

let request = Envelope::new(1, None, b"vector".to_vec());
let reply: Envelope = client.call_correlated(request).await.expect("a reply");

assert!(reply.correlation_id().is_some());

The builder also takes socket_options (TCP_NODELAY, keepalive, buffer sizes), a preamble to send on connect with with_preamble, and a preamble_timeout. close() shuts the connection down and runs the teardown hook.

Correlated calls

The client offers two levels. send, receive, and call work with any message type. The envelope-aware methods work with a Packet:

  • send_envelope stamps a correlation ID if the envelope has none, sends it, and returns the ID.
  • receive_envelope reads the next frame as an envelope.
  • call_correlated does both and fails with ClientError::CorrelationMismatch if the reply carries a different ID.

Correlation IDs come from a per-client counter, also available through next_correlation_id. A wireframe server copies the request’s ID onto its reply, so call_correlated against one matches when nothing else arrives first. It reads the next envelope, whatever it is. On a connection that also receives pushes, a push that lands before the reply is taken for it: one with a missing or different correlation ID fails the call with CorrelationMismatch, and one that carries the request’s ID is returned as the reply. Either way the real reply is left unread, so a protocol with pushes needs its own receive loop that tells notifications from replies.

Read a streamed reply

call_streaming sends a request and returns a ResponseStream that yields each frame of the reply until the protocol’s terminator arrives. The envelope type decides what a terminator is, by overriding Packet::is_stream_terminator. The bundled Envelope has none, so a stream of them ends only when the connection does, with an UnexpectedEof error.

streaming_client.rs · an envelope with a terminatorWorking example
/// An envelope whose message ID 0 means "end of stream".
#[derive(bincode::Encode, bincode::BorrowDecode, Debug, Clone, PartialEq)]
struct Row {
    id: u32,
    correlation_id: Option<u64>,
    payload: Vec<u8>,
}

impl CorrelatableFrame for Row {
    fn correlation_id(&self) -> Option<u64> {
        self.correlation_id
    }

    fn set_correlation_id(&mut self, id: Option<u64>) {
        self.correlation_id = id;
    }
}

impl Packet for Row {
    fn id(&self) -> u32 {
        self.id
    }

    fn into_parts(self) -> PacketParts {
        PacketParts::new(self.id, self.correlation_id, self.payload)
    }

    fn from_parts(parts: PacketParts) -> Self {
        Self {
            id: parts.id(),
            correlation_id: parts.correlation_id(),
            payload: parts.into_payload(),
        }
    }

    fn is_stream_terminator(&self) -> bool {
        self.id == 0
    }
}
streaming_client.rs · reading the rowsWorking example
let request = Row {
    id: 1,
    correlation_id: None,
    payload: b"vertex".to_vec(),
};
let mut rows = client.call_streaming::<Row>(request).await.expect("sent");

let mut ops = Vec::new();
while let Some(row) = rows.next().await {
    let row = row.expect("a correlated row");
    ops.push(String::from_utf8(row.payload).expect("text"));
}

The stream checks each data frame’s correlation ID and ends with ClientError::StreamCorrelationMismatch on the first mismatch. It consumes the terminator before that check. The stream borrows the client mutably while it is live. Read through the terminator before sending another request on the same connection: dropping the stream releases the borrow but leaves any unread frames on the socket, where the next call may mistake them for its reply. If reading cannot finish, close the client and reconnect. StreamingResponseExt::typed_with maps frames to domain values and can skip control frames along the way.

The server in this sample is a WireframeServer with one route_response handler and a protocol that supplies the terminator. See responses that stream.

Hooks and tracing

  • Lifecycle. on_connection_setup returns per-connection state after the connection, and any preamble, succeeds; on_connection_teardown receives it on close(); on_error sees failed sends, receives, and calls, but not failures from connecting or the preamble, because the client does not exist yet, nor errors yielded by a ResponseStream.
  • Per frame. before_send receives each serialized frame’s bytes before they are written, and after_receive each raw frame before it is decoded. Several may be registered; they run in order. The sample counts frames with before_send. Frames from send_streaming, which sends a large body as many frames, bypass it.
  • Tracing. The client emits tracing spans around connection and message operations, at INFO for connect and close and DEBUG for send, receive, call, and call_streaming; send_streaming and receive_streaming create none. tracing_config changes the levels and can time each operation.

Connection pools

With the pool feature, connect_pool keeps a bounded set of reusable sockets, each opened on first use. A lease forwards the usual request methods to one of them; the pool recycles sockets that sit idle past idle_timeout, and reruns the preamble and setup hook for each new one.

client.rs · a poolWorking example
let pool = WireframeClient::builder()
    .connect_pool(
        addr,
        ClientPoolConfig::default()
            .pool_size(2)
            .max_in_flight_per_socket(2)
            .max_waiters(8)
            .idle_timeout(Duration::from_secs(30))
            .fairness_policy(PoolFairnessPolicy::RoundRobin),
    )
    .await
    .expect("a pool");

let lease = pool.acquire().await.expect("a lease");
let request = Envelope::new(1, Some(5), b"blank".to_vec());
let reply: Envelope = lease.call(&request).await.expect("a reply");
assert_eq!(reply.payload_bytes(), b"blank");

max_in_flight_per_socket is an admission budget, not parallel writes: I/O on one socket is still one request at a time. For a long-running workflow that should take fair turns with others, pool.handle() returns a PoolHandle that queues under the pool’s fairness policy instead of acquiring a lease each time.

  • A dead server shows up late. connect_pool and acquire can succeed with the server down, and the first operation is what reports it. In the sample, against a port with nothing listening, that call took 30 seconds and failed with a checkout timeout rather than a refused connection.
  • Waiting is bounded. At most max_waiters acquisitions may queue, 64 by default. Further attempts return ClientError::PoolSaturated at once. No socket is affected, so retrying later is fine.
  • Closing is final. A closed pool returns ClientError::PoolClosed, and one whose scheduler died returns ClientError::SchedulerFailed. Neither means a socket is dirty, and neither is retried: discard the pool and build another.
  • Interrupted work discards the socket. A cancelled operation, or a lease dropped before its reply was read, costs that socket, so a late response cannot reach the next caller. Finish send and receive on the same lease to keep it.