pub struct WireframeApp<S: Serializer + Send + Sync = BincodeSerializer, C: Send + 'static = (), E: Packet = Envelope, F: FrameCodec = LengthDelimitedFrameCodec> { /* private fields */ }Expand description
Configures routing and middleware for a WireframeServer.
The builder stores registered routes and middleware without enforcing an
ordering. Methods return Result<Self> so registrations can be chained
ergonomically.
Implementations§
Source§impl<S, C, E, F> WireframeApp<S, C, E, F>
impl<S, C, E, F> WireframeApp<S, C, E, F>
Sourcepub fn with_codec<F2: FrameCodec>(self, codec: F2) -> WireframeApp<S, C, E, F2>
pub fn with_codec<F2: FrameCodec>(self, codec: F2) -> WireframeApp<S, C, E, F2>
Replace the frame codec used for framing I/O.
This resets any installed protocol hooks, push-queue template, and session registry because the frame type may change across codecs. Fragmentation is disabled so callers can reconfigure explicitly for the new frame budget.
Sourcepub fn serializer<Ser>(self, serializer: Ser) -> WireframeApp<Ser, C, E, F>
pub fn serializer<Ser>(self, serializer: Ser) -> WireframeApp<Ser, C, E, F>
Replace the serializer used for messages.
Source§impl<S, C, E> WireframeApp<S, C, E, LengthDelimitedFrameCodec>
impl<S, C, E> WireframeApp<S, C, E, LengthDelimitedFrameCodec>
Sourcepub fn buffer_capacity(self, capacity: usize) -> Self
pub fn buffer_capacity(self, capacity: usize) -> Self
Set the initial buffer capacity for framed reads. Clamped between 64 bytes and 16 MiB.
This also clears any previously configured fragmentation settings.
Re-enable fragmentation explicitly with WireframeApp::enable_fragmentation
(or WireframeApp::fragmentation) after changing the frame budget.
Source§impl<S, C, E, F> WireframeApp<S, C, E, F>
impl<S, C, E, F> WireframeApp<S, C, E, F>
Sourcepub fn read_timeout_ms(self, timeout_ms: u64) -> Self
pub fn read_timeout_ms(self, timeout_ms: u64) -> Self
Configure the inbound read wake-up interval in milliseconds.
Clamped between 1 and 86,400,000 milliseconds (24 h). When the interval elapses without a frame, the connection purges expired partial messages and keeps waiting: this does not close an idle connection.
Sourcepub const fn fragmentation(self, config: Option<FragmentationConfig>) -> Self
pub const fn fragmentation(self, config: Option<FragmentationConfig>) -> Self
Override the fragmentation configuration.
Provide None to disable fragmentation entirely.
Sourcepub const fn memory_budgets(self, budgets: MemoryBudgets) -> Self
pub const fn memory_budgets(self, budgets: MemoryBudgets) -> Self
Configure per-connection memory budgets for inbound buffering.
These budgets apply across the inbound assembly pipeline. Message assembly uses them for per-frame rejection, and retained fragment and assembly bytes together drive soft-pressure read pacing and hard-cap connection aborts.
Sourcepub fn enable_fragmentation(self) -> Self
pub fn enable_fragmentation(self) -> Self
Enable transport fragmentation using codec-derived defaults.
The derived settings are bounded by the current frame codec budget.
Call this after with_codec or buffer_capacity so defaults align with
the final frame length.
Source§impl<S, C, E, F> WireframeApp<S, C, E, F>
impl<S, C, E, F> WireframeApp<S, C, E, F>
Source§impl<S, C, E, F> WireframeApp<S, C, E, F>
impl<S, C, E, F> WireframeApp<S, C, E, F>
Sourcepub fn on_connection_setup<SetupFn, Fut, C2>(
self,
f: SetupFn,
) -> Result<WireframeApp<S, C2, E, F>>
pub fn on_connection_setup<SetupFn, Fut, C2>( self, f: SetupFn, ) -> Result<WireframeApp<S, C2, E, F>>
Register a callback invoked when a new connection is established.
The callback can perform authentication or other setup tasks and returns connection-specific state stored for the connection’s lifetime.
§Type Parameters
This method changes the connection state type parameter from C to C2.
This means that any subsequent builder methods will operate on the new connection state type
C2. Be aware of this type transition when chaining builder methods.
Because teardown callbacks receive the connection state, this transition
clears any teardown callback registered for the previous C type.
Register teardown after setup when both hooks are needed.
§Errors
This function always succeeds currently but uses Result for
consistency with other builder methods.
Sourcepub fn on_connection_teardown<TeardownFn, Fut>(
self,
f: TeardownFn,
) -> Result<Self>
pub fn on_connection_teardown<TeardownFn, Fut>( self, f: TeardownFn, ) -> Result<Self>
Register a callback invoked when a connection is closed.
The callback receives the connection state produced by
on_connection_setup.
After registration, once setup has produced state, teardown runs exactly once after the connection stops processing. This holds for clean completion, stream-processing errors such as malformed frames or failed sends, and a handler panic caught by the connection runtime. Setup completes before the connection’s framing state is created, and the transport is released before teardown runs, so a callback may wait for the peer to observe closure.
The crate-private runtime also finalizes on a connection-scoped cancellation token observed at a read boundary, but no public entry point currently supplies one.
Teardown is skipped when setup was absent, failed, or never completed,
and when the connection future is dropped or aborted before processing
stops. A panic during setup or teardown is not retried, and builds
using panic = "abort" cannot recover a handler panic. See
ADR-012
for the full contract.
§Errors
This function always succeeds currently but uses Result for
consistency with other builder methods.
Source§impl<S, C, E, F> WireframeApp<S, C, E, F>
impl<S, C, E, F> WireframeApp<S, C, E, F>
Sourcepub fn with_protocol<P>(self, protocol: P) -> Self
pub fn with_protocol<P>(self, protocol: P) -> Self
Install a WireframeProtocol implementation.
The protocol defines hooks for connection setup, frame modification, and
command completion. It is wrapped in an Arc and stored for later use
by the connection actor and the application response pipeline.
A fresh ProtocolHooks value is built for each connection. The
before_send hook runs for every WireframeApp handler response frame
after serialization and codec wrapping, immediately before the frame is
written to the transport. Because handler responses are driven through
the per-connection crate::connection::ConnectionActor, the
on_command_end, stream-end terminator, and error hooks also run on the
application path. Connection setup runs once per connection before the
response actor starts, and the end-of-file hook runs when a connection’s
input ends mid-header or mid-frame. The direct response helpers on
WireframeApp bypass before_send because they write to a
caller-supplied stream.
At present, the protocol must use ProtocolError = (). This keeps the
protocol object safe for dynamic dispatch, maintains a uniform
interface across connections, and avoids leaking application-specific
error types into the builder API.
Sourcepub fn with_message_assembler(
self,
assembler: impl MessageAssembler + 'static,
) -> Self
pub fn with_message_assembler( self, assembler: impl MessageAssembler + 'static, ) -> Self
Install a MessageAssembler implementation.
The assembler parses protocol-specific frame headers for multi-frame
request assembly on the inbound pipeline. Wireframe applies the hook
after any transport fragmentation reassembly and before handler
dispatch, producing one buffered request per completed assembly. The
runtime creates no streaming request body from an assembled message, so
handlers never receive RequestParts plus a body stream from this
hook.
§Examples
use wireframe::{
app::WireframeApp,
message_assembler::{MessageAssembler, ParsedFrameHeader},
};
struct DemoAssembler;
impl MessageAssembler for DemoAssembler {
fn parse_frame_header(&self, _payload: &[u8]) -> Result<ParsedFrameHeader, std::io::Error> {
Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"unimplemented",
))
}
}
let app: WireframeApp = WireframeApp::new()
.expect("builder")
.with_message_assembler(DemoAssembler);
let _ = app;Sourcepub fn protocol(
&self,
) -> Option<Arc<dyn WireframeProtocol<Frame = F::Frame, ProtocolError = ()>>>
pub fn protocol( &self, ) -> Option<Arc<dyn WireframeProtocol<Frame = F::Frame, ProtocolError = ()>>>
Get a clone of the configured protocol, if any.
Returns None if no protocol was installed via with_protocol.
Sourcepub fn protocol_hooks(&self) -> ProtocolHooks<F::Frame, ()>
pub fn protocol_hooks(&self) -> ProtocolHooks<F::Frame, ()>
Return protocol hooks derived from the installed protocol.
If no protocol is installed, returns default (no-op) hooks.
Sourcepub fn message_assembler(&self) -> Option<&dyn MessageAssembler>
pub fn message_assembler(&self) -> Option<&dyn MessageAssembler>
Get the configured message assembler, if any.
§Examples
use wireframe::{
app::WireframeApp,
message_assembler::{MessageAssembler, ParsedFrameHeader},
};
struct DemoAssembler;
impl MessageAssembler for DemoAssembler {
fn parse_frame_header(&self, _payload: &[u8]) -> Result<ParsedFrameHeader, std::io::Error> {
Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"unimplemented",
))
}
}
let app: WireframeApp = WireframeApp::new()
.expect("builder")
.with_message_assembler(DemoAssembler);
assert!(app.message_assembler().is_some());The accessor borrows the application-owned assembler. It deliberately
does not hand out a cloneable handle: the assembler is immutable and
only called through &self, so a caller that needs to invoke it can do
so through the returned reference. This is the
#598 disposition and
replaces the former Option<&Arc<dyn MessageAssembler>> return type in
the 0.4.0 release.
Source§impl<S, C, E, F> WireframeApp<S, C, E, F>
impl<S, C, E, F> WireframeApp<S, C, E, F>
Sourcepub fn with_push_queues(self, push_queues: PushQueuesBuilder<F::Frame>) -> Self
pub fn with_push_queues(self, push_queues: PushQueuesBuilder<F::Frame>) -> Self
Provide the template used to build every connection’s push queues.
The template is cloned once per accepted connection, so each connection gets independent queues, rate limiter state, and dead-letter routing derived from the same configuration. A dead-letter queue configured here receives codec frames, matching ADR 009.
The template is validated when the application is prepared, so an invalid capacity or rate fails before any connection is accepted.
§Examples
use bytes::Bytes;
use tokio::sync::mpsc;
use wireframe::{app::WireframeApp, push::PushQueues};
let (dlq_tx, _dlq_rx) = mpsc::channel(16);
let templates = PushQueues::<Bytes>::builder()
.high_capacity(8)
.low_capacity(8)
.dlq(Some(dlq_tx));
let app = build().with_push_queues(templates);Sourcepub fn with_session_registry(
self,
registry: Arc<SessionRegistry<F::Frame>>,
) -> Self
pub fn with_session_registry( self, registry: Arc<SessionRegistry<F::Frame>>, ) -> Self
Share a session registry across every connection.
Connections register their push handle with this registry on setup and
deregister it on close, so application code holding the same Arc can
address individual connections. Without this call the application
creates its own registry, which Self::session_registry returns, so
call that before handing the application to a server if application
code needs to address its connections.
§Examples
use std::sync::Arc;
use bytes::Bytes;
use wireframe::{app::WireframeApp, session::SessionRegistry};
let registry = Arc::new(SessionRegistry::<Bytes>::new());
let app: WireframeApp = WireframeApp::new()
.expect("builder creation should not fail")
.with_session_registry(Arc::clone(®istry));Sourcepub fn session_registry(&self) -> Arc<SessionRegistry<F::Frame>> ⓘ
pub fn session_registry(&self) -> Arc<SessionRegistry<F::Frame>> ⓘ
Return the registry every connection built from this application uses.
§Examples
use std::sync::Arc;
use bytes::Bytes;
use wireframe::{app::WireframeApp, session::SessionRegistry};
let registry = Arc::new(SessionRegistry::<Bytes>::new());
let app: WireframeApp = WireframeApp::new()
.expect("builder creation should not fail")
.with_session_registry(Arc::clone(®istry));
assert!(Arc::ptr_eq(&app.session_registry(), ®istry));Sourcepub fn with_push_dlq(self, dlq: Sender<Vec<u8>>) -> Self
👎Deprecated since 0.4.0: use with_push_queues(PushQueues::builder().dlq(sender)) so dropped frames arrive as codec frames
pub fn with_push_dlq(self, dlq: Sender<Vec<u8>>) -> Self
use with_push_queues(PushQueues::builder().dlq(sender)) so dropped frames arrive as codec frames
Configure a legacy Dead Letter Queue for dropped push frames.
§Deprecated
This sink receives serialized payloads and is no longer consulted when
building connection queues. Use
with_push_queues with
PushQueues::builder and its
dlq method so dropped frames arrive as codec frames, as required by
ADR 009.
use tokio::sync::mpsc;
use wireframe::app::WireframeApp;
let (tx, _rx) = mpsc::channel(16);
let app = build().with_push_dlq(tx);Source§impl<S, C, E, F> WireframeApp<S, C, E, F>
impl<S, C, E, F> WireframeApp<S, C, E, F>
Sourcepub fn with_recovery_hook<H>(self, hook: H) -> Selfwhere
H: RecoveryPolicyHook + 'static,
pub fn with_recovery_hook<H>(self, hook: H) -> Selfwhere
H: RecoveryPolicyHook + 'static,
Install a RecoveryPolicyHook consulted when a decoder fails.
Without a hook, a decoder failure on a live connection is terminal: the
connection stops reading and the original error reaches the teardown
path unchanged. Installing a hook lets the application choose between
Drop,
Quarantine, and
Disconnect per error.
The hook is shared by every connection built from this application and
is wrapped in an Arc, so all its methods take
&self. Per-connection state belongs in a connection setup hook, not in
the recovery hook.
§Callback order
For each decoder failure the connection loop performs these steps in order:
- Call
recovery_policyto select a policy. - Apply the fallbacks described below, which may replace the selection.
- Call
quarantine_durationwhen the applied policy isQuarantine, and pause for that duration. - Call
on_errorwith the applied policy, immediately before the loop acts on it. - Increment
wireframe_codec_errors_totalonce, labelled with the error type and the applied policy.
§Fallbacks
The connection loop overrides the hook’s selection in three cases, because continuing would either repeat forever or cannot help:
- A failure from
decode_eofalways disconnects: the peer has stopped sending, so no later frame can arrive on this connection. DroporQuarantineselected for a failure that consumed no bytes disconnects: the same malformed prefix would be decoded again.- A
DropbeyondRecoveryConfig::max_consecutive_dropsdisconnects. The counter restarts whenever a frame decodes successfully.
on_error and the metric report the applied policy, so they never claim
a drop or quarantine that was escalated to a disconnect.
§Decoder contract
Recovery only works if the decoder consumes the malformed frame and leaves its framing state valid before returning the error. A decoder that returns an error without consuming any bytes would be offered the same input again, so the connection loop escalates that case to a disconnect.
§Examples
use wireframe::{
app::WireframeApp,
codec::{CodecError, CodecErrorContext, RecoveryPolicy, RecoveryPolicyHook},
};
struct DisconnectOnEveryError;
impl RecoveryPolicyHook for DisconnectOnEveryError {
fn recovery_policy(&self, _error: &CodecError, _ctx: &CodecErrorContext) -> RecoveryPolicy {
RecoveryPolicy::Disconnect
}
}
let app: WireframeApp = WireframeApp::new()
.expect("builder")
.with_recovery_hook(DisconnectOnEveryError);
let _ = app;Sourcepub const fn recovery_config(self, config: RecoveryConfig) -> Self
pub const fn recovery_config(self, config: RecoveryConfig) -> Self
Replace the global recovery settings.
These settings are independent of the installed hook: the drop limit
bounds how many consecutive frames a hook’s Drop may discard, and
RecoveryConfig::log_dropped_frames
controls the log line emitted for an applied drop.
RecoveryConfig::quarantine_duration
is only a fallback. When a hook is installed, its
quarantine_duration method
decides how long a quarantine lasts, because the hook may vary the pause
per error.
§Examples
use std::time::Duration;
use wireframe::{app::WireframeApp, codec::RecoveryConfig};
let app: WireframeApp = WireframeApp::new().expect("builder").recovery_config(
RecoveryConfig::default()
.max_consecutive_drops(3)
.quarantine_duration(Duration::from_millis(250)),
);
let _ = app;Source§impl<S, C, E, F> WireframeApp<S, C, E, F>
impl<S, C, E, F> WireframeApp<S, C, E, F>
Sourcepub fn route(self, id: u32, handler: Handler<E>) -> Result<Self>
pub fn route(self, id: u32, handler: Handler<E>) -> Result<Self>
Register a route that maps id to handler.
§Errors
Returns WireframeError::DuplicateRoute if a handler for id
has already been registered, buffered or streaming.
Sourcepub fn route_response(
self,
id: u32,
handler: ResponseHandler<E>,
) -> Result<Self>
pub fn route_response( self, id: u32, handler: ResponseHandler<E>, ) -> Result<Self>
Register a route whose handler returns the response to stream.
This is the streaming counterpart to route. The
handler receives the decoded request envelope and returns any
Response variant; Single, Vec, and
Empty complete immediately, while Stream and MultiPacket are
driven by the connection actor.
Every emitted frame is stamped with the request’s correlation id and
passes through fragmentation, outbound metrics, serialization, codec
wrapping, and the protocol before_send hook. A streamed response is
driven to completion before the next inbound frame on the connection is
read. Middleware observes an empty response frame for these routes
because the body travels in a deferred slot; see
ServiceResponse.
§Errors
Returns WireframeError::DuplicateRoute if a handler for id has
already been registered.
Sourcepub fn streaming_route(self, id: u32, handler: StreamingHandler) -> Result<Self>
pub fn streaming_route(self, id: u32, handler: StreamingHandler) -> Result<Self>
Register a streaming route that maps id to handler.
A streaming handler receives RequestParts
and a RequestBodyStream instead
of a fully assembled envelope. When the first frame for id completes
the message, the handler still receives a one-chunk stream. Middleware
registered with wrap does not run for streaming routes.
§Errors
Returns WireframeError::DuplicateRoute if a handler for id has
already been registered, buffered or streaming.
Sourcepub fn wrap<M>(self, mw: M) -> Result<Self>where
M: Middleware<E> + 'static,
pub fn wrap<M>(self, mw: M) -> Result<Self>where
M: Middleware<E> + 'static,
Add a middleware component to the processing pipeline.
§Errors
This function currently always succeeds.
Source§impl<S, C, E, F> WireframeApp<S, C, E, F>where
S: Serializer + FrameMetadata<Frame = Envelope> + Send + Sync + 'static,
C: Send + 'static,
E: Packet,
F: FrameCodec,
Envelope: DecodeWith<S> + EncodeWith<S>,
impl<S, C, E, F> WireframeApp<S, C, E, F>where
S: Serializer + FrameMetadata<Frame = Envelope> + Send + Sync + 'static,
C: Send + 'static,
E: Packet,
F: FrameCodec,
Envelope: DecodeWith<S> + EncodeWith<S>,
Sourcepub async fn handle_connection_result<W>(&self, stream: W) -> Result<()>
👎Deprecated since 0.4.0: prepare the app once, then call PreparedApp::handle_connection_result
pub async fn handle_connection_result<W>(&self, stream: W) -> Result<()>
prepare the app once, then call PreparedApp::handle_connection_result
Sourcepub async fn handle_connection<W>(&self, stream: W)
👎Deprecated since 0.4.0: prepare the app once, then call PreparedApp::handle_connection
pub async fn handle_connection<W>(&self, stream: W)
prepare the app once, then call PreparedApp::handle_connection
Handle a connection through the compatibility preparation path.
Source§impl<S, C, E, F> WireframeApp<S, C, E, F>
impl<S, C, E, F> WireframeApp<S, C, E, F>
Sourcepub async fn send_response<W, M>(
&self,
stream: &mut W,
msg: &M,
) -> Result<(), SendError>
pub async fn send_response<W, M>( &self, stream: &mut W, msg: &M, ) -> Result<(), SendError>
Serialize msg and write it to stream using the configured codec.
This helper writes directly to the stream and therefore does not run
the configured crate::hooks::WireframeProtocol hooks, including
before_send.
§Errors
Returns a SendError if serialization or writing fails.
Sourcepub async fn send_response_framed_with_codec<W, M, Cc>(
&self,
framed: &mut Framed<W, Cc>,
msg: &M,
) -> Result<(), SendError>
pub async fn send_response_framed_with_codec<W, M, Cc>( &self, framed: &mut Framed<W, Cc>, msg: &M, ) -> Result<(), SendError>
Serialize msg and send it through an existing framed stream.
This helper bypasses the application response pipeline and does not run
the configured crate::hooks::WireframeProtocol hooks, including
before_send.
§Errors
Returns a SendError if serialization or sending fails.
Source§impl<S, C, E> WireframeApp<S, C, E, LengthDelimitedFrameCodec>
impl<S, C, E> WireframeApp<S, C, E, LengthDelimitedFrameCodec>
Sourcepub fn length_codec(&self) -> LengthDelimitedCodec
pub fn length_codec(&self) -> LengthDelimitedCodec
Construct a length-delimited codec capped by the application’s buffer capacity.
Sourcepub async fn send_response_framed<W, M>(
&self,
framed: &mut Framed<W, LengthDelimitedCodec>,
msg: &M,
) -> Result<(), SendError>
pub async fn send_response_framed<W, M>( &self, framed: &mut Framed<W, LengthDelimitedCodec>, msg: &M, ) -> Result<(), SendError>
Serialize msg and send it through an existing framed stream.
This helper bypasses the application response pipeline and does not run
the configured crate::hooks::WireframeProtocol hooks, including
before_send.
§Errors
Returns a SendError if serialization or sending fails.
Source§impl<S, C, E, F> WireframeApp<S, C, E, F>
impl<S, C, E, F> WireframeApp<S, C, E, F>
Sourcepub async fn prepare(self) -> Result<PreparedApp<S, C, E, F>, PrepareError>
pub async fn prepare(self) -> Result<PreparedApp<S, C, E, F>, PrepareError>
Consume builder registrations and prepare immutable route services.
Middleware transforms run once for each buffered route during this transition; a streaming route is registered with its handler alone and bypasses the middleware chain, because middleware transforms a whole payload and a streaming handler owns its body incrementally. The returned template can then drive multiple connections without rebuilding its route chains.
§Examples
use wireframe::app::{PreparedApp, WireframeApp};
let prepared: PreparedApp = WireframeApp::new()?.prepare().await?;§Errors
Returns PrepareError if a future fallible preparation step fails.
Trait Implementations§
Source§impl<S, C, E, F> Default for WireframeApp<S, C, E, F>
impl<S, C, E, F> Default for WireframeApp<S, C, E, F>
Source§impl<Ser, Ctx, E, Codec> FactoryResult<WireframeApp<Ser, Ctx, E, Codec>> for WireframeApp<Ser, Ctx, E, Codec>
impl<Ser, Ctx, E, Codec> FactoryResult<WireframeApp<Ser, Ctx, E, Codec>> for WireframeApp<Ser, Ctx, E, Codec>
Source§impl<Ser, Ctx, E, Codec, Err> FactoryResult<WireframeApp<Ser, Ctx, E, Codec>> for Result<WireframeApp<Ser, Ctx, E, Codec>, Err>where
Ser: Serializer + Send + Sync,
Ctx: Send + 'static,
E: Packet,
Codec: FrameCodec,
Err: Error + Send + Sync + 'static,
impl<Ser, Ctx, E, Codec, Err> FactoryResult<WireframeApp<Ser, Ctx, E, Codec>> for Result<WireframeApp<Ser, Ctx, E, Codec>, Err>where
Ser: Serializer + Send + Sync,
Ctx: Send + 'static,
E: Packet,
Codec: FrameCodec,
Err: Error + Send + Sync + 'static,
Source§fn into_result(self) -> Result<WireframeApp<Ser, Ctx, E, Codec>, Self::Error>
fn into_result(self) -> Result<WireframeApp<Ser, Ctx, E, Codec>, Self::Error>
Result. Read more