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.
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_envelopestamps a correlation ID if the envelope has none, sends it, and returns the ID.receive_envelopereads the next frame as an envelope.call_correlateddoes both and fails withClientError::CorrelationMismatchif 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.
/// 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
}
}
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_setupreturns per-connection state after the connection, and any preamble, succeeds;on_connection_teardownreceives it onclose();on_errorsees failed sends, receives, and calls, but not failures from connecting or the preamble, because the client does not exist yet, nor errors yielded by aResponseStream. - Per frame.
before_sendreceives each serialized frame’s bytes before they are written, andafter_receiveeach raw frame before it is decoded. Several may be registered; they run in order. The sample counts frames withbefore_send. Frames fromsend_streaming, which sends a large body as many frames, bypass it. - Tracing. The client emits
tracingspans around connection and message operations, atINFOfor connect and close andDEBUGforsend,receive,call, andcall_streaming;send_streamingandreceive_streamingcreate none.tracing_configchanges 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.
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_poolandacquirecan 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_waitersacquisitions may queue, 64 by default. Further attempts returnClientError::PoolSaturatedat once. No socket is affected, so retrying later is fine. - Closing is final. A closed pool returns
ClientError::PoolClosed, and one whose scheduler died returnsClientError::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
sendandreceiveon the same lease to keep it.

