Skip to content
wireframe home
Menu

Middleware and lifecycle hooks

A route handler observes; middleware answers. Hooks give each connection its own state.

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

Write a Transform

Middleware in wireframe follows the Tower and Actix shape. A Service turns a ServiceRequest into a ServiceResponse; a Transform wraps one service in another. WireframeApp::wrap takes any Transform whose output is a HandlerService, the type every route’s handler is held in.

The layer below counts every request on every route. It is generic over the envelope type, so it works with a custom Packet as well as Envelope. HandlerService::from_service keeps the route’s ID while swapping in the wrapping service.

middleware.rs · a counting layerWorking example
/// Counts every request that passes through, on any route.
struct Tally {
    tallied: Arc<AtomicUsize>,
}

struct TallyService<S> {
    inner: S,
    tallied: Arc<AtomicUsize>,
}

#[async_trait]
impl<S> Service for TallyService<S>
where
    S: Service<Error = Infallible> + Send + Sync + 'static,
{
    type Error = Infallible;

    async fn call(&self, req: ServiceRequest) -> Result<ServiceResponse, Infallible> {
        self.tallied.fetch_add(1, Ordering::Relaxed);
        self.inner.call(req).await
    }
}

#[async_trait]
impl<E: Packet> Transform<HandlerService<E>> for Tally {
    type Output = HandlerService<E>;

    async fn transform(&self, service: HandlerService<E>) -> Self::Output {
        let id = service.id();
        let tallied = Arc::clone(&self.tallied);
        HandlerService::from_service(
            id,
            TallyService {
                inner: service,
                tallied,
            },
        )
    }
}

Both traits are async_trait traits, so implementations need the async-trait crate.

Order and scope

  • Per route, once. The application wraps each route’s handler in the full middleware stack when it is prepared, and every connection shares the result. The router chooses the route first, so a message with an unknown ID never reaches middleware.
  • First registered, outermost. The first wrap sees the request first and the reply last. In the sample application, the version upgrade runs before the counter.
  • Infallible. The routed path expects Error = Infallible: a layer that cannot proceed writes an error reply rather than returning an error.

Code that accepts streams itself, rather than using WireframeServer, calls prepare() once and reuses the PreparedApp. The older WireframeApp::handle_connection methods are deprecated because they rebuild the middleware chains for every connection.

Write the reply

A handler registered with route returns nothing, and the default HandlerService answers with the request’s payload. Its reply is therefore written by middleware: call the inner service, then replace the bytes through ServiceResponse::frame_mut(). Getting started builds a full Ping to Pong layer this way. The reply keeps the request’s message ID; see correlation IDs for what happens to its correlation ID. A handler registered with route_response returns its reply itself, as a Response; middleware around it sees an empty frame, because the body travels separately and frame_mut() cannot change it.

A route handler that needs to influence the reply shares state with the middleware, through a channel or a value both capture; one that computes the whole reply is simpler as a route_response handler. ADR 0017 removed the extractor building blocks and app_data, which no dispatch path ever invoked.

What from_fn is for

middleware::from_fn turns an async function into a Transform, but it cannot be passed to wrap: from_fn’s output is an FnService, not a HandlerService, so it fails wrap’s bound. It can still wrap a service directly, inside a handwritten Transform that hands the result to HandlerService::from_service, but for routed middleware a handwritten Transform is the shorter path.

Accept two versions

Middleware can rewrite a request before the handler sees it. This layer upgrades a legacy message format so the handler only ever sees the current one. It tries the current format first, then the legacy format, and checks that each decoder consumed the whole payload. A payload matching neither is answered with an invalid point error and never reaches the handler. The version test only works because version 2 added a field, so a version 1 payload is too short to decode as version 2: bincode carries no type information, and two formats with the same layout decode as each other without complaint. The sample asserts the difference before relying on it.

middleware.rs · upgrade on ingressWorking example
async fn call(&self, mut req: ServiceRequest) -> Result<ServiceResponse, Infallible> {
    if matches!(PointV2::from_bytes(req.frame()), Ok((_, read)) if read == req.frame().len()) {
        return self.inner.call(req).await;
    }
    let Ok((v1, read)) = PointV1::from_bytes(req.frame()) else {
        return Ok(ServiceResponse::new(b"invalid point".to_vec(), None));
    };
    if read != req.frame().len() {
        return Ok(ServiceResponse::new(b"invalid point".to_vec(), None));
    }
    let v2 = PointV2 {
        id: v1.id,
        display_name: v1.name,
        intensity: 0,
    };
    *req.frame_mut() = v2.to_bytes().expect("encode PointV2");
    self.inner.call(req).await
}

In the sample, a version 1 point goes in and the echoed reply decodes as version 2. A production version of this layer would also count legacy traffic, so the old format can be retired when the count reaches zero.

Connection setup and teardown

WireframeApp::on_connection_setup runs once when a connection starts and returns a value of any type. That value is held for the life of the connection and handed to on_connection_teardown when the stream ends. Registering a setup hook changes the application’s connection-state type parameter.

middleware.rs · per-connection stateWorking example
let app = app
    .on_connection_setup(|| async {
        let link = Link::default();
        link.opened.fetch_add(1, Ordering::Relaxed);
        link
    })?
    .on_connection_teardown(move |link: Link| {
        let closed = Arc::clone(&closed);
        async move {
            closed.fetch_add(link.opened.load(Ordering::Relaxed), Ordering::Relaxed);
        }
    })?;

Both hooks are async. Setup runs before any frame is read, after a preamble if the server expects one. Handlers and middleware have no access to this state; it is for per-connection bookkeeping such as metrics, registration, and cleanup. To share state with a handler, capture it when building the closure, as the counting layer above does with its counter.

The WireframeProtocol trait, installed with with_protocol, defines further hooks, and a server connection runs all of them. Its own on_connection_setup receives the connection’s PushHandle before the first frame is read; before_send runs once on every outbound frame, including each fragment, streamed frame, terminator, and push, after the codec has wrapped it and just before it is encoded; on_command_end follows each completed reply, a plain route reply included.

middleware.rs · a protocol hookWorking example
/// Runs on every response frame a server connection sends, after the codec
/// has wrapped it and just before it is encoded.
struct Stamped;

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

    fn before_send(&self, frame: &mut Bytes, _context: &mut ConnectionContext) {
        let mut stamped = BytesMut::from(frame.as_ref());
        stamped.extend_from_slice(b"!");
        *frame = stamped.freeze();
    }
}

What it writes must still fit the codec’s max_frame_length. The default codec rejects an oversized frame, which fails the send and ends the connection, while a custom encoder must enforce the limit itself. stream_end_frame, handle_error, and on_eof concern streamed replies and truncated frames; see responses that stream and codec errors. on_command_end does not run for a cancelled reply, so cleanup belongs in teardown.