# Server configuration
`WireframeServer` provides a builder API for adjusting runtime behaviour. The
server employs a typestate (from `Unbound` to `Bound`) to ensure that binding
occurs before runtime: unbound servers do not expose `run` methods. This guide
focuses on tuning the exponential backoff used when accepting connections fails.
```rust,no_run
use wireframe::{
app::WireframeApp,
serializer::BincodeSerializer,
server::WireframeServer,
};
# #[tokio::main]
# async fn main() -> Result<(), wireframe::server::ServerError> {
server.run().await?;
# Ok(())
# }
```
## Binding flow
The sequence below details how a server binds to an address, prepares its
application, installs its accept loops, and signals readiness once those
workers exist. Readiness does not mean the listener has accepted a connection.
```mermaid
sequenceDiagram
autonumber
actor Caller
participant WS as WireframeServer<F,T,Unbound>
participant OS as StdTcpListener
participant Helper as bind_to_listener
participant Tokio as TcpListener::from_std
participant WSB as WireframeServer<F,T,Bound>
participant Factory as AppFactory
participant Prepared as Arc<PreparedApp>
participant Workers as Accept loops
participant Ready as oneshot::Sender<()>
participant Hooks as Preamble handlers
Caller->>WS: bind(addr)
WS->>OS: create StdTcpListener
WS->>Helper: bind_to_listener(OS)
Helper->>OS: set_nonblocking(true)
Helper->>Tokio: from_std(OS)
Helper->>Hooks: register preamble success/failure
Helper->>Ready: store readiness sender
Helper-->>WSB: return Bound server
WSB-->>Caller: Bound instance
Caller->>WSB: run_with_shutdown()
WSB->>Factory: build() once
Factory-->>WSB: WireframeApp
WSB->>Prepared: prepare().await
Prepared-->>WSB: immutable prepared root
WSB->>Workers: spawn with shared root
WSB->>Ready: send readiness
Workers->>Hooks: process preamble events
note over Prepared,Workers: Accept loops are spawned after preparation, then readiness is signalled
```
_Figure 1: Server binding, application preparation, worker startup, and
readiness signalling._
The server evaluates `WireframeServer::new`'s factory once per
`run_with_shutdown` invocation, prepares the resulting application once, and
shares one immutable prepared root between accept loops and connection tasks.
`WireframeServer::from_app(app)` follows the same preparation path for an
already-built application. Readiness is signalled only after that preparation
succeeds and all worker tasks have been installed. Put connection-specific
state in lifecycle setup state `C` through `on_connection_setup`, rather than
rebuilding the application graph for each connection.
## Accept loop backoff
The accept loop retries failed `accept()` calls using exponential backoff.
`accept_backoff(cfg)` sets both bounds using a `BackoffConfig` value. The
builder normalizes the supplied configuration via `BackoffConfig::normalized`,
so out-of-range values are adjusted rather than preserved:
- `initial_delay` – starting delay for the first retry, clamped to at least 1
millisecond.
- `max_delay` – maximum delay for retries, never less than `initial_delay`.
### Behaviour
- If `initial_delay` exceeds `max_delay`, the values are swapped.
- `max_delay` is raised to match `initial_delay` when required.
### Example
```rust
use std::time::Duration;
use wireframe::{
app::WireframeApp,
serializer::BincodeSerializer,
server::{BackoffConfig, WireframeServer},
};
let cfg = BackoffConfig {
initial_delay: Duration::from_millis(5),
max_delay: Duration::from_millis(500),
};
```
## Preamble handling
Servers that expect a preamble can bound how long they wait for it and decide
what to do when decoding fails. Every server starts with a 10-second deadline,
exposed as `wireframe::server::DEFAULT_PREAMBLE_TIMEOUT`, which wraps
`read_preamble` in a timeout. `preamble_timeout(Duration)` replaces that
deadline; values below 1 ms are clamped to 1 ms, so `Duration::ZERO` still
leaves a usable bound. The last configuration call wins.
`disable_preamble_timeout()` removes the deadline entirely. Use it only when a
peer legitimately needs unbounded waiting, because a peer that never sends a
preamble otherwise keeps its connection task alive indefinitely. It does not
delay a server stop: the handshake read is raced against the stop token, which
releases the socket and the connection task.
The opt-out does not by itself make the server speak first. A non-empty
preamble is read before the server writes anything, so a server-first protocol
whose preamble is non-empty still needs its greeting from an outer layer that
runs before the preamble read. A preamble that encodes to no bytes, such as a
unit `()`, is decoded from an empty buffer without reading from the peer, so
the default deadline is never reached and the connection proceeds straight to
application handling. Only a non-empty preamble makes the server wait for the
client.
The deadline covers only the preamble read: the success and failure callbacks
and application message handling run outside it.
When decoding fails or times out, an optional failure handler runs before the
connection is closed. The handler is asynchronous and receives both the error
and the mutable `TcpStream`, allowing a response to be written back to the
client.
After a successful decode, an optional success handler runs before the
connection reaches the application. The handler is awaited, so it can complete
a handshake or reject the peer. A success handler that returns an error fails
closed: the error is logged and the connection is closed without invoking
`WireframeApp`, which lets the handler enforce pre-application access controls.
Submit any rejection response before returning the error.
```rust,no_run
use std::time::Duration;
use futures::FutureExt;
use tokio::io::AsyncWriteExt;
use wireframe::{
app::WireframeApp,
serializer::BincodeSerializer,
server::WireframeServer,
};
.on_preamble_decode_failure(|_err, stream| {
async move {
stream.write_all(b"preamble required").await?;
Ok(())
}
.boxed()
});
```