repe-rs
Rust implementation of the REPE RPC protocol with JSON and BEVE body support.
- Spec reference: https://github.com/repe-org/REPE
- Crate: repe on crates.io
This crate provides:
- REPE header and message types with correct little-endian encoding
- Message encode/decode to/from bytes and I/O helpers for streams
- JSON body helpers using
serde/serde_json - BEVE binary body helpers via the
bevecrate - Dynamic registry routing with JSON Pointer semantics
- Error codes and formats aligned with the spec
- Optional native WebSocket transport (
websocketfeature) - Optional browser WebSocket transport for wasm (
websocket-wasmfeature)
Installation
Add to your Cargo.toml:
[dependencies]
repe = "1.1"
Tip: run
cargo add repeto automatically pull the latest compatible release.
Quick start
use ;
// Build a JSON message
let msg = builder
.id
.query_str
.query_format
.body_json?
.build;
// Serialize to bytes and back
let bytes = msg.to_vec;
let parsed = from_slice?;
assert_eq!;
assert_eq!;
let val: Value = parsed.json_body?;
assert_eq!;
use ;
// Build a BEVE message
let msg = builder
.id
.query_str
.query_format
.body_beve?
.build;
let bytes = msg.to_vec;
let parsed = from_slice?;
assert_eq!;
let val: Value = parsed.beve_body?;
assert_eq!;
Streaming and zero-copy I/O
For large bodies (e.g. multi-MiB binary chunks), Message::to_vec /
Message::from_slice add a full-body memcpy you may not want. The streaming
APIs below let the body flow directly between the wire and a user-supplied
encoder/decoder.
use ;
use Write;
// Send: BEVE-encode a body straight into the writer with no intermediate Vec.
let mut header = new;
header.id = 99;
header.query_format = JsonPointer as u16;
header.body_format = Beve as u16;
let body_len = beve_chunk_size; // computed up front
write_message_streaming?;
use MessageView;
// Receive: borrow into the WS frame buffer instead of copying out of it.
let view = from_slice?;
let path = view.query_str?;
// view.body is &[u8] pointing inside frame_bytes; pair with serde_bytes::Bytes<'a>
// on a Deserialize struct to keep the chunk payload borrowed end-to-end.
Message::write_to and Message::serialized_len are the owned-Message
counterparts: emit a Message to a Write without going through to_vec,
or query its wire size in O(1).
Peer-aware handlers
When a handler needs to push more than one message back to the calling
client (e.g. server-pushed file chunks after a single /run_collection
call), it needs a typed handle to that specific connection. PeerSink /
PeerHandle / CallContext provide that handle; Registry::dispatch_with_ctx
threads it through to handlers.
Repe-rs's built-in TCP/WebSocket servers do not yet construct PeerHandles
themselves. Embedders that want peer routing wire their own PeerSink
(typically a bounded channel drained by a writer task) against their
server's outbound side.
use ;
use ;
use Arc;
// Implement PeerSink against your server's outbound mechanism.
;
// Register a context-aware handler. WithContext is the marker that opts
// into the &CallContext parameter; plain Fn(Option<Value>) -> Result<...>
// closures keep working unchanged.
let registry = new;
registry.register_function.unwrap;
// At dispatch time, build a CallContext for the calling peer and invoke
// dispatch_with_ctx. Plain dispatch() supplies CallContext::detached.
let peer = new;
let ctx = new;
let _ = registry.dispatch_with_ctx;
Examples
examples/json_roundtrip.rs– construct/serialize/parse a JSON message.examples/server.rs– run a JSON-pointer server (TCP).examples/client.rs– call the server routes.examples/registry_server.rs– serve a dynamic registry under a path prefix.examples/registry_roundtrip.rs– local registry READ/WRITE/CALL roundtrip.examples/async_server.rs– tokio-based async server.examples/async_client.rs– tokio-based async client.
Notes
- BEVE helpers encode/decode via serde, so your existing request/response types continue to work.
- The header
reservedfield is validated and must be zero. - The header length is validated to be
48 + query_length + body_length.
Feature flags
websocket- nativeWebSocketClient,WebSocketServer, andproxy_connectionwebsocket-wasm- browserWasmClientonwasm32-unknown-unknownfleet-udp- UDP fanout support viaUniUdpFleetparking-lot-Lockablesupport forparking_lot::Mutex/RwLock
WebSocket transport
- Each REPE message maps to exactly one WebSocket binary message.
- WebSocket decoding enforces exact message length within each bounded binary frame.
use WebSocketClient;
use json;
async
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.
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, and 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 like server-pushed binary chunks).
The channel is unbounded. The transport read loop pushes every inbound notify into the channel without backpressure, so a slow or stalled 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) is the right fix; the consumer must drain the receiver promptly. The API deliberately does not offer a bounded variant: 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.
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.
use WebSocketClient;
use Value;
async
JSON Pointer Routing and Typed Handlers
-
Router keys are JSON Pointer paths (e.g.,
/ping,/echo,/status). Raw-binary queries are rejected with an explicitInvalid queryerror. -
Add JSON Value handlers with
.with("/path", |v: serde_json::Value| -> Result<Value, (ErrorCode,String)>). -
Add typed handlers with
.with_typed("/path", |req: T| -> Result<R, (ErrorCode,String)>)whereT: Deserialize,R: Serialize.- Typed handlers auto-deserialize JSON, UTF-8, or BEVE bodies into
T. Responses default to JSON. - Wrap the return value with
TypedResponse::beve(...)/TypedResponse::utf8(...)/ etc. to pick a different response [BodyFormat]. - If a body arrives with an unsupported format for typed handlers, the server returns
Invalid body.
- Typed handlers auto-deserialize JSON, UTF-8, or BEVE bodies into
-
Attach pre-request middleware with
.with_middleware(|req, next| { /* auth/logging */ next.run(req) })to centralize auth, validation, or tracing without hand-wrapping handlers. -
Implement the pluggable trait
JsonTypedHandlerto attach methods from a service type:
use ;
use ;
;
let router = new.with_handler;
Async (tokio)
- Use
AsyncServerandAsyncClientfor asynchronous operation with tokio. - See
examples/async_server.rsandexamples/async_client.rs.
Fleet (Multi-Node Control)
- Use
Fleet/AsyncFleetto manage multiple TCP REPE servers as one logical unit. - Use
UniUdpFleetfor fire-and-forget UDP fanout (enable with--features fleet-udp). - TCP retry policy retries transport/I/O failures only; application-level server errors are returned without retry.
- See docs/fleet.md for complete API details.
use ;
use json;
use Duration;
use ;
use json;
use Duration;
async
use ;
use json;
Server
- Build a router and serve TCP:
use ;
use json;
use Duration;
let router = new
.with_middleware
.with
.with
.with;
let server = new
.read_timeout
.write_timeout;
let listener = server.listen?;
server.serve?;
- Register a struct and expose its fields/methods through JSON pointer paths:
use Router;
use ;
use json;
let mut router = new;
let device_handle = router.register_struct;
// Update initial state before serving.
// Example calls (JSON Pointer paths):
// - `/device/greet` -> "device sensor-42 reporting online"
// - `/device/status` with body "offline" writes the field and returns null
// - `/device/metrics/temperature` reads the nested value (21.5)
// - `/device/reset_metrics` zeroes out the metrics
Router handles `` for any lock implementing `Lockable`, so you can swap in
`Mutex`/`RwLock` or enable the optional
`parking-lot` feature to use `Mutex`/`RwLock` without extra wrapper types.
Registry (Dynamic Routing)
- Mount a
Registryon any path prefix withRouter::with_registry("/api/v1", registry). - Registry request semantics:
- Empty body => READ value.
- Non-empty body + function target => CALL function.
- Non-empty body + non-function target => WRITE value.
- See docs/registry.md for full behavior, format decoding details, and client examples.
use ;
use ;
use Arc;
let registry = new;
registry.register_value?;
registry.register_function?;
let router = new.with_registry;
let server = new;
let listener = server.listen?;
server.serve?;
Client
- Connect and call JSON-pointer routes with JSON bodies:
use Client;
use ;
use json;
let client = connect?;
let pong = client.call_json?;
assert_eq!;
let typed: AddResp = client.call_typed_json?;
assert_eq!;
client.notify_typed_json?;
client.notify_typed_beve?;
Typed helpers work for BEVE payloads too:
let beve_sum: AddResp = client.call_typed_beve?;
assert_eq!;
Registry-oriented client helpers:
- Empty-body READs:
registry_read("/api/v1/counter")orcall_message(...) - Typed READs:
registry_read_typed::<_, MyType>(...) - JSON WRITE/CALL helpers:
registry_write_json(...)andregistry_call_json(...) - Custom wire formats:
call_with_formats(...)andnotify_with_formats(...)
Multiplexed calls, timeouts, and batching
ClientandAsyncClientcan run multiple in-flight requests on one connection.- Clone the client handle and issue calls concurrently; responses are matched by request
ideven if the server replies out of order. - Use per-call timeout helpers:
call_json_with_timeoutcall_typed_json_with_timeoutcall_typed_beve_with_timeout
- Use batch helpers for JSON calls:
batch_json(Vec<(String, Value)>)batch_json_with_timeout(Vec<(String, Value)>, Duration)
Notify semantics
- If a request is marked
notify = true, the server will process the handler but will not send a response. - In the protocol, the
idstill increments client-side, but no matching response should be expected. - The
Client::notify_jsonandAsyncClient::notify_jsonhelpers set the flag accordingly. Client::notify_typed_json/Client::notify_typed_beveand their async counterparts send typed payloads without waiting for a response, mirroring the call helpers.
Error handling
- Errors are returned “in-band” as responses with
ec != Okand a UTF‑8 body describing the error. - Common mappings:
- Header parse/validation issues →
InvalidHeaderorParseError. - JSON deserialization/serialization issues →
ParseError. - Missing routes →
MethodNotFoundwith the requested path in the message. - Application failures from handlers → return
(ErrorCode, String)to control both fields.
- Header parse/validation issues →
- Clients surface mismatched protocol versions as
RepeError::VersionMismatch. - Responses with unknown request IDs are logged and dropped by default (including late responses for timed-out requests).
- For bounded latency, prefer
call_*_with_timeoutAPIs so a dropped response ID cannot leave a call waiting indefinitely.
Async usage (minimal end‑to‑end)
use ;
use ;
use json;
#
# async
Running the examples
cargo run --example server
cargo run --example client
cargo run --example registry_server
cargo run --example registry_roundtrip
cargo run --example async_server
cargo run --example async_client
Design overview
- Fixed header size is
48bytes (HEADER_SIZE) followed byqueryandbodypayloads. - All numeric fields are little‑endian. Header
lengthequals48 + query_length + body_lengthand is validated. query_format/body_formatuse the enums inrepe::constants.- Suggested query format is JSON Pointer (
/path/to/resource).
JSON Pointer helpers
parse_json_pointersplits a pointer into unescaped tokens.eval_json_pointerindexes into aserde_json::Valueusing array indices or object keys.
Testing
- Run
cargo testto execute unit and integration tests. The crate denies warnings and includes async tests; you’ll need a recent tokio. - Example integration tests cover sync/async server + client calls, unknown routes, handler error mapping, ID mismatches, and timeouts.
License
- MIT, see
LICENSE.