moonpool ~
GitHub →
$ extras

moonpool-rpc, call by call

Typed RPC between dynamic endpoints: its frames byte by byte, what each failure proves, admission, streams and security.

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

modulewhat it holds
codecPayload codecs: how request and reply bodies become bytes.
configinternalTransport limits and settings.
endpointinternalEndpoint identity: transport incarnations, checked tokens, addresses and access classes.
errorinternalCall outcomes: the failure reason, kept separate from what it proves about execution.
failureinternalThe 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.
interfaceInterfaces as data: serialisable references, endpoint groups and their checked method adjustment.
observabilityMetrics and diagnostics: the runtime's counters and gauges as a MetricsSource, with a fixed, bounded label set.
protocolWire protocol: framing, the envelope and method/schema identity.
securityWho may call what: request verification, endpoint access policy, the UTC validation clock and, behind feature tls, the TLS adapter.
statsinternalObservable counters and lifetime probes.
streamReply streams: one request, then an ordered stream of typed replies paced by the consumer's consumption (FoundationDB's getReplyStream, ReplyPromiseStream and AcknowledgementReceiver).
callinternalThe typed calling and serving surface: references, clients, receivers and reply handles.
transportinternalThe 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:

  1. Frame (frame): u32 LE length | u64 LE XXH3-64(length bytes ‖ payload) | payload. The length is bounded by RpcConfig::max_frame_bytes before the payload is buffered; the checksum is verified before the payload is parsed.
  2. Envelope (wire): a hand-written, fixed-width, little-endian layout owned by this crate and versioned by PROTOCOL_VERSION. It carries everything the transport needs to route, bound and reject a message — kind, reply route (call_id), transport incarnation, endpoint token, MethodId, SchemaVersion and CodecId — and never depends on a payload codec.
  3. Body: opaque bytes produced by a Wire implementation, 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
  • length counts the payload only (the envelope, see wire). It is never zero.
  • checksum is XXH3-64 over the four length bytes 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. features is 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_bytes is 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. listen is 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 in FoundationDB).
  • REQUEST: interface / interface_version name 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. metadata is 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. flags bit 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 credit window (accounted bytes it buffers unconsumed) right after the flags, and its call_id names the stream on this connection. Both bits together are invalid; every other bit is reserved and must be zero.
  • STREAM_ITEM (server to caller): item sequence (0, 1, 2, … per stream) of the stream call_id. Its accounted size, the unit of stream credit, is its whole frame: stream_item_frame_len of the body length.
  • STREAM_END (server to caller): the stream’s single terminal frame, after its last item. items is how many items were sent; status 0 (with detail 0) is a normal end, any other value a reply status code (below) with its detail.
  • STREAM_ACK (caller to server): consumed is 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 · 44 bytes · golden vector hello-v1-v2-listen-v4
atbytesfieldvaluewhat it holds
01kind10x01: this frame is a HELLO.
14magic1297109571"MPRC" in ASCII: a moonpool-rpc session.
52min_version1The oldest envelope version the sender speaks.
72max_version2The newest envelope version the sender speaks.
916incarnation0x0102030405060708090a0b0c0d0e0f10The sender's transport incarnation.
258features0Reserved capability bits; zero in this version.
334max_frame_bytes1048576The largest frame payload the sender accepts.
377listen04 0a 00 01 01 94 11The 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 · 58 bytes · golden vector request
atbytesfieldvaluewhat it holds
01kind20x02: this frame is a REQUEST.
18call_id7Caller-allocated reply route, meaningful only on this connection.
916incarnation0x0102030405060708090a0b0c0d0e0f10The transport incarnation the caller's reference names.
258token.index3The endpoint token's token index (the top bit marks a well-known id).
334token.generation1The endpoint token's token generation: a slot used again has a new generation.
374interface1802895361The interface of the group the reference names (zero: a single-method endpoint).
412interface_version2That interface's version (zero with interface zero).
434method32The method the caller invokes.
472schema1The contract version the caller encoded with.
492codec1The codec that produced body.
511flags0Request flags (REQUEST_FLAG_ONE_WAY, REQUEST_FLAG_STREAM); unknown bits are a protocol violation.
522metadata_len0The length of the metadata section, in bytes.
540metadatanoneReserved credential/metadata section; empty in this version.
544body0a 02 68 69The encoded request.
REQUEST that opens a reply stream · 66 bytes · golden vector request-stream
atbytesfieldvaluewhat it holds
01kind20x02: this frame is a REQUEST.
18call_id7Caller-allocated reply route, meaningful only on this connection.
916incarnation0x0102030405060708090a0b0c0d0e0f10The transport incarnation the caller's reference names.
258token.index3The endpoint token's token index (the top bit marks a well-known id).
334token.generation1The endpoint token's token generation: a slot used again has a new generation.
374interface1802895361The interface of the group the reference names (zero: a single-method endpoint).
412interface_version2That interface's version (zero with interface zero).
434method32The method the caller invokes.
472schema1The contract version the caller encoded with.
492codec1The codec that produced body.
511flags2Request flags (REQUEST_FLAG_ONE_WAY, REQUEST_FLAG_STREAM); unknown bits are a protocol violation.
528stream_window65536With 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.
602metadata_len0The length of the metadata section, in bytes.
620metadatanoneReserved credential/metadata section; empty in this version.
624body0a 02 68 69The encoded request.
REQUEST with a bearer credential (version 2) · 74 bytes · golden vector request-bearer
atbytesfieldvaluewhat it holds
01kind20x02: this frame is a REQUEST.
18call_id7Caller-allocated reply route, meaningful only on this connection.
916incarnation0x0102030405060708090a0b0c0d0e0f10The transport incarnation the caller's reference names.
258token.index3The endpoint token's token index (the top bit marks a well-known id).
334token.generation1The endpoint token's token generation: a slot used again has a new generation.
374interface1802895361The interface of the group the reference names (zero: a single-method endpoint).
412interface_version2That interface's version (zero with interface zero).
434method32The method the caller invokes.
472schema1The contract version the caller encoded with.
492codec1The codec that produced body.
511flags0Request flags (REQUEST_FLAG_ONE_WAY, REQUEST_FLAG_STREAM); unknown bits are a protocol violation.
522metadata_len16The length of the metadata section, in bytes.
5416metadata01 0d 00 65 79 4a 2e 74 6f 6b 65 6e 2e 73 69 67Reserved credential/metadata section; empty in this version.
704body0a 02 68 69The encoded request.

The metadata section holds one entry: kind 1 (a bearer credential), its length (u16), then its bytes.

REPLY, a success · 16 bytes · golden vector reply-ok
atbytesfieldvaluewhat it holds
01kind30x03: this frame is a REPLY.
18call_id7The call_id of the request this answers, on this connection.
91status00: the handler replied. The reply body follows.
102codec1
124body0a 02 68 69
REPLY, a rejection · 18 bytes · golden vector reply-method-mismatch
atbytesfieldvaluewhat it holds
01kind30x03: this frame is a REPLY.
18call_id7The call_id of the request this answers, on this connection.
91status3The status code: 3 is a method mismatch, and its detail is the registered method.
108detail33What the status adds (see the table of statuses). 0 when it carries nothing.
PING (a PONG has the same layout, kind 0x05) · 9 bytes · golden vector ping
atbytesfieldvaluewhat it holds
01kind40x04: this frame is a PING.
18nonce9Echoed back in the pong.
STREAM_ITEM · 21 bytes · golden vector stream-item
atbytesfieldvaluewhat it holds
01kind60x06: this frame is a STREAM_ITEM.
18call_id7The stream: the call_id of the request that opened it.
98sequence3The item's position in the stream, from zero.
172codec1The codec that produced body.
192body08 01The encoded item.
STREAM_END, a failed stream · 26 bytes · golden vector stream-end-failed
atbytesfieldvaluewhat it holds
01kind70x07: this frame is a STREAM_END.
18call_id7The stream.
98items1How many items the producer sent.
171status130 for a normal end, else a status code: 13 is a stream that its producer failed.
188detail5With status 13, the application's code.
STREAM_ACK · 17 bytes · golden vector stream-ack
atbytesfieldvaluewhat it holds
01kind80x08: this frame is a STREAM_ACK.
18call_id7The stream.
98consumed128Accounted bytes of items the caller's application consumed.
STREAM_CANCEL · 9 bytes · golden vector stream-cancel
atbytesfieldvaluewhat it holds
01kind90x09: this frame is a STREAM_CANCEL.
18call_id7The 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.

codestatussinceprovesends the referencewhat the server says
1EndpointNotFoundv1NotAdmittedyesNo live endpoint holds the token.
2StaleIncarnationv1NotAdmittedyesThe reference names another incarnation of this transport.
3MethodMismatchv1NotAdmittedyesThe endpoint serves a different method.
4SchemaMismatchv1NotAdmittedyesThe endpoint serves a different contract version.
5CodecMismatchv1NotAdmittedyesThe request body uses a codec the endpoint does not accept.
6MalformedRequestv1NotAdmittednoThe request body did not decode as the registered request type.
7Overloadedv1NotAdmittednoThe endpoint's queue was full.
8BrokenPromisev1MaybeExecutednoThe handler dropped its reply handle without replying.
9ReplyTooLargev1ExecutednoThe handler's reply exceeded the frame limit of the session.
10ReplyEncodeFailedv1ExecutednoThe handler's reply could not be encoded by its codec.
11MethodNotFoundv1NotAdmittednoThe endpoint is a group that does not serve the method.
12InterfaceMismatchv1NotAdmittedyesThe endpoint serves another interface than the reference names.
13StreamFailedv1ExecutednoThe producer ended the stream with an application error code.
14StreamProtocolv1MaybeExecutednoThe other side broke the stream protocol (a regressing, excess or misaligned acknowledgement); the stream was ended.
15StreamingMismatchv1NotAdmittedyesA stream request for a unary method, or a unary request for a streaming method.
16Unauthenticatedv2NotAdmittednoThe caller is not (validly) authenticated for the endpoint (version 2).
17PermissionDeniedv2NotAdmittednoThe caller is authenticated but not allowed to call the endpoint (version 2).
18ShuttingDownv2NotAdmittednoThe 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.

proofwhat it means
NotAdmittedThe 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.
MaybeExecutedThe handler may or may not have run (the request may have been admitted, and no outcome came back). Retrying may execute it twice.
ExecutedThe 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 (see BootstrapClient);
  • the Incarnation is 128 bits drawn from the provider’s random source when a runtime starts (or supplied by the caller), so a restarted process at the same ip:port is a different incarnation and rejects references to its predecessor;
  • the EndpointToken is 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 WellKnownId token 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:

ServiceRef · 52 bytes · golden vector service
attagtypefieldvalue
01varintmethod id1701013615
62varintschema version1
83varintrequest codec1
104varintreply codec1
125varintaccess class (0 private, 1 public)1
146fixed64incarnation, high and low 64 bits72623859790382856
237fixed64incarnation, high and low 64 bits651345242494996240
328fixed64token index (the top bit marks a well-known id)3
419varinttoken generation7
4310bytesIP address, 4 or 16 bytes0a 00 01 01
4911varintport4500

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).

  • RpcInterface names an interface with an explicit InterfaceId and version; InterfaceMethod declares a method a member.
  • RpcHandle::register_group allocates a ServiceGroup; ServiceGroup::serve opens one method’s RequestStream.
  • InterfaceRef and ServiceRef are 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:

  1. ShuttingDown status 18
  2. StaleIncarnation status 2
  3. EndpointNotFound status 1
  4. InterfaceMismatch status 12
  5. MethodMismatch status 3
  6. MethodNotFound status 11
  7. SchemaMismatch status 4
  8. CodecMismatch status 5
  9. StreamingMismatch status 15
  10. Unauthenticated status 16
  11. PermissionDenied status 17
  12. Overloaded status 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 one RpcError: 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 ServiceRef travels 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, as ErrorReason::Overloaded with Execution::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::Disconnected for the consumer, SendError::Disconnected for 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’s send reserves an item’s accounted size (its whole frame, stream_item_frame_len) atomically, first come first served, and waits while W bytes 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 most W bytes and a stalled one stops the producer. Counters are cumulative, checked u64s.
  • Oversized items are refused, never parked. An item larger than the window or the session’s frame limit fails its send with SendError::TooLarge at 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’s fail, 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 ReplyStream before the request left withdraws it (never admitted); after, sends STREAM_CANCEL, and the producer’s next send (or the one waiting for credit) fails with SendError::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 becomes Failed only after connections to it kept failing for PeerPolicy::failure_detection_delay, and Available again 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 tls module, behind feature tls) 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 with SecurityConfig::admit_authenticated_peers.
  • A client is identified per request, by a credential it attaches (Credential, from a CredentialSource) and the server verifies (RequestVerifier, which the application supplies: a token format is the application’s choice) into a Principal.
  • An AccessPolicy decides, per request, whether that principal (or an anonymous caller) may call the endpoint. The default (DefaultPolicy) lets anyone who passes verification call a Public endpoint and requires a verified principal for a Private one.
  • 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.

  1. Close admission: from now on new requests from peers are refused (ErrorReason::ServerShuttingDown for them, never admitted), new calls, streams and registrations here fail with ErrorReason::Shutdown, the listener closes and nothing is dialed or re-dialed (a reliable call whose connection ends is failed, not retransmitted).
  2. 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 grace has passed.
  3. Terminate: every call still pending fails with ErrorReason::Shutdown and the execution knowledge it has (MaybeExecuted once its request left), and every connection is closed from this side (a TLS session sends its close_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.
  4. 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::Overloaded refusal 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-rpc carries 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 of moonpool_rpc::RpcStats that every runtime reports (one last time when it stops, through its moonpool_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.

In the Guide

All the extras