The program on this page is a test in the site’s sample crate. It starts a real server on a loopback port, connects a real client, sends a Ping, and checks the Pong. Every panel below is cut from that file, and the crate runs against wireframe 0.4.0-alpha1 built from source at commit 9408f167, with Rust 1.100.1. wireframe needs Rust 1.95 or newer.
Add the dependencies
wireframe runs on Tokio and, by default, encodes messages with bincode 2. The sample crate also uses async-trait to write middleware, and turns on two opt-in features: pool for client connection pools and testkit for the test drivers. Neither is needed for a first server.
[dependencies]
wireframe = { version = "=0.4.0-alpha1", features = ["pool", "testkit"] }
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "sync", "test-util", "time"] }
async-trait = "0.1.89"
bincode = "2.0.1"
bytes = "1.10.1"
futures = "0.3.31"
tokio-util = { version = "0.7.16", features = ["codec", "rt"] }
Describe the messages
A message is any type bincode can encode and decode. Deriving bincode::Encode and bincode::BorrowDecode is enough: wireframe implements its Message trait for such types, which provides to_bytes and from_bytes. The message ID is not part of the type. It travels in the envelope, so the same type could be routed under any ID. The crate root is deliberately small: each item lives in a module named for its domain, as the imports in this sample show, and wireframe::prelude::* gathers the most common ones.
#[derive(bincode::Encode, bincode::BorrowDecode, Debug)]
struct Ping {
body: String,
}
#[derive(bincode::Encode, bincode::BorrowDecode, Debug, PartialEq)]
struct Pong {
body: String,
}
const PING: u32 = 1;
Route and answer
A route maps a message ID to a handler. A handler is an Arc’d closure that receives a reference to the envelope and returns a boxed future of (). It can inspect the request, log it, or hand work elsewhere, but it does not return the reply. A handler registered with route_response does; the streaming guide covers it.
Replies are written in middleware. Each route’s handler is wrapped in a HandlerService, and the default service answers with the request’s own payload, so an unwrapped route is an echo. A middleware layer calls the inner service, then replaces the reply’s bytes.
/// Middleware that answers every `Ping` with a `Pong`.
struct AnswerPings;
struct AnswerPingsService<S> {
inner: S,
}
#[async_trait]
impl<S> Service for AnswerPingsService<S>
where
S: Service<Error = Infallible> + Send + Sync + 'static,
{
type Error = Infallible;
async fn call(&self, req: ServiceRequest) -> Result<ServiceResponse, Infallible> {
let ping = Ping::from_bytes(req.frame()).map(|(msg, _)| msg).ok();
let mut response = self.inner.call(req).await?;
if let Some(ping) = ping {
let pong = Pong {
body: format!("pong {}", ping.body),
};
*response.frame_mut() = pong.to_bytes().expect("encode Pong");
}
Ok(response)
}
}
#[async_trait]
impl Transform<HandlerService<Envelope>> for AnswerPings {
type Output = HandlerService<Envelope>;
async fn transform(&self, service: HandlerService<Envelope>) -> Self::Output {
let id = service.id();
HandlerService::from_service(id, AnswerPingsService { inner: service })
}
}
With the middleware in place, the application is a route and a wrap. WireframeApp::new() is fallible, as are route and wrap, so the whole chain returns wireframe::Result.
fn build_app() -> wireframe::Result<WireframeApp> {
let handler: Handler<Envelope> = Arc::new(|env: &Envelope| {
let id = env.id();
Box::pin(async move { println!("routed message {id}") })
});
WireframeApp::new()?.route(PING, handler)?.wrap(AnswerPings)
}
Serve it
The application is already built, so WireframeServer::from_app takes it directly. WireframeServer::new takes a factory instead, which it calls once per server run. Either way, the application is prepared once and shared by every connection, so per-connection state belongs in on_connection_setup. Binding moves the server into its bound state; port 0 asks the operating system for a free port, and local_addr reports which one it chose. spawn prepares the application, runs the server in the background, and returns a ServerShutdown.
async fn serve() -> Result<(SocketAddr, ServerShutdown), Box<dyn Error>> {
let server = WireframeServer::from_app(build_app()?)
.workers(2)
.bind("127.0.0.1:0".parse()?)?;
let addr = server.local_addr().expect("a bound address");
let shutdown = server.spawn().await?;
Ok((addr, shutdown))
}
Call it
The client shares the server’s defaults: the same length-delimited framing, the same bincode serializer, the same envelope. call_correlated stamps a correlation ID on a request that has none, sends it, reads the reply, and fails with ClientError::CorrelationMismatch if the reply carries a different one.
async fn call(addr: SocketAddr) -> Result<Pong, Box<dyn Error>> {
let mut client = WireframeClient::builder().connect(addr).await?;
let ping = Ping {
body: "from the scope".into(),
};
let request = Envelope::new(PING, None, ping.to_bytes()?);
let response: Envelope = client.call_correlated(request).await?;
let (pong, _) = Pong::from_bytes(response.payload_bytes())?;
client.close().await;
Ok(pong)
}
Without a preamble, the connection goes straight to the application, and a quiet client stays connected until it leaves. This server only answers; one with push queues can speak first. Once the client has closed, the test stops the server. stop requests shutdown, and drained waits for it to finish. Shutdown closes idle connections. Tracked tasks can still delay drained, so put a timeout around that wait when it needs a deadline.
shutdown.stop();
shutdown.drained().await.expect("a clean stop");
The panels above are excerpts. The whole program, with its imports and the test that calls each part, is in the site’s sample crate at templates/wireframe/samples/ in the df12-www repository. Clone the repository, change into that directory, and run it with the rest of the crate:
git clone https://github.com/leynos/df12-www.git
cd df12-www/templates/wireframe/samples
cargo test --test first_server
