repe 10.1.0

Rust implementation of the REPE RPC protocol (JSON-focused)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
# WebSocket Transport

Enable the `websocket` feature for the native `WebSocketClient`, `WebSocketServer`, and `proxy_connection`. Enable `websocket-wasm` for a browser `WasmClient` on `wasm32-unknown-unknown`.

Each REPE message maps to exactly one WebSocket binary message. WebSocket decoding enforces exact message length within each bounded binary frame.

## Native Client

```rust
use repe::WebSocketClient;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = WebSocketClient::connect("ws://127.0.0.1:8081/repe").await?;
    let pong = client.call_json("/ping", &json!({})).await?;
    assert_eq!(pong["pong"], true);
    Ok(())
}
```

## Receiving Server-Pushed Notifies

`WebSocketClient::subscribe_notifies()` returns a tokio mpsc receiver that yields every inbound `Message` whose `notify` header flag is set. The response loop checks the notify flag *before* the request/response correlation map, so server-pushed notifies never collide with an in-flight request that happens to share the same id. The browser `WasmClient` has the same method; see [From the browser](#from-the-browser).

```rust
use repe::WebSocketClient;
use serde_json::Value;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = WebSocketClient::connect("ws://127.0.0.1:8081/repe").await?;
    let mut notifies = client.subscribe_notifies()?;
    tokio::spawn(async move {
        while let Some(msg) = notifies.recv().await {
            let path = msg.query_str().unwrap_or("");
            let body: Value = msg.json_body().unwrap_or(Value::Null);
            println!("notify {path}: {body}");
        }
    });
    let _ = client.call_json("/start", &serde_json::json!({})).await?;
    Ok(())
}
```

The receiver yields raw `Message` values; decode the body using `Message::json_body::<T>()`, `beve::from_slice(&msg.body)`, or `MessageView::from_slice(&frame_bytes)` as appropriate for the wire `body_format`.

### Subscription rules

- At most one subscriber may be active at a time. If a live subscription already exists, `subscribe_notifies` returns `Err(AlreadySubscribed)` without disturbing the existing receiver. This matters because `WebSocketClient` is `Clone`: the loud-replace contract keeps two holders of the same client from silently stealing each other's subscription. Call `unsubscribe_notifies()` first to take over.
- A stale slot whose receiver was already dropped does not block a new subscription; in that case `subscribe_notifies` silently installs the new sender.
- Notifies that arrive while no subscriber is registered are silently dropped. Logging every drop would avalanche under high-rate notifies (e.g. server-pushed binary chunks).
- The channel closes when the socket closes or errors, so `recv()` yields `None`. A consumer driven only by server pushes never issues a request and so never sees a transport error; end-of-stream is its signal to reconnect. A malformed inbound frame does *not* end the stream on its own — only the connection going away does. Resubscribing on a dead client succeeds, but the receiver it hands back is wired to a socket that is gone; reconnect instead.

### Backpressure

The notify channel is unbounded by design. The transport read loop pushes every inbound notify into the channel without backpressure, so a slow consumer plus a high-rate producer will grow the buffer until the process OOMs. Application-level backpressure (e.g. ACK windows in a chunk protocol; see [streaming.md](streaming.md)) is the right fix; the consumer must drain the receiver promptly.

A bounded variant is not offered: dropping notifies on overflow corrupts chunk streams, and blocking the read loop on overflow stalls the request/response correlation path that shares the same socket.

### From the browser

`WasmClient::subscribe_notifies()` is the same API under the `websocket-wasm` feature, with the same subscription rules (including end-of-stream when the socket drops, which surfaces here as `next()` yielding `None`), the same notify-before-correlation ordering, and the same unbounded-channel hazard.

One difference: it returns a `futures_channel::mpsc::UnboundedReceiver<Message>`, which is a `Stream`, not a tokio receiver. Drain it with `StreamExt::next().await` rather than `recv().await`. tokio does not build for `wasm32-unknown-unknown`, so the browser client uses `futures_channel` throughout. Naming that receiver type or calling `next()` on it means depending on the same crates repe does:

```toml
[dependencies]
repe = { version = "9", features = ["websocket-wasm"] }
futures-channel = "0.3"       # only to name UnboundedReceiver in a struct or signature
futures-util = "0.3"          # StreamExt::next; needs default features, unlike repe's own build of it
wasm-bindgen-futures = "0.4"  # spawn_local
web-sys = { version = "0.3", features = ["console"] }
```

```rust,ignore
use futures_util::StreamExt;
use repe::WasmClient;

let client = WasmClient::connect("ws://127.0.0.1:8081/repe").await?;
let mut notifies = client.subscribe_notifies()?;
wasm_bindgen_futures::spawn_local(async move {
    while let Some(msg) = notifies.next().await {
        let path = msg.query_str().unwrap_or("");
        web_sys::console::log_1(&format!("notify {path}").into());
    }
});
```

## Server-Initiated Notifies

`WebSocketServer` can push REPE notifies to connected clients without an embedder having to rebuild the per-connection transport loop. Attach a `PeerRegistry` (or register raw connect/disconnect hooks) and the server tracks each accepted peer's outbound channel for you.

```rust
use repe::PeerRegistry;
use repe::server::Router;
use repe::websocket_server::WebSocketServer;
use serde_json::json;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let router = Router::new().with_json("/ping", |_| Ok(json!({ "ok": true })));

    let peers = PeerRegistry::new();
    let server = WebSocketServer::new(router).with_peer_registry(peers.clone());

    // Background task fans out a notify to every connected client.
    let publisher = peers.clone();
    tokio::spawn(async move {
        loop {
            tokio::time::sleep(std::time::Duration::from_secs(5)).await;
            let _ = publisher.broadcast_notify_json("/heartbeat", &json!({ "t": 1 }));
        }
    });

    server.serve("0.0.0.0:8081", "/repe").await
}
```

### `PeerRegistry`

`PeerRegistry::new()` builds an empty, cloneable handle. `with_peer_registry` wires accept/close to `insert`/`remove`. Background tasks clone the registry and broadcast.

Per-peer broadcast helpers all encode the body once on the caller's task and clone the encoded bytes into each peer's outbound channel:

- `broadcast_notify_json<P, T: Serialize>(path, body)` — JSON body.
- `broadcast_notify_beve<P, T: Serialize>(path, body)` — BEVE body.
- `broadcast_notify_utf8<P, S: AsRef<str>>(path, text)` — UTF-8 body.
- `broadcast_notify_raw<P>(path, body_format, body_bytes)` — raw bytes with the caller-chosen `BodyFormat` tag.

Each helper returns a `HashMap<PeerId, Result<(), PeerSendError>>` so callers can prune dead peers (`PeerSendError::Disconnected`) or surface backpressure (`PeerSendError::Full`).

### Addressing peers by an embedder key

`PeerId` is the registry's canonical, server-minted key: it is what `with_peer_registry` auto-inserts and what the `broadcast_notify_*` result maps are keyed by. When your own client identity is something else — a UUID/token from the handshake, a domain id — attach it as a secondary **alias** instead of maintaining a parallel `key -> PeerId` map by hand:

- `alias<K: Into<String>>(peer_id, key)` associates an embedder key with an already-inserted peer. Returns `false` if the peer is gone (no dangling alias is created). A peer may carry several aliases; a given key addresses at most one peer (re-aliasing moves it).
- `get_by<Q>(&key)` resolves an alias to its `PeerHandle` for a **targeted push** by your own identity (`peers.get_by("session-abc").map(|h| h.send_notify(...))`). The lookup is generic over the borrowed key form, like `HashMap::get`, so string aliases are queried with a `&str`.
- `key_for(peer_id)` / `aliases_for(peer_id)` map a `PeerId` **back** to your key(s). Use these to read a `broadcast_notify_*` result map by your own identity — e.g. to answer "which of *my* clients hit `PeerSendError::Full`?". `key_for` returns the first alias (the common single-alias case); `aliases_for` returns all of them.

`PeerId` stays canonical, so the auto-insert path is untouched and the whole feature is additive. Aliases are cleaned up automatically: `remove` (which `with_peer_registry` routes disconnect through) drops the peer's primary entry and every alias pointing at it, so a disconnect needs no extra bookkeeping. Aliases are owned `String`s; convert a non-string key with `to_string()`.

When the key rides in the upgrade request itself, derive it at connect time with [`on_peer_connect_with_handshake`](#lifecycle-hooks):

```rust
use repe::{PeerRegistry, NotifyBody, WebSocketServer};

let peers = PeerRegistry::new();
let server = WebSocketServer::new(router)
    .with_peer_registry(peers.clone())
    .on_peer_connect_with_handshake({
        let peers = peers.clone();
        move |peer, hs| {
            // e.g. a bearer token in the Authorization header
            if let Some(token) = hs.header("authorization") {
                peers.alias(peer.peer_id(), token);
            }
        }
    });

// Later, anywhere holding a registry clone — a targeted push by your key:
if let Some(handle) = peers.get_by("Bearer abc123") {
    let _ = handle.send_notify("/nudge", NotifyBody::Json(b"{}".to_vec()));
}
```

### Lifecycle hooks

`with_peer_registry` is sugar over two lower-level hooks:

```rust
let server = WebSocketServer::new(router)
    .on_peer_connect(|peer| { /* metrics: connection opened */ })
    .on_peer_disconnect(|id| { /* metrics: connection closed */ });
```

Both hooks compose: every registered closure fires in registration order, so `with_peer_registry` can coexist with logging or metrics callbacks instead of replacing them.

The connect hook runs synchronously on the accept task **before** the reader/writer tasks start processing traffic. A notify queued via `peer.send_notify(...)` from inside the hook is guaranteed to land on the wire before any response to a client request on that connection.

After the hook returns, the outbound channel is strict FIFO across both notifies and responses on the same connection: a notify pushed by a background broadcaster at time T arrives on the wire in the order it was enqueued relative to any handler response also enqueued at time T. Clients de-multiplex by the `notify` header flag (`WebSocketClient::subscribe_notifies()`); notifies do not "cut the line" past in-flight responses.

The disconnect hook fires from a `Drop` guard, so it runs on every exit path: clean Close frame, transport error, handler panic, or a panic in a *later* connect hook (the guard is built before the connect-hook loop). Exactly once per accepted connection.

`on_peer_connect_with_handshake(|peer, hs|)` is a sibling connect hook that additionally receives a `HandshakeContext` — the upgrade request's `path()`, `query()`, and `header(name)` (case-insensitive). Use it when your client identity rides in the handshake: derive your key from the request and `alias` the just-inserted peer (see [Addressing peers by an embedder key](#addressing-peers-by-an-embedder-key)). These hooks fire **after** the plain `on_peer_connect` hooks — so a `with_peer_registry` insert has already landed and the peer is present for `alias` — and still before any traffic is processed. The context is available wherever the handshake is: the built-in `serve*` loops, and the co-hosting `accept_with_handshake` + `serve_connection_with_handshake` (or `serve_connection_with_cancel_and_handshake`) path. A connection served through plain `serve_connection`, which carries no captured handshake, does not fire these hooks. If your key instead arrives in a request *body*, this hook is unnecessary — the handler already has both the key and the peer via `CallContext::peer`.

`PeerHandle::send_notify` returning `Ok(())` means the message was queued onto the outbound channel, not that it was written to the wire. During concurrent disconnect, a late-arriving send may queue successfully but be dropped when the writer task exits and the bounded receiver is released. This is intrinsic to async shutdown; treat `Ok` as best-effort delivery, not as confirmation.

### Error reporting

By default the server prints transport-level errors to stderr (`eprintln!`). To route them into your own `log` / `tracing` pipeline instead, register an `on_error` hook. It receives a `ConnectionError` — a typed taxonomy of the events that would otherwise hit stderr, plus the off-reader saturation rejection:

```rust
use repe::{ConnectionError, WebSocketServer};

let server = WebSocketServer::new(router).on_error(|err| match err {
    ConnectionError::Handshake(e)      => tracing::warn!(%e, "websocket handshake failed"),
    ConnectionError::Connection(e)     => tracing::info!(%e, "connection ended"),
    ConnectionError::HandlerPanic { method } => tracing::error!(%method, "off-reader handler panicked"),
    ConnectionError::Saturation { method }   => tracing::debug!(%method, "off-reader limit reached"),
});
```

Like the lifecycle hooks, `on_error` composes: every registered callback fires in registration order, on the task that detected the error (an accept task, a connection's reader, or an off-reader blocking thread), so it must not block. Registering at least one callback makes the callbacks the sole sink — the default stderr logging is suppressed. With no callback registered the server keeps its stderr behavior (and stays silent on saturation, which never logged).

`Handshake` and `Connection` errors are reported only by the built-in accept loops (`serve*`); a co-hosting embedder that owns its accept loop gets the connection error as the `RepeError` returned by `serve_connection` and handles it however it likes. `HandlerPanic` and `Saturation` are reported wherever the connection runs. `ConnectionError::error_code()` returns the wire `ErrorCode` that reached the client for the panic (`InternalError`) and saturation (`ResourceExhausted`) categories, and `None` for handshake / connection failures (which sent no REPE response).

### Backpressure on the server outbound channel

Each accepted connection allocates a bounded `tokio::sync::mpsc` channel for outbound messages (responses plus pushed notifies). The default capacity is `DEFAULT_OUTBOUND_CAPACITY` (256). Tune per server with `with_outbound_capacity(n)`.

When the channel is full, `PeerHandle::send_notify` (and thus `broadcast_notify_*`) returns `PeerSendError::Full` for that peer; other peers are unaffected. A slow consumer cannot stall delivery to the broadcast set. The embedder chooses the policy: retry on the next tick, prune the peer, or escalate.

### In-Handler Notifies

Request handlers can also push notifies back to the calling peer mid-request. Register a handler via `Router::with_json_ctx` (or `with_typed_ctx`) and the closure receives a `CallContext` carrying the `PeerHandle`:

```rust
use repe::server::Router;
use repe::websocket_server::WebSocketServer;
use repe::NotifyBody;
use serde_json::json;

let router = Router::new().with_json_ctx("/run", |ctx, _params| {
    if let Some(peer) = ctx.peer() {
        let _ = peer.send_notify(
            "/progress",
            NotifyBody::Json(serde_json::to_vec(&json!({ "stage": "begin" })).unwrap()),
        );
        // ... do work ...
        let _ = peer.send_notify(
            "/progress",
            NotifyBody::Json(serde_json::to_vec(&json!({ "stage": "end" })).unwrap()),
        );
    }
    Ok(json!({ "ok": true }))
});

let server = WebSocketServer::new(router);
```

Registry-backed handlers reach the same `CallContext`: wrap a closure with `repe::registry::WithContext` before registering it. `WebSocketServer` automatically calls `Registry::dispatch_with_ctx` so the registered callable receives the peer.

Middleware does not need to be aware of `CallContext` to forward it. `Next::run(req)` threads whatever the upstream caller attached, so existing middleware composes transparently with new context-aware handlers. Handlers registered via `with_json` / `with_typed` (the legacy non-`_ctx` variants) keep working unchanged; they simply do not receive the context. A cross-cutting middleware that *does* want the calling peer can read it through `next.ctx()` (or the `next.peer()` shortcut); both return `None` on peer-less transports.

Calls dispatched through the TCP transports (`Client`, `AsyncClient`, `Server`, `AsyncServer`) do not carry a peer today; `ctx.peer()` returns `None` for those. Context-aware handlers should treat `None` as the no-push case rather than relying on the peer always being present.

### Compatibility

The push path is strictly opt-in. Existing `WebSocketServer::new(router).serve(addr, path)` callers see no behavior change, no new error variants, and no protocol changes. Notify frames are the same shape they have always been (`Message::builder().notify(true)`).

Adding `handle_with_ctx` to `HandlerErased` is source-compatible because the trait provides a default implementation that delegates to `handle`. Existing implementors of `HandlerErased` (embedder custom handler types) compile unchanged.

## Off-Reader Handler Dispatch (`_blocking`)

By default every handler runs **inline** on the connection's reader task: the reader decodes a frame, runs the handler to completion, then decodes the next frame. That keeps strict per-connection, request-at-a-time ordering, but it means a handler that **blocks or parks** also stalls the reader — no further inbound frames on that connection are decoded until it returns. On a `current_thread` runtime it stalls the whole server.

That is fatal for a [`repe::stream`](streaming.md) producer. The producer parks in `wait_for_credit` until the receiver ACKs, and those ACKs arrive as inbound frames the *same* reader must decode. Drive the producer from an inline handler and the reader is parked inside it, the ACKs are never read, the credit window never reopens, and the transfer deadlocks at the first full window.

The `_blocking` constructors opt a route out of inline dispatch:

```rust
use repe::server::Router;

let router = Router::new()
    .with_json("/status", |_| Ok(serde_json::json!({ "ok": true })))  // inline, as usual
    .with_json_blocking("/download/begin", |_params| { /* may block / park */ Ok(serde_json::json!({})) })
    .with_json_ctx_blocking("/export", |ctx, _params| { /* ctx.peer() + may park */ Ok(serde_json::json!({})) })
    .with_typed_blocking::<Req, Resp, _>("/report", |req| { /* ... */ })
    .with_typed_ctx_blocking::<Req, Resp, _>("/stream", |ctx, req| { /* ... */ });
```

On the WebSocket server an off-reader handler runs on a blocking thread (`tokio::task::spawn_blocking`); the reader keeps decoding inbound frames (ACKs, cancels, resumes) while it runs or parks. The handler's response, if any, flows back through the same writer task on completion. The `_blocking` suffix describes the callee — it runs on the blocking pool and may park, exactly as in `tokio::task::spawn_blocking` — and never means "blocks the reader." The TCP `Server` / `AsyncServer` ignore the off-reader tag and always run inline (they have no peer and no push primitive).

Reach for `_blocking` when a handler **blocks or parks**: a `repe::stream` producer, a synchronous read of a large blob, a blocking database call. Leave fast request/response handlers inline.

### Ordering

Inline handlers keep strict per-connection, request-at-a-time order. Off-reader handlers run **concurrently** with subsequent inline handlers and with each other, so their responses interleave on the wire. Clients correlate responses to requests by the REPE message id (as they already do); do not assume per-connection serialization for off-reader routes. This is the same concurrency you would get by hand-rolling a worker thread, made first-class and opt-in.

### Concurrency cap and saturation

Off-reader dispatch is capped per connection by `with_offreader_limit(n)` (default `DEFAULT_OFFREADER_LIMIT`, 16). A permit is acquired before the handler is spawned and held for its whole life, so the count reflects actually-running handlers and a finished, panicked, or cancelled handler frees its slot on exit.

```rust
use repe::websocket_server::WebSocketServer;

let server = WebSocketServer::new(router).with_offreader_limit(32);  // 0 removes the cap
```

When the cap is reached the reader does **not** block waiting for a slot — that would stall the very ACK/cancel frames in-flight transfers need to finish and free a slot, recreating the deadlock. Instead a further off-reader request gets an immediate error response and the reader keeps reading; the client should retry. A handler **panic** is caught and likewise mapped to an error response, so the connection — which it shares with other concurrent transfers — survives rather than being torn down.

The saturation rejection and the caught panic carry **distinct** wire codes so a client can branch on them: a saturation rejection is `ErrorCode::ResourceExhausted` (retryable — back off and retry) and a caught panic is `ErrorCode::InternalError` (a real failure, not a normal result), both separate from the `ErrorCode::ApplicationErrorBase` an ordinary handler error returns. The two codes occupy the REPE-reserved `8..4095` range, so a client implementing automatic retry keys off the code alone — retry-on-busy, surface-on-error. (Both surfaced as `ApplicationErrorBase` before this distinction landed; a client that matched that code to detect saturation must update.)

`with_offreader_limit` bounds **per-connection fairness, not the global blocking pool.** `spawn_blocking` draws from tokio's process-wide blocking pool (512 threads by default), and a producer parked in `wait_for_credit` holds its thread for the whole transfer. Embedders expecting many concurrent streaming connections should raise the runtime's `max_blocking_threads` or use a dedicated runtime. The idle watchdog (`spawn_watchdog`, see [streaming.md](streaming.md)) reclaims both the blocking-pool thread and the permit from a transfer that goes silent.

### Cancellation on disconnect and shutdown

An off-reader handler can observe that its work has become pointless through its `CallContext`. `ctx.is_cancelled()` (non-blocking) returns `true`, and `ctx.cancelled()` (a future) resolves, once the calling peer disconnects or the server begins a [graceful drain](#draining-in-flight-connections). A long poll-loop or compute handler should check `is_cancelled()` at loop boundaries and return early, freeing its `spawn_blocking` thread and off-reader permit instead of running to completion:

```rust
let router = Router::new().with_json_ctx_blocking("/export", |ctx, _params| {
    for chunk in chunks {
        if ctx.is_cancelled() {
            return Ok(serde_json::json!({ "cancelled": true }));  // peer gone / shutting down
        }
        // ... produce and push the chunk via ctx.peer() ...
    }
    Ok(serde_json::json!({ "done": true }))
});
```

The signal is a never-cancelling no-op on peer-less transports (TCP servers, in-process dispatch), so the same handler is safe to register on a `Router` served over any transport — `is_cancelled()` simply stays `false` and `cancelled()` never resolves there.

**It does not wake a `wait_for_credit` park.** A `repe::stream` producer parked in `wait_for_credit` is blocked on a `Condvar`, not polling `is_cancelled()`, so the cancellation signal cannot reach it. That park is still woken only by `TransferControl::cancel`, which you drive from an `on_peer_disconnect` hook: the hook receives a `PeerId` while a `TransferRegistry` is keyed by your transfer id, so keep your own peer-to-transfer association and call `cancel` for each transfer that belonged to the departing peer. The two paths complement each other — poll-loop and compute handlers use the cancellation signal; credit-parked producers use `cancel`. With neither wired, a parked producer still wakes on the `deadline` passed to `wait_for_credit` (suggested `DEFAULT_BACKPRESSURE_TIMEOUT`, 30 s) or when the idle watchdog fires, so a departed peer's transfer holds its blocking-pool thread and off-reader permit for at most that long — the hold is bounded, not indefinite.

### One producer per transfer

Removing per-connection serialization also removes an implicit safety net. Inline, a second `/begin` for the same transfer id cannot start until the first returns; off-reader, two `begin` frames spawn two producers against one `TransferControl`, violating its single-producer assumption and racing the registry entry (the second `begin` overwrites it while both producers run). The concurrency cap bounds the *count* of off-reader tasks, not duplicate registration, so a `begin`-style handler **must reject (or de-duplicate) a transfer id that is already registered** — check `TransferRegistry::get` before `register` and return an application error if it is already present.

### Deferred: a first-class stream source

The wiring above — install a `TransferControl`, spawn the producer off the reader, and route inbound ack/cancel/resume through your own handlers — is deliberately left to the embedder. A higher-level `WebSocketServer` stream-source surface that owns all of it (you would supply only the byte source and the chunk method names, and `begin`/ack/cancel/resume would be handled internally) is **deferred** until a second distinct windowed-transfer consumer of the built-in server exists, so the trait is designed against more than one transfer shape rather than over-fit to one. Its prerequisites — cancellation-on-disconnect ([above](#cancellation-on-disconnect-and-shutdown)) and orderly drain ([below](#draining-in-flight-connections)) — now exist, so the surface can be designed against this consumer once a second appears. When it is built it should be *pull-based* (the server asks the source for the next chunk only when the credit window has room) and expose a seek so replay/resume can re-emit from an arbitrary offset. Until then, off-reader dispatch plus the [`repe::stream`](streaming.md) API fully cover a single consumer.

## Message Size Limits

WebSocket size limits are enforced by the **reader**. Each endpoint carries its own thresholds, a writer consults none of them, and nothing in the handshake communicates either side's choice. Everything in this section follows from that asymmetry.

### Configuring what an endpoint accepts

`WebSocketLimits` sets the thresholds for a connection. It is a repe-owned type rather than a re-export of the underlying transport's config, so the surface stays the knobs that carry protocol meaning and leaves out buffer-tuning fields the transport panics on if set inconsistently. (The transport type itself does appear in repe's public API — `accept`, `proxy_connection`, and `adopt_upgraded` all name `WebSocketStream` — so a tokio-tungstenite major bump is a repe major bump either way; it is re-exported as `repe::tokio_tungstenite` so you can always name the matching version.)

```rust
use repe::{WebSocketClient, WebSocketLimits, WebSocketServer};
use repe::server::Router;

let limits = WebSocketLimits::default()
    .with_max_incoming_frame_size(Some(64 << 20))
    .with_max_incoming_message_size(Some(64 << 20))
    .with_assumed_peer_frame_limit(Some(64 << 20));

// Server: applies to every connection it upgrades itself.
let server = WebSocketServer::new(Router::new()).with_limits(limits);

// Client: applies to this connection.
// let client = WebSocketClient::connect_with_limits(url, limits).await?;
```

Raising a limit on one side does **not** raise it on the other. `max_incoming_frame_size` governs what *this* endpoint will read, so a larger payload in either direction requires the *receiving* end to be configured for it. Both ends usually want the same value.

Two paths do not pick up a server's limits, because repe never ran their handshake:

- `SharedWebSocketServer::serve_connection` and friends take a stream the embedder already upgraded. The transport fixes inbound limits at construction and exposes no setter, so they cannot be retrofitted; set them on your own upgrade call.
- `WebSocketServer::accept` and `accept_with_handshake` are associated functions and cannot see a builder. Use `accept_with_limits` / `accept_with_handshake_and_limits`.

The outbound guard below is repe's own, so it applies on every path regardless.

### Guarding outbound size

Because limits are read-side and undiscoverable, an oversized message fails in a way that looks like nothing at all: it leaves the sender cleanly, the peer's reader rejects it and closes the connection, and the sender sees a dropped socket with no error. A client that reconnects and re-requests the same payload reproduces it indefinitely.

`assumed_peer_frame_limit` is an assumption you configure, checked before sending:

- an oversized **response** is replaced with an `ErrorCode::InternalError` response carrying the same request id, so the caller gets a real error and the connection stays up;
- an oversized **notify** is dropped, since it has no response to carry a failure;
- both reach the server's `on_error` hooks as `ConnectionError::OutboundTooLarge`;
- on the client, an oversized request fails locally with `RepeError::MessageTooLarge` before it reaches the wire.

It defaults on, at the transport's own 16 MiB default frame size. Set it to the peer's `max_incoming_frame_size` when you know it, or clear it with `.with_assumed_peer_frame_limit(None)` for a peer whose limits are known to be absent.

For a payload with no useful upper bound, prefer [SVS streaming](streaming-serialized-values.md) over raising limits: it chunks the transfer, so frame size stays bounded however large the payload grows, and no assumption about the peer is needed.

## Graceful Shutdown

`serve` and `serve_listener` run until the listener errors or the task is dropped. To stop accepting cleanly without tearing down the runtime, use `serve_with_shutdown` (which binds an address) or `serve_listener_with_shutdown` (which takes an already-bound listener); both `select!` between accepting connections and a shutdown future and return `Ok(())` once it resolves.

```rust
use repe::websocket_server::WebSocketServer;
use tokio::sync::oneshot;

let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
let server = WebSocketServer::new(router);
let handle = tokio::spawn(async move {
    server
        .serve_with_shutdown("0.0.0.0:8081", "/repe", async {
            let _ = shutdown_rx.await;
        })
        .await
});

// ... later, to stop accepting new connections:
let _ = shutdown_tx.send(());
let _ = handle.await;
```

Already-accepted connections are **not** awaited: each runs on its own detached task and continues until its peer disconnects or it errors, and the call returns as soon as the accept loop stops. Track connection lifetimes yourself (e.g. via a [`PeerRegistry`](#peerregistry)) if you need to drain them before exiting.

### Draining in-flight connections

`serve_with_shutdown` returns the instant the accept loop stops, so in-flight work on already-accepted connections is cut off at process exit. When connections carry multi-minute transfers, use the draining entry points instead — `serve_with_graceful_drain(addr, path, shutdown, drain_timeout)` and `serve_listener_with_graceful_drain(listener, path, shutdown, drain_timeout)`. On shutdown they stop accepting, **cancel** every in-flight off-reader handler (so handlers that poll [`ctx.is_cancelled()`](#cancellation-on-disconnect-and-shutdown) wind down promptly), then await the connection tasks for up to `drain_timeout` before aborting whatever remains.

```rust
server
    .serve_listener_with_graceful_drain(
        listener,
        "/repe",
        async { let _ = shutdown_rx.await; },
        Duration::from_secs(10),
    )
    .await?;
```

The server tracks every connection it accepts in a `JoinSet`, so you do not have to. `drain_timeout` is a backstop, not the common wait: cancellation winds cooperative handlers down in milliseconds, and the timeout only bounds connections whose handlers ignore cancellation or whose peers are slow to flush. Aborting a connection at the deadline tears down its writer task too, so the server-level `drain_timeout` supersedes the per-connection 5 s writer drain. A `_blocking` handler that never polls `is_cancelled()` still holds its `spawn_blocking` thread past the deadline (a blocking thread cannot be aborted) — the abort reclaims the connection's reader/writer, not such a handler, which is one more reason to poll the signal.

`examples/websocket_graceful_server.rs` is a runnable end-to-end demo of this section: a cancellation-polling off-reader handler, an `on_error` hook, and `serve_listener_with_graceful_drain` winding a connection down on shutdown. Run it with `cargo run --example websocket_graceful_server --features websocket`.

## One-Port Co-Hosting

To share a single TCP port between the REPE WebSocket endpoint and your own HTTP routes, drive connections yourself instead of using the built-in accept loop. `WebSocketServer::into_shared()` consumes the builder into a cheap, cloneable `SharedWebSocketServer` — the per-connection configuration is built once, each clone is an `Arc` clone, and the handle is `Send + Sync + 'static`. Then, for each accepted stream, classify it and route it: `is_websocket_upgrade(&stream)` reports whether the client is opening a WebSocket upgrade, `WebSocketServer::accept(stream, path)` performs the REPE handshake (validating `path`), and `SharedWebSocketServer::serve_connection(ws)` runs that connection's reader/writer loop. Connect/disconnect hooks and any attached `PeerRegistry` fire exactly as under `serve`.

```rust
use repe::{is_websocket_upgrade, WebSocketServer};

let shared = WebSocketServer::new(router).into_shared();
let listener = tokio::net::TcpListener::bind("0.0.0.0:8081").await?;
loop {
    let (stream, _addr) = listener.accept().await?;
    let shared = shared.clone();
    tokio::spawn(async move {
        match is_websocket_upgrade(&stream).await {
            Ok(true) => {
                if let Ok(ws) = WebSocketServer::accept(stream, "/repe").await {
                    let _ = shared.serve_connection(ws).await;
                }
            }
            Ok(false) => { let _ = serve_http(stream).await; }  // your own HTTP handler
            Err(err) => eprintln!("peek failed: {err}"),
        }
    });
}
```

`is_websocket_upgrade` is **non-destructive**: it peeks (`TcpStream::peek`) and leaves the request bytes in the socket buffer, because `WebSocketServer::accept` replays the handshake from the start of the stream. It is a sniff — it looks for an `Upgrade: websocket` header — and `accept` still does the authoritative RFC 6455 validation on the `true` branch, so a false positive fails the handshake rather than corrupting anything. A helper that *parsed* the request would consume the bytes and break `accept`; the peek-and-sniff keeps repe out of the business of serving HTTP while removing the trickiest part of the fork.

`examples/websocket_cohosting.rs` is a runnable end-to-end demo: it fills in both pieces the sketch above leaves open — the `is_websocket_upgrade` classifier and a minimal, dependency-free `serve_http` (a `/healthz` probe plus a small JSON `GET`) — and drives both forks against one port. Run it with `cargo run --example websocket_cohosting --features websocket`.

The built-in `serve` / `serve_listener` loop is itself implemented on top of `into_shared` + `accept` + `serve_connection`, so a co-hosted connection behaves identically to one accepted by the built-in loop.

### Adopting a connection your HTTP framework upgraded

The peek-then-fork recipe above requires repe to own the `TcpStream` before any HTTP is parsed. That is the wrong shape for an embedder whose routes already live in an HTTP framework — an `axum` `Router` with a `/healthz` probe and a handful of `/api/*` routes, wanting the REPE endpoint to be one more route on it. There, the framework owns the socket and answers the `101` itself; repe never sees a `TcpStream`.

For that shape, hand repe the byte stream the framework upgraded. `SharedWebSocketServer::adopt_upgraded(io)` wraps it into a server-role `WebSocketStream` carrying this server's configured `WebSocketLimits`, and `serve_connection` takes it from there — the serving path is generic over the underlying stream, so it does not have to be a socket this crate accepted.

Note this does *not* go through `axum::extract::ws::WebSocketUpgrade`. That extractor hands back axum's own `WebSocket`, a wrapper around its own tungstenite version with only `send`/`recv` on it — not a byte stream anything else can adopt. Taking `hyper::upgrade::OnUpgrade` out of the request directly is what yields the raw upgraded IO, and it keeps axum's tungstenite out of the dependency graph entirely.

```rust
use axum::body::Body;
use axum::extract::{Request, State};
use axum::http::header::{SEC_WEBSOCKET_ACCEPT, SEC_WEBSOCKET_KEY, SEC_WEBSOCKET_VERSION};
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use hyper::upgrade::OnUpgrade;
use hyper_util::rt::TokioIo;
use repe::{HandshakeContext, ShutdownToken, SharedWebSocketServer, WebSocketServer, derive_accept_key};

#[derive(Clone)]
struct AppState {
    repe: SharedWebSocketServer,
    shutdown: ShutdownToken,
}

async fn repe_upgrade(State(state): State<AppState>, mut req: Request) -> Response {
    // RFC 6455 requires all three. The framework routed the path here, but it
    // did not check that this is really a WebSocket upgrade.
    if req.headers().get(SEC_WEBSOCKET_VERSION).map(|v| v.as_bytes()) != Some(b"13") {
        return (StatusCode::BAD_REQUEST, "unsupported Sec-WebSocket-Version").into_response();
    }
    let Some(key) = req.headers().get(SEC_WEBSOCKET_KEY).cloned() else {
        return (StatusCode::BAD_REQUEST, "missing Sec-WebSocket-Key").into_response();
    };
    let Some(on_upgrade) = req.extensions_mut().remove::<OnUpgrade>() else {
        return (StatusCode::BAD_REQUEST, "not an upgrade request").into_response();
    };

    // Capture before answering: the peer is keyed off the upgrade request, and
    // after this handler returns the request is gone.
    let handshake = HandshakeContext::from_http_request(&req);

    tokio::spawn(async move {
        let upgraded = match on_upgrade.await {
            Ok(upgraded) => upgraded,
            Err(err) => return tracing::warn!(%err, "upgrade failed"),
        };
        let ws = state.repe.adopt_upgraded(TokioIo::new(upgraded)).await;
        // Errors surface here rather than through `on_error` — this is an
        // embedder-driven path, so the connection result is yours to handle.
        if let Err(err) = state
            .repe
            .serve_connection_with_cancel_and_handshake(ws, handshake, &state.shutdown)
            .await
        {
            tracing::warn!(%err, "repe connection ended");
        }
    });

    Response::builder()
        .status(StatusCode::SWITCHING_PROTOCOLS)
        .header(header::UPGRADE, "websocket")
        .header(header::CONNECTION, "Upgrade")
        .header(SEC_WEBSOCKET_ACCEPT, derive_accept_key(key.as_bytes()))
        .body(Body::empty())
        .expect("valid 101 response")
}

let state = AppState {
    repe: WebSocketServer::new(router).into_shared(),
    shutdown: ShutdownToken::new(),
};
let app = axum::Router::new()
    .route("/healthz", get(|| async { "ok" }))
    .route("/repe", get(repe_upgrade))
    .with_state(state);
axum::serve(listener, app).await?;
```

Everything a connection gets under `serve` it also gets here: connect/disconnect hooks, an attached `PeerRegistry`, `CallContext::peer`, off-reader dispatch, pushed notifies, and — via the captured `HandshakeContext` — `on_peer_connect_with_handshake`, so peers can be `alias`ed by an identity carried in the upgrade request just as they are under `serve`.

Three things are the caller's responsibility, because they happen before repe is involved:

- **The handshake.** Validate the request and answer `101` with the `derive_accept_key` of the client's `Sec-WebSocket-Key`. `adopt_upgraded` reads nothing before the first REPE frame, so a botched handshake that produces garbage surfaces as a protocol error on that connection alone. The quieter shape is a client still waiting for a `101` that never came: neither side speaks, and repe applies no read timeout or idle deadline, so the framework's own upgrade timeout is what bounds it.
- **Path routing.** `adopt_upgraded` does no path validation, since the framework already routed the request to this handler. This is the counterpart to the `path` argument that `WebSocketServer::accept` takes.
- **Draining.** The connection runs on a task the embedder spawned, and `axum::serve`'s graceful shutdown does not wait for upgraded connections. Serving through `serve_connection_with_cancel*` and a shared `ShutdownToken`, as above, is what gives you the cancellation half; see [below](#draining-a-co-hosted-server) for the rest.

`adopt_upgraded` is where the connection's inbound thresholds are fixed — they cannot be changed afterwards — which is why it exists rather than leaving you to call `tokio_tungstenite`'s `from_raw_socket`, whose defaults would silently replace the limits the server was built with. If your framework hands back the bytes it read past the request separately, as `(io, buffered)`, use `adopt_upgraded_partially_read(io, buffered)` instead: a client may legally pipeline its first frame with the upgrade request, and dropping those bytes loses a frame. (`hyper` replays them itself, so the plain call is right there.)

### Draining a co-hosted server

Because a co-hosting embedder owns its accept loop, it cannot hand its listener to `serve_listener_with_graceful_drain`. To get the cancellation half on its own terms, create one `ShutdownToken`, serve each connection with `serve_connection_with_cancel(ws, &token)` instead of `serve_connection(ws)`, and `token.cancel()` on shutdown — every connection's in-flight off-reader handlers then observe [`ctx.is_cancelled()`](#cancellation-on-disconnect-and-shutdown) at once. Track the futures in your own `JoinSet` (as you already do for one-port hosting) and drain it with whatever deadline you choose.

```rust
use repe::{ShutdownToken, WebSocketServer};

let shared = WebSocketServer::new(router).into_shared();
let shutdown = ShutdownToken::new();
// ... in your accept loop, for each REPE upgrade:
let (shared, shutdown) = (shared.clone(), shutdown.clone());
conns.spawn(async move {
    if let Ok(ws) = WebSocketServer::accept(stream, "/repe").await {
        let _ = shared.serve_connection_with_cancel(ws, &shutdown).await;
    }
});
// ... on shutdown:
shutdown.cancel();           // wake every connection's in-flight handlers
// then drain your own JoinSet with a deadline, aborting stragglers.
```

Plain `serve_connection(ws)` still fires each connection's cancellation signal on **disconnect**; `serve_connection_with_cancel` additionally ties it to the shared token, so cancelling the token triggers all connections at once. The `ShutdownToken` hides its backing `tokio_util` cancellation type, so you are not coupled to that crate's version.