This page is the crate's own documentation and code, read when the site builds. The frames come from the encoder in protocol/wire.rs, laid over the golden vectors that the crate's tests check, so each byte is a byte the code writes.
Typed request/reply RPC between dynamically allocated endpoints. The
crate is written once against the moonpool provider traits, so the same
code runs over real TCP (TokioProviders) and under deterministic
simulation (SimProviders). It is inspired by FoundationDB’s fdbrpc,
without its wire format, global state or Flow runtime.
server runtime client runtime
┌─────────────────────────────┐ TCP frames ┌────────────────────────┐
│ RpcDriver (owned, polled) │◄────────────────►│ RpcDriver │
│ registry: token → inbox │ │ pending: call → reply │
│ RequestStream<M> ◄─ admit │ │ ServiceClient<P, M> │
│ IncomingRequest ─ reply ─►│ │ try_get_reply(req) │
└─────────────────────────────┘ └────────────────────────┘
ServiceRef<M> / InterfaceRef<I> ── protobuf data, handed out by the app ──►The modules
| module | what it holds |
|---|---|
codec | Payload codecs: how request and reply bodies become bytes. |
configinternal | Transport limits and settings. |
endpointinternal | Endpoint identity: transport incarnations, checked tokens, addresses and access classes. |
errorinternal | Call outcomes: the failure reason, kept separate from what it proves about execution. |
failureinternal | The failure monitor: what one runtime currently believes about the addresses and endpoints it talks to, and race-free ways to wait for that belief to change. |
interface | Interfaces as data: serialisable references, endpoint groups and their checked method adjustment. |
observability | Metrics and diagnostics: the runtime's counters and gauges as a MetricsSource, with a fixed, bounded label set. |
protocol | Wire protocol: framing, the envelope and method/schema identity. |
security | Who may call what: request verification, endpoint access policy, the UTC validation clock and, behind feature tls, the TLS adapter. |
statsinternal | Observable counters and lifetime probes. |
stream | Reply streams: one request, then an ordered stream of typed replies paced by the consumer's consumption (FoundationDB's getReplyStream, ReplyPromiseStream and AcknowledgementReceiver). |
callinternal | The typed calling and serving surface: references, clients, receivers and reply handles. |
transportinternal | The runtime: owned driver, weak handles, registry, peers, pending calls and the failure monitor. |
| Feature | Default | What it adds |
|---|---|---|
prost |
on | Protobuf bodies: every prost::Message + Default type is Wire |
derive |
off | #[moonpool_rpc::service]: interfaces, dispatchers and clients from a trait (moonpool-rpc-derive) |
tls |
off | Server-authenticated TLS 1.3 sessions (security::tls, rustls with ring); native only |
The frame envelope is hand-written and codec-independent. With
--no-default-features the transport still works, applications
implement Wire themselves, and the crate builds for
wasm32-unknown-unknown. The security policy core in security is
always compiled.
RpcDriver owns everything: the listener, every connection’s I/O, the
endpoint registry, the peers and the pending calls (through the one
strong reference to the shared state). RpcHandle,
ServiceClient, RequestStream,
FailureMonitor and reply handles only hold
weak references. Driving is the caller’s job: poll RpcDriver::run
alongside the application (inside the process body in a simulation, so
a crash that aborts the process drops the whole tree). No task is
spawned: the accept loop and each connection are child futures the
driver polls, so dropping the driver cancels them before their next
poll, closes every socket, ends every
RequestStream, completes every pending call
with ErrorReason::Shutdown and releases
every failure-monitor waiter.
The wire
Wire protocol: framing, the envelope and method/schema identity.
Three layers, each validated before the next is looked at:
- Frame (
frame):u32 LE length | u64 LE XXH3-64(length bytes ‖ payload) | payload. The length is bounded byRpcConfig::max_frame_bytesbefore the payload is buffered; the checksum is verified before the payload is parsed. - Envelope (
wire): a hand-written, fixed-width, little-endian layout owned by this crate and versioned byPROTOCOL_VERSION. It carries everything the transport needs to route, bound and reject a message — kind, reply route (call_id), transport incarnation, endpoint token,MethodId,SchemaVersionandCodecId— and never depends on a payload codec. - Body: opaque bytes produced by a
Wireimplementation, decoded only after the endpoint’s method, schema and codec all matched (codec).
Connection rules: the first frame each way is WireMessage::Hello
carrying PROTOCOL_MAGIC, the sender’s supported version range
(its RpcConfig::protocol_versions,
within MIN_PROTOCOL_VERSION..=PROTOCOL_VERSION), its
Incarnation, reserved feature bits, its frame
limit and its canonical listening address. A peer
with no common version, anything but a Hello first, a wrong magic, a
checksum mismatch or an unparsable envelope is a protocol violation: the
connection is closed (never resynchronised), its calls fail through the
ordinary disconnect path, and
RpcStats::protocol_violations
(plus RpcStats::checksum_failures
for corruption, or
RpcStats::version_rejections for
an unsupported peer) counts it.
The frame
Length-prefixed, checksummed frames and the incremental parser.
Frame layout
+----------------+---------------------+---------------------------+
| length: u32 LE | checksum: u64 LE | payload: `length` bytes |
+----------------+---------------------+---------------------------+
bytes 0..4 bytes 4..12 bytes 12..12+length
lengthcounts the payload only (the envelope, seewire). It is never zero.checksumis XXH3-64 over the fourlengthbytes followed by the payload: the header field that frames the stream is covered too, so a flipped length bit cannot silently re-frame the stream into different messages.
This mirrors FDB FlowTransport (scanPackets): a packet length, an
XXH3-64 checksum, PACKET_LIMIT checked before waiting for the body, the
checksum verified before anything is delivered, and checksum_failed
tearing the connection down. Unlike FDB, the checksum also covers the
length and is always on, TLS sessions included: making it optional
where the record layer already authenticates every byte would need one
more negotiated capability for the cost of one hash per frame, so it
stays on.
Until the checksum is verified, length is used for exactly two things:
rejecting a frame larger than the configured maximum (without buffering
it, so a corrupt or hostile length cannot allocate more than
HEADER_LEN + max_frame_bytes plus one read chunk) and knowing how many
bytes to wait for. Nothing is decoded before the checksum matches. On a
mismatch the decoder fails permanently: the connection is closed, never
resynchronised, and its in-flight calls fail as disconnected.
The envelope
The frame envelope: a hand-written, versioned, codec-independent layout.
The transport routes, bounds and rejects messages using only these
fields; bodies are opaque bytes tagged with their CodecId. All
integers are little-endian and fixed-width.
kind 0x01 HELLO magic u32 | min_version u16 | max_version u16
| incarnation u128 | features u64 | max_frame_bytes u32
| listen: family u8 (0 none, 4, 6) | ip (0, 4 or 16 bytes) | port u16 (if family > 0)
kind 0x02 REQUEST call_id u64 | incarnation u128 | token.index u64 | token.generation u32
| interface u32 | interface_version u16
| method u32 | schema u16 | codec u16 | flags u8
| [window u64, only with the stream flag]
| metadata_len u16 | metadata | body (rest of the frame)
kind 0x03 REPLY call_id u64 | status u8 | status 0: codec u16 | body (rest)
| status >0: detail u64 (nothing after)
kind 0x04 PING nonce u64
kind 0x05 PONG nonce u64
kind 0x06 STREAM_ITEM call_id u64 | sequence u64 | codec u16 | body (rest)
kind 0x07 STREAM_END call_id u64 | items u64 | status u8 | detail u64
kind 0x08 STREAM_ACK call_id u64 | consumed u64
kind 0x09 STREAM_CANCEL call_id u64
- HELLO: each side announces the range of envelope versions it speaks;
the session runs at the highest common version (
negotiate) and a peer with no common version is refused.featuresis reserved and unused: every version so far sends zero and ignores whatever arrives (TLS is a session upgrade, credentials and streams are negotiated by the version itself).max_frame_bytesis the largest frame payload the sender accepts: each side sends the peer nothing larger, so an oversized request or reply fails its own call instead of tearing the session down.listenis the sender’s canonical listening address (none for a client-only runtime): the receiver of an inbound session uses it to share that session as its own connection to the sender and to settle simultaneous connects (the larger canonical address keeps the connection it dialed, as inFoundationDB). - REQUEST:
interface/interface_versionname the endpoint group’s interface the reference was adjusted from; zero for a single-method endpoint. The server compares them with the registration before the method.metadatais a length-prefixed section: version 1 carries it and ignores it; version 2 reads request credentials from it (metadata), which the server’s security check verifies. It is never passed to a handler.flagsbit 0 marks a one-way request: the receiver never sends a reply or a rejection for it. Bit 1 opens a reply stream: the request then carries the caller’s creditwindow(accounted bytes it buffers unconsumed) right after the flags, and itscall_idnames the stream on this connection. Both bits together are invalid; every other bit is reserved and must be zero. STREAM_ITEM(server to caller): itemsequence(0, 1, 2, … per stream) of the streamcall_id. Its accounted size, the unit of stream credit, is its whole frame:stream_item_frame_lenof the body length.STREAM_END(server to caller): the stream’s single terminal frame, after its last item.itemsis how many items were sent;status0(with detail0) is a normal end, any other value a reply status code (below) with its detail.STREAM_ACK(caller to server):consumedis the cumulative accounted size of the items the caller’s application has taken, always on an item boundary. Cumulative, so only the latest one matters.STREAM_CANCEL(caller to server): the caller abandoned the stream.- PING / PONG: connection liveness. A PING is answered with a PONG carrying the same nonce; any received byte counts as liveness.
Frames byte by byte
Each frame below is a golden vector of tests/fixtures/: the payload of one frame, without its 12-byte header. The fields are the calls of the encoder, in order. The shared values of the vectors: call id 7, endpoint token 3, generation 1, method 0x20, schema 1, codec 1 (prost), and the body 0a 02 68 69, the protobuf of the string "hi".
hello-v1-v2-listen-v4| at | bytes | field | value | what it holds |
|---|---|---|---|---|
| 0 | 1 | kind | 1 | 0x01: this frame is a HELLO. |
| 1 | 4 | magic | 1297109571 | "MPRC" in ASCII: a moonpool-rpc session. |
| 5 | 2 | min_version | 1 | The oldest envelope version the sender speaks. |
| 7 | 2 | max_version | 2 | The newest envelope version the sender speaks. |
| 9 | 16 | incarnation | 0x0102030405060708090a0b0c0d0e0f10 | The sender's transport incarnation. |
| 25 | 8 | features | 0 | Reserved capability bits; zero in this version. |
| 33 | 4 | max_frame_bytes | 1048576 | The largest frame payload the sender accepts. |
| 37 | 7 | listen | 04 0a 00 01 01 94 11 | The sender's canonical listening address; None for a runtime that does not listen. One byte of family (0 none, 4, 6), the address (0, 4 or 16 bytes), then the port (u16). |
request| at | bytes | field | value | what it holds |
|---|---|---|---|---|
| 0 | 1 | kind | 2 | 0x02: this frame is a REQUEST. |
| 1 | 8 | call_id | 7 | Caller-allocated reply route, meaningful only on this connection. |
| 9 | 16 | incarnation | 0x0102030405060708090a0b0c0d0e0f10 | The transport incarnation the caller's reference names. |
| 25 | 8 | token.index | 3 | The endpoint token's token index (the top bit marks a well-known id). |
| 33 | 4 | token.generation | 1 | The endpoint token's token generation: a slot used again has a new generation. |
| 37 | 4 | interface | 1802895361 | The interface of the group the reference names (zero: a single-method endpoint). |
| 41 | 2 | interface_version | 2 | That interface's version (zero with interface zero). |
| 43 | 4 | method | 32 | The method the caller invokes. |
| 47 | 2 | schema | 1 | The contract version the caller encoded with. |
| 49 | 2 | codec | 1 | The codec that produced body. |
| 51 | 1 | flags | 0 | Request flags (REQUEST_FLAG_ONE_WAY, REQUEST_FLAG_STREAM); unknown bits are a protocol violation. |
| 52 | 2 | metadata_len | 0 | The length of the metadata section, in bytes. |
| 54 | 0 | metadata | none | Reserved credential/metadata section; empty in this version. |
| 54 | 4 | body | 0a 02 68 69 | The encoded request. |
request-stream| at | bytes | field | value | what it holds |
|---|---|---|---|---|
| 0 | 1 | kind | 2 | 0x02: this frame is a REQUEST. |
| 1 | 8 | call_id | 7 | Caller-allocated reply route, meaningful only on this connection. |
| 9 | 16 | incarnation | 0x0102030405060708090a0b0c0d0e0f10 | The transport incarnation the caller's reference names. |
| 25 | 8 | token.index | 3 | The endpoint token's token index (the top bit marks a well-known id). |
| 33 | 4 | token.generation | 1 | The endpoint token's token generation: a slot used again has a new generation. |
| 37 | 4 | interface | 1802895361 | The interface of the group the reference names (zero: a single-method endpoint). |
| 41 | 2 | interface_version | 2 | That interface's version (zero with interface zero). |
| 43 | 4 | method | 32 | The method the caller invokes. |
| 47 | 2 | schema | 1 | The contract version the caller encoded with. |
| 49 | 2 | codec | 1 | The codec that produced body. |
| 51 | 1 | flags | 2 | Request flags (REQUEST_FLAG_ONE_WAY, REQUEST_FLAG_STREAM); unknown bits are a protocol violation. |
| 52 | 8 | stream_window | 65536 | With REQUEST_FLAG_STREAM: the caller's credit window, the accounted bytes it buffers unconsumed. Not on the wire (and zero) otherwise. Only when flags & REQUEST_FLAG_STREAM != 0. |
| 60 | 2 | metadata_len | 0 | The length of the metadata section, in bytes. |
| 62 | 0 | metadata | none | Reserved credential/metadata section; empty in this version. |
| 62 | 4 | body | 0a 02 68 69 | The encoded request. |
request-bearer| at | bytes | field | value | what it holds |
|---|---|---|---|---|
| 0 | 1 | kind | 2 | 0x02: this frame is a REQUEST. |
| 1 | 8 | call_id | 7 | Caller-allocated reply route, meaningful only on this connection. |
| 9 | 16 | incarnation | 0x0102030405060708090a0b0c0d0e0f10 | The transport incarnation the caller's reference names. |
| 25 | 8 | token.index | 3 | The endpoint token's token index (the top bit marks a well-known id). |
| 33 | 4 | token.generation | 1 | The endpoint token's token generation: a slot used again has a new generation. |
| 37 | 4 | interface | 1802895361 | The interface of the group the reference names (zero: a single-method endpoint). |
| 41 | 2 | interface_version | 2 | That interface's version (zero with interface zero). |
| 43 | 4 | method | 32 | The method the caller invokes. |
| 47 | 2 | schema | 1 | The contract version the caller encoded with. |
| 49 | 2 | codec | 1 | The codec that produced body. |
| 51 | 1 | flags | 0 | Request flags (REQUEST_FLAG_ONE_WAY, REQUEST_FLAG_STREAM); unknown bits are a protocol violation. |
| 52 | 2 | metadata_len | 16 | The length of the metadata section, in bytes. |
| 54 | 16 | metadata | 01 0d 00 65 79 4a 2e 74 6f 6b 65 6e 2e 73 69 67 | Reserved credential/metadata section; empty in this version. |
| 70 | 4 | body | 0a 02 68 69 | The encoded request. |
The metadata section holds one entry: kind 1 (a bearer credential), its length (u16), then its bytes.
reply-ok| at | bytes | field | value | what it holds |
|---|---|---|---|---|
| 0 | 1 | kind | 3 | 0x03: this frame is a REPLY. |
| 1 | 8 | call_id | 7 | The call_id of the request this answers, on this connection. |
| 9 | 1 | status | 0 | 0: the handler replied. The reply body follows. |
| 10 | 2 | codec | 1 | |
| 12 | 4 | body | 0a 02 68 69 |
reply-method-mismatch| at | bytes | field | value | what it holds |
|---|---|---|---|---|
| 0 | 1 | kind | 3 | 0x03: this frame is a REPLY. |
| 1 | 8 | call_id | 7 | The call_id of the request this answers, on this connection. |
| 9 | 1 | status | 3 | The status code: 3 is a method mismatch, and its detail is the registered method. |
| 10 | 8 | detail | 33 | What the status adds (see the table of statuses). 0 when it carries nothing. |
ping| at | bytes | field | value | what it holds |
|---|---|---|---|---|
| 0 | 1 | kind | 4 | 0x04: this frame is a PING. |
| 1 | 8 | nonce | 9 | Echoed back in the pong. |
stream-item| at | bytes | field | value | what it holds |
|---|---|---|---|---|
| 0 | 1 | kind | 6 | 0x06: this frame is a STREAM_ITEM. |
| 1 | 8 | call_id | 7 | The stream: the call_id of the request that opened it. |
| 9 | 8 | sequence | 3 | The item's position in the stream, from zero. |
| 17 | 2 | codec | 1 | The codec that produced body. |
| 19 | 2 | body | 08 01 | The encoded item. |
stream-end-failed| at | bytes | field | value | what it holds |
|---|---|---|---|---|
| 0 | 1 | kind | 7 | 0x07: this frame is a STREAM_END. |
| 1 | 8 | call_id | 7 | The stream. |
| 9 | 8 | items | 1 | How many items the producer sent. |
| 17 | 1 | status | 13 | 0 for a normal end, else a status code: 13 is a stream that its producer failed. |
| 18 | 8 | detail | 5 | With status 13, the application's code. |
stream-ack| at | bytes | field | value | what it holds |
|---|---|---|---|---|
| 0 | 1 | kind | 8 | 0x08: this frame is a STREAM_ACK. |
| 1 | 8 | call_id | 7 | The stream. |
| 9 | 8 | consumed | 128 | Accounted bytes of items the caller's application consumed. |
stream-cancel| at | bytes | field | value | what it holds |
|---|---|---|---|---|
| 0 | 1 | kind | 9 | 0x09: this frame is a STREAM_CANCEL. |
| 1 | 8 | call_id | 7 | The stream. |
The metadata section
The request credential section (protocol version 2).
A request’s metadata section (its u16-length-prefixed bytes, see
wire) holds zero or more entries:
entry := kind u8 | len u16 LE | value (len bytes)
kind 1: bearer credential (at most one; never empty)
Every other kind is reserved: a section carrying one is malformed and the request is refused (fail closed), never partly understood. Under protocol version 1 the section is carried and ignored, as version 1 specifies: credentials only count on a version 2 session.
Reply statuses
A REPLY or a STREAM_END with a status other than 0 is a rejection. The status tells the caller why, and the error that the caller gets tells it what the server did: never ran the handler (NotAdmitted), maybe ran it (MaybeExecuted), or ran it (Executed). A status that ends the reference fails every later call through the same reference.
| code | status | since | proves | ends the reference | what the server says |
|---|---|---|---|---|---|
| 1 | EndpointNotFound | v1 | NotAdmitted | yes | No live endpoint holds the token. |
| 2 | StaleIncarnation | v1 | NotAdmitted | yes | The reference names another incarnation of this transport. |
| 3 | MethodMismatch | v1 | NotAdmitted | yes | The endpoint serves a different method. |
| 4 | SchemaMismatch | v1 | NotAdmitted | yes | The endpoint serves a different contract version. |
| 5 | CodecMismatch | v1 | NotAdmitted | yes | The request body uses a codec the endpoint does not accept. |
| 6 | MalformedRequest | v1 | NotAdmitted | no | The request body did not decode as the registered request type. |
| 7 | Overloaded | v1 | NotAdmitted | no | The endpoint's queue was full. |
| 8 | BrokenPromise | v1 | MaybeExecuted | no | The handler dropped its reply handle without replying. |
| 9 | ReplyTooLarge | v1 | Executed | no | The handler's reply exceeded the frame limit of the session. |
| 10 | ReplyEncodeFailed | v1 | Executed | no | The handler's reply could not be encoded by its codec. |
| 11 | MethodNotFound | v1 | NotAdmitted | no | The endpoint is a group that does not serve the method. |
| 12 | InterfaceMismatch | v1 | NotAdmitted | yes | The endpoint serves another interface than the reference names. |
| 13 | StreamFailed | v1 | Executed | no | The producer ended the stream with an application error code. |
| 14 | StreamProtocol | v1 | MaybeExecuted | no | The other side broke the stream protocol (a regressing, excess or misaligned acknowledgement); the stream was ended. |
| 15 | StreamingMismatch | v1 | NotAdmitted | yes | A stream request for a unary method, or a unary request for a streaming method. |
| 16 | Unauthenticated | v2 | NotAdmitted | no | The caller is not (validly) authenticated for the endpoint (version 2). |
| 17 | PermissionDenied | v2 | NotAdmitted | no | The caller is authenticated but not allowed to call the endpoint (version 2). |
| 18 | ShuttingDown | v2 | NotAdmitted | no | The server's runtime is shutting down and admits nothing new (version 2). |
A failure that no server sent has a reason and a proof too: a disconnect before the request left is NotAdmitted, after it MaybeExecuted; a timeout keeps the ambiguity.
| proof | what it means |
|---|---|
NotAdmitted | The request was never handed to a handler: it was refused before admission (by this runtime or by the server) or never left this process. Retrying cannot duplicate a previous execution of *this* attempt. |
MaybeExecuted | The handler may or may not have run (the request may have been admitted, and no outcome came back). Retrying may execute it twice. |
Executed | The handler ran: it produced an outcome this side could not use. |
The one error every RPC operation returns: a reason and what it proves about execution.
The two are separate on purpose. The same reason can carry different
knowledge: a disconnect before the request frame left this process is
Execution::NotAdmitted; after, Execution::MaybeExecuted. Every
failure path reports the strongest knowledge it honestly has, never more.
A caller that drops the call future (or wraps it in its own timeout) is
cancelling, not failing: no RpcError is produced, and the attempt must
be treated as Execution::MaybeExecuted. Use
ServiceClient::try_get_reply_within
to get a timeout with execution knowledge.
Versions
| Version | Adds |
|---|---|
| 1 | everything above except what version 2 adds: handshake, requests, replies, liveness, reply streams (stream frames, flag and statuses 13–15 were added to version 1 in place by #216, before any release) |
| 2 | the metadata section carries credentials (metadata) and the server verifies them; statuses 16–18 |
Every frame layout is identical in both versions: version 2 changes
what the metadata section means and adds status codes. The rule that
keeps an older peer safe: nothing introduced after the negotiated
version is ever sent. A rejection a version 1 peer cannot decode is
sent as the version 1 status that proves the same about execution
(WireError::for_version: a denial becomes “endpoint not found”, as
FoundationDB’s unauthorized-endpoint notice marks the endpoint failed
for its caller; shutting down becomes “overloaded”), and a version 1
session ignores credentials, as version 1 specifies. A server that
verifies credentials speaks only version 2, so an older client is
refused at the handshake rather than let through without one. The
decoder is version-aware too (decode_message_at): a status newer
than the session’s version is a protocol violation, never guessed at.
The golden vectors of both versions are in tests/fixtures/wire-v1.txt
and tests/fixtures/wire-v2.txt. Changing a layout, a kind or a status
code requires a new PROTOCOL_VERSION.
Identity and references
Endpoint identity: transport incarnations, checked tokens, addresses and access classes.
A dynamic Endpoint names one receiving endpoint inside one transport
incarnation, plus the resolved address that reaches it:
- the address is a resolved
ip:port(SocketAddr); hostnames belong only to well-known bootstrap endpoints (seeBootstrapClient); - the
Incarnationis 128 bits drawn from the provider’s random source when a runtime starts (or supplied by the caller), so a restarted process at the sameip:portis a different incarnation and rejects references to its predecessor; - the
EndpointTokenis a 64-bit registry slot plus a checked 32-bit generation, so a slot reused after its receiver was dropped never answers to the old token (no ABA); - a
WellKnownIdtoken instead names a fixed bootstrap service that answers in every incarnation (its admission skips the incarnation check), so a reference to it survives the server’s restart.
None of these is a credential. Two independently started runtimes collide
with probability about n² / 2^129 for n live incarnations. Durable
identity and fencing are the application’s.
A reference, field by field
A ServiceRef is a protobuf message. This is the golden vector service of tests/fixtures/references-v1.txt, read field by field:
service| at | tag | type | field | value |
|---|---|---|---|---|
| 0 | 1 | varint | method id | 1701013615 |
| 6 | 2 | varint | schema version | 1 |
| 8 | 3 | varint | request codec | 1 |
| 10 | 4 | varint | reply codec | 1 |
| 12 | 5 | varint | access class (0 private, 1 public) | 1 |
| 14 | 6 | fixed64 | incarnation, high and low 64 bits | 72623859790382856 |
| 23 | 7 | fixed64 | incarnation, high and low 64 bits | 651345242494996240 |
| 32 | 8 | fixed64 | token index (the top bit marks a well-known id) | 3 |
| 41 | 9 | varint | token generation | 7 |
| 43 | 10 | bytes | IP address, 4 or 16 bytes | 0a 00 01 01 |
| 49 | 11 | varint | port | 4500 |
A field equal to its default is not written. The incarnation is two fixed64 halves (tags 6 and 7); the address is 10.0.1.1 (tag 10) and the port 4500 (tag 11).
Interfaces as data
Interfaces as data: serialisable references, endpoint groups and their checked method adjustment.
A service interface is a set of methods served by one dynamic
endpoint group: one registry slot, one runtime incarnation, one
AccessClass, several RpcMethods told apart
by their explicit MethodIds (FoundationDB’s
getAdjustedEndpoint, with stable method identifiers instead of
declaration offsets).
RpcInterfacenames an interface with an explicitInterfaceIdand version;InterfaceMethoddeclares a method a member.RpcHandle::register_groupallocates aServiceGroup;ServiceGroup::serveopens one method’sRequestStream.InterfaceRefandServiceRefare immutable routing data and protobuf messages: return them in replies, embed them in requests, persist them, forward them to a third participant. Decoding one needs no runtime and keeps nothing alive.- Binding (
InterfaceRef::bind,ServiceRef::bind) picks the runtime that carries the calls; it registers nothing.
Lifetimes
Dropping the ServiceGroup destroys the group: new requests for any of
its methods fail with EndpointNotFound,
requests queued but not yet received complete as broken promises, and
every stream of the group ends. A request already received finishes
under its own ReplyHandle, which is the owned
guard of admitted work: replying after the group is gone still reaches
the caller over the session it came from. Dropping one method’s stream
removes only that method; the group keeps serving the others and the
method may be served again under the same reference. That is why
MethodNotFound is not terminal
for a reference (it proves only that this attempt never ran), while
InterfaceMismatch is.
Fresh incarnations are explicit
A reference names one runtime incarnation. After a restart at the same
address every reference to the old incarnation is refused
(StaleIncarnation) and never
dispatched to the new one; the new incarnation publishes new references
and callers learn them through the application (a well-known directory,
a recruitment reply). Nothing refreshes a dynamic reference by itself.
Callbacks
A ReplyHandle is bound to the session that
delivered its request and has no byte form: it cannot be forwarded. A
callback that a third party may invoke is an ordinary dynamic endpoint:
register it, and put its ServiceRef in the request.
Admission
Validate and hand one request to its receiver. Local and remote admissions both come through here. Every rejection is delivered along the context’s route before returning.
Order: shutdown, identity (incarnation, token), contract (interface, method, schema, codec, streaming), security (credential and access policy), then capacity; only then is the body decoded and handed to the endpoint. A request that fails any check never reaches a handler or a queue.
The rejections, in the order that admit makes them. The first check that fails sends its status, and no body byte is decoded before the last one passed:
ShuttingDownstatus 18StaleIncarnationstatus 2EndpointNotFoundstatus 1InterfaceMismatchstatus 12MethodMismatchstatus 3MethodNotFoundstatus 11SchemaMismatchstatus 4CodecMismatchstatus 5StreamingMismatchstatus 15Unauthenticatedstatus 16PermissionDeniedstatus 17Overloadedstatus 7
Delivery
| Call | Delivery | Completion |
|---|---|---|
ServiceClient::send |
one-way, zero or one executions | Ok means queued, never “executed” |
ServiceClient::try_get_reply, ServiceClient::attempt |
one attempt, never retransmitted | reply, or an error that says what it proves |
ServiceClient::get_reply |
request retained in memory and resent on every new connection: may execute more than once | first outcome wins; a dead dynamic endpoint ends it at once |
ServiceClient::get_reply_unless_failed_for |
reliable, bounded by sustained observed failure | ErrorReason::PeerFailed keeps the ambiguity |
A method whose RpcMethod::STREAMING is true answers with a reply
stream instead: ServiceClient::get_reply_stream returns a
ReplyStream of ordered items, the handler turns its reply handle
into a StreamProducer (ReplyHandle::into_stream), and the
producer is paced by what the caller’s application consumed, never by
what was merely read off the socket. See stream.
A ReplyAttempt is one attempt as a future: kept, it yields a late
outcome after its caller moved on; dropped, its route is released and a
late reply is counted and discarded. On the serving side a
ReplyHandle can reply, be dropped (a broken promise), or finish with
ReplyHandle::never_reply (nothing sent; the caller’s own deadline
decides).
An at-most-once attempt is bound to the connection it was queued on:
when that connection ends, the attempt fails (NotAdmitted if its frame
never started to leave, MaybeExecuted otherwise). A reliable call
keeps its request in memory while its caller waits, and each time its
connection ends it is queued again on the next one, so the server may
execute it more than once. Unsent bytes belong to a connection;
retained requests belong to the call. Nothing is retained past the
caller: cancellation, a reply, a terminal rejection or shutdown release
it, without retracting bytes already written.
Contracts
-
At most once per attempt. No hidden retry or reconnect replay outside
ServiceClient::get_reply, which says so. Every failure is oneRpcError: a reason plus what it proves (Execution::NotAdmitted,Execution::MaybeExecuted,Execution::Executed); a timeout, disconnect after transmission or dropped caller preserves ambiguity. -
Checked identity. A request is admitted only if its incarnation, endpoint token (slot + generation), method, schema and codec all match a live registration, before any body byte is decoded. Dropping a receiver destroys its endpoint; a reused slot never answers an old token; a restarted process at the same address rejects its predecessor’s references (
ErrorReason::StaleIncarnation). -
Peer-relative replies. A reply handle routes only to the connection that delivered the request; it has no byte form and cannot be forwarded (a forwardable callback is an ordinary registered endpoint whose
ServiceReftravels in the request):fn embed<T: Wire>() {} embed::<ReplyHandle<Echo>>(); // a reply handle is not data -
Owned lifetimes. Handles, clients, receivers and reply handles hold the runtime weakly; nothing but the driver keeps it serving.
-
Bounded everything, pushing back instead of failing. Frame size, queued requests and bytes, in-flight requests, retained bodies, streams and their windows, control frames, pending calls, endpoints and connections all have hard limits (
RpcConfig,ResourceLimits,StreamPolicy). Work beyond a budget is refused where it would enter, asErrorReason::OverloadedwithExecution::NotAdmitted; nothing admitted is dropped to make room, and a slow writer pushes back on admission instead of closing the session. Control frames go first and the socket reader never waits on an application queue; malformed, corrupt or oversized input closes the connection observably (RpcStats).
Reply streams
Reply streams: one request, then an ordered stream of typed replies
paced by the consumer’s consumption (FoundationDB’s getReplyStream,
ReplyPromiseStream and AcknowledgementReceiver).
caller server
get_reply_stream(req) ── REQUEST (stream, window W) ──► admission
handler: reply.into_stream()
ReplyStream::next() ◄── STREAM_ITEM #0, #1, ... ── StreamProducer::send(item)
(item taken) ── STREAM_ACK consumed ────► (waits while W is used up)
◄── STREAM_END (ok | error) ── finish() / fail(code) / drop
drop(stream) ── STREAM_CANCEL ──────────► send() -> Err(Cancelled)
Contracts
- One registration attempt. Opening a stream sends one request, at
most once; it is never retransmitted, and a stream is never resumed
on another connection. A broken connection ends the stream on both
sides (
ErrorReason::Disconnectedfor the consumer,SendError::Disconnectedfor the producer); continuing is the application’s decision, with a new stream. - Credit is consumption. The consumer announces a window
W(StreamPolicy::window_bytes). The producer’ssendreserves an item’s accounted size (its whole frame,stream_item_frame_len) atomically, first come first served, and waits whileWbytes are sent and unacknowledged. The consumer acknowledges an item when its application takes it: on arrival if the application is already waiting (the item is handed to it), otherwise when it is popped from the queue. Bytes read off the socket earn nothing, so a slow consumer holds at mostWbytes and a stalled one stops the producer. Counters are cumulative, checkedu64s. - Oversized items are refused, never parked. An item larger than
the window or the session’s frame limit fails its
sendwithSendError::TooLargeat once; the stream stays open. Choose a window at least as large as the largest item. - Order and one terminal state. Items carry sequence numbers; the
consumer checks them, the announced item count at the end and its
window, and ends the stream with
ErrorReason::StreamProtocol(telling the producer to stop) on any violation instead of skipping. The producer checks every acknowledgement: a repeat is ignored; one that regresses, exceeds what was sent, or does not land on an item boundary ends the stream with a protocol error. Every stream ends exactly once, and every item that reached the consumer is observable in order before its terminal outcome, whatever that outcome is (normal end, the producer’sfail, a broken promise, a disconnect). A consumer that drops its stream observes nothing more; the producer’s unwritten items are discarded. - Cancellation does not roll back. Dropping a
ReplyStreambefore the request left withdraws it (never admitted); after, sendsSTREAM_CANCEL, and the producer’s nextsend(or the one waiting for credit) fails withSendError::Cancelled. Effects the handler already had stay. - Errors need no credit. A stream’s end is not an item: it is emitted even when the window is exhausted, after the items already queued.
What an error proves about execution: a rejection before admission is
Execution::NotAdmitted; once an item
arrived the handler demonstrably ran, so every later error is
Execution::Executed; before any item, a
disconnect or broken promise is
Execution::MaybeExecuted.
Sessions, peers and failure
A connection is upgraded (Connector / Acceptor, Plaintext by
default) before any frame is exchanged, then both sides send a Hello.
Requests are written only after the peer’s Hello was accepted, so a
session refused at the handshake never carried a request and its calls
fail as Execution::NotAdmitted.
Calls to a remote address ride that address’s selected connection
(see peer). It is dialed on demand, re-dialed with a jittered
backoff after it ends, pinged while it lives and closed once idle. An
accepted session whose Hello names a listen address (verified per
InboundSharing) becomes the selected
connection to that address when none exists, so two runtimes calling
each other share one connection; when both dial at once, the runtime
with the larger canonical address keeps the connection it dialed and
the other adopts it and closes its own (FoundationDB’s
Peer::onIncomingConnection).
The failure monitor
The failure monitor: what one runtime currently believes about the addresses and endpoints it talks to, and race-free ways to wait for that belief to change.
Three facts are kept apart on purpose (FoundationDB’s
SimpleFailureMonitor, without its process-global singleton):
- Address availability (
AddressState). An address becomesFailedonly after connections to it kept failing forPeerPolicy::failure_detection_delay, andAvailableagain as soon as a session with it establishes. An address never contacted is available. Two failures further apart than one full redial cycle belong to different runs. A peer that closes an established session cleanly, with no call on it and no watcher of its address, causes no failure. - Disconnect events. Every end of a connection this runtime used to call an address is stamped at once with a runtime-wide, monotonic sequence, even while the address still counts as available: a call bound to the connection that died learns of it without waiting for the failure delay.
- Permanent endpoint failure (
EndpointState::NotFound,EndpointState::StaleIncarnation). Learned from the server’s own rejection and remembered (bounded), so later calls to the same dynamic reference fail at once without a round trip. A live address never revives a dead dynamic endpoint; well-known endpoints are never remembered as failed because they may come back at the same token.
Every wait registers before it checks (a versioned latch), so a change
that happens between the check and the wait is never lost. Waits may
wake spuriously; each re-checks its condition. All of them fail with
ErrorReason::Shutdown once the runtime is gone.
Security
Who may call what: request verification, endpoint access policy, the
UTC validation clock and, behind feature tls, the TLS adapter.
Trust model
- A TCP address or an endpoint token is not an identity.
- TLS (the
tlsmodule, behind featuretls) authenticates the server to its clients, and, when the server asks for it (tls::ClientAuth), the client to the server (mutual TLS). A verified certificate’s name becomes the session’s peer identity; it grants something only on a runtime that opts in withSecurityConfig::admit_authenticated_peers. - A client is identified per request, by a credential it attaches
(
Credential, from aCredentialSource) and the server verifies (RequestVerifier, which the application supplies: a token format is the application’s choice) into aPrincipal. - An
AccessPolicydecides, per request, whether that principal (or an anonymous caller) may call the endpoint. The default (DefaultPolicy) lets anyone who passes verification call aPublicendpoint and requires a verified principal for aPrivateone. - The check runs in admission, after the endpoint’s identity and contract were checked and before the request reaches a handler or a queue. Local calls (a caller in the same runtime) go through the same check with the same credential, so they get no shortcut.
Private endpoints fail closed by default. SecurityConfig::default
verifies nothing, so every private endpoint refuses every caller. A
deployment that relies on its network instead says so with
SecurityConfig::trusted_network, which admits everything and makes
no confidentiality or authentication claim.
Clocks and entropy
Validation time is a UtcClock, never the runtime’s scheduling time;
the default NoUtc knows no time, so expiring credentials fail closed
until a clock is chosen (SystemUtc in production, FixedUtc in
tests and simulation). Cryptographic entropy belongs to the TLS
dependency; the runtime’s RandomProvider only draws protocol values
(incarnations, jitter).
Redaction
A credential’s Debug shows only its length, and nothing in this crate
logs credential bytes, principals or tokens. Denials are traced as audit
events (target moonpool_rpc::audit, rpc_request_denied, after
FoundationDB’s AttemptedRPCToPrivatePrevented) naming the endpoint,
the access class, the peer address and the reason code. There is one
warn event per denial and no built-in throttling: aggregate through the
moonpool_rpc_requests_denied_total{reason} counter of
RpcMetrics, and rate-limit a noisy peer in the
tracing subscriber.
Shutdown
Shut the runtime down gracefully, within grace of provider time.
- Close admission: from now on new requests from peers are
refused (
ErrorReason::ServerShuttingDownfor them, never admitted), new calls, streams and registrations here fail withErrorReason::Shutdown, the listener closes and nothing is dialed or re-dialed (a reliable call whose connection ends is failed, not retransmitted). - Drain: admitted requests may still be answered, streams may
still produce and be consumed, and calls this runtime made may
still complete, until nothing is pending or
gracehas passed. - Terminate: every call still pending fails with
ErrorReason::Shutdownand the execution knowledge it has (MaybeExecutedonce its request left), and every connection is closed from this side (a TLS session sends itsclose_notify), which ends the streams on it; callers still owed a reply see their session end after admission, i.e.MaybeExecuted. Nothing is reported as executed or not executed that was not proven. - Waits (at most
RpcConfig::handshake_timeout) for every connection’s driver to finish.
The driver must keep being polled meanwhile (poll this future next to
RpcDriver::run); drop the driver once it
resolves. Dropping the driver instead is the abrupt shutdown: it
closes everything at once, and this future then resolves with
ShutdownReport::already_stopped.
How it is tested
This crate never depends on moonpool-sim. It calls the inert
moonpool_buggify macros, which evaluate to false outside a
simulation. Under a simulation, these sites force the rare moments that
random network faults seldom hit:
- a session cut right behind a two-way request (the lost-response
window): an at-most-once call fails
Execution::MaybeExecuted, and a reliable call may execute twice; - a spurious
ErrorReason::Overloadedrefusal at admission; - a stream acknowledgement deferred to the next item;
- a failure-monitor wakeup with nothing changed.
RpcStats counts each injected fault. The simulation harness,
workloads and oracles live in the non-published moonpool-rpc-sim
crate.
Wire format: protocol (frame and envelope), codec (bodies).
The golden vectors of both versions are in tests/fixtures/wire-v1.txt
and tests/fixtures/wire-v2.txt. Changing a layout, a kind or a status
code requires a new PROTOCOL_VERSION.
The campaigns of moonpool-rpc-sim
| Module | Binary | What it proves |
|---|---|---|
foundations |
sim-rpc-foundations |
Typed request/reply between two process groups and a surviving workload, judged by a handler receipt ledger. The corruption suite: it alone draws bit flips |
delivery |
sim-rpc-delivery |
Every delivery mode, lost replies, crashes, simultaneous connects, bootstrap names and failure-monitor transitions, judged by an execution ledger |
interfaces |
sim-rpc-interfaces |
Interfaces published, stored, recruited and forwarded to a third participant across same-address restarts |
streams |
sim-rpc-streams |
Reply streams with consumption credit, abandonment, saturation, bounded admission and producer reboots |
security |
sim-rpc-security |
Credentials and endpoint access under key rotation, UTC transitions, crashes, graceful shutdowns and mixed protocol versions: no unauthorized execution, ever |
tls |
sim-rpc-tls |
TLS 1.3 sessions, mutual or not, with certificates from the production authority, under UTC steps, certificate rotation, an impostor server and bit flips |
qualification |
sim-rpc-qualification |
All of the above at once, with a declared recovery phase, resource baselines after every process death, and semantic replay across runs and host speeds |
Each module exposes a campaign function that returns a configured
moonpool_sim::SimulationBuilder, plus its processes, workload, fault
injector and records. The tests in tests/ run each campaign as
bounded, deterministic seed budgets under nextest.
- Network chaos. Swarm network faults per seed. Every campaign but
foundations and tls masks bit flips with
without_corruption: corruption is its own explicit suite, never arbitrary loss on healthy TCP. Under TLS a flipped bit is an authentication failure that ends the session, so the tls campaign keeps them. - Process faults. Scripted crashes (for example, right after a
handler received a request), same-address restarts and graceful
shutdowns, through each campaign’s
FaultInjector. - Runtime buggify sites.
moonpool-rpccarries its own buggify points: session cuts behind a request, spurious overload refusals, deferred stream acknowledgements and spurious failure-monitor wakeups. Each campaign records which ones fired as reachable assertions, read from the counters ofmoonpool_rpc::RpcStatsthat every runtime reports (one last time when it stops, through itsmoonpool_rpc::ResourceProbe). Each campaign’s test requires the sites that campaign reaches.
The network faults are the simulator's: Network faults shows each family in a live run.