Connection middleware
Add policy and observation to the post-connection admit, opened, and closed steps.
WsConnectionMiddleware runs after a successful HTTP Upgrade. It observes events around the application's admission and publication of a connection. Choose message middleware for work that must surround every message.
Three callbacks#
| Callback | When | Signal |
|---|---|---|
admit |
After 101, before publication in the manager | ExecutionCancellation |
opened |
After publication in the connection manager | ExecutionCancellation |
closed |
During connection shutdown cleanup | CleanupCancellation |
Because 101 has already occurred, do not interpret an admit error as HTTP 403. Connection error/close handling applies. Verification requiring pre-101 rejection belongs in handshake or identity middleware.
Register the example#
The connection_policy.rs file on the handshake middleware page also contains ConnectionAudit. To use only the audit component:
use crate::connection_policy::ConnectionAudit;
let builder = WsAppBuilder::default()
.connection_middleware::<ConnectionAudit>();The first application's facade imports include WsAppBuilder. Controller-specific use is #[connection_middleware(ConnectionAudit)]. The descriptor must be MiddlewareKind::WebSocketConnection. Do not repeat a type across global and controller registrations in the same effective plan.
Order and cleanup eligibility#
Global registrations run before controller registrations. Cleanup runs in reverse order for the successfully entered prefix; do not treat an unstarted or failed admission as completed. The closed callback receives the reason category as WsConnectionCloseCategory and observes its own independent cleanup signal.
Connection middleware's closed and a controller's disconnected are separate obligations. The latter is eligible only after a successful connected return; do not apply the hook page's rule in place of middleware event rules.
Resource and time ownership#
Middleware is created once per app. It does not provide a connection-lived DI scope. You can use shared Singleton services in the constructor; do not retain a Scoped transaction in a callback as though a message scope existed there.
connection_middleware_timeout_secs bounds admit/opened invocations and the aggregate closed chain. The socket may already be terminal during cleanup. Keep work such as audit writes bounded and idempotent; do not make cleanup depend on delivering a final message to the live caller.
Sources for this page v0.1.0
This guide is based on the reviewed framework commit.