Skip to main content

Crate moonpool

Crate moonpool 

Source
Expand description

§Moonpool

Deterministic simulation testing for distributed systems in Rust.

Moonpool enables you to write distributed system logic once, test it with simulated networking for reproducible debugging, then deploy with real networking—all using identical application code.

Inspired by FoundationDB’s simulation testing.

§Crate Architecture

┌─────────────────────────────────────────────────┐
│           moonpool (this crate)                 │
│         Re-exports all functionality            │
├─────────────────────────────────────────────────┤
│  moonpool-transport    │    moonpool-sim        │
│  • Peer connections    │    • SimWorld runtime  │
│  • Wire format         │    • Chaos testing     │
│  • NetTransport        │    • Buggify macros    │
│  • RPC primitives      │    • Assertions        │
├─────────────────────────────────────────────────┤
│              moonpool-core                      │
│  Provider traits: Time, Task, Network, Random   │
│  Core types: UID, Endpoint, NetworkAddress      │
└─────────────────────────────────────────────────┘

§Quick Start

use moonpool::{SimulationBuilder, WorkloadTopology};

SimulationBuilder::new()
    .topology(WorkloadTopology::ClientServer { clients: 2, servers: 1 })
    .run(|ctx| async move {
        // Your distributed system workload
    });

§Which Crate to Use

Use caseCrate
Full framework (recommended)moonpool
Provider traits onlymoonpool-core
Simulation without transportmoonpool-sim
Transport without simulationmoonpool-transport

§Documentation

Modules§

chaos
Chaos testing infrastructure for deterministic fault injection. Chaos testing infrastructure for deterministic fault injection.
error
Error types for transport operations. Error types for the moonpool messaging layer.
flags
Address flags.
network
Network simulation and configuration. Network simulation and configuration.
peer
Resilient peer connection management. Resilient peer connection management.
providers
Provider implementations for simulation. Provider implementations for simulation.
rpc
RPC layer with typed request/response patterns. FDB-style static messaging with fixed endpoints.
runner
Simulation runner and orchestration framework. Simulation runner and orchestration framework.
sim
Core simulation engine for deterministic testing. Core simulation engine for deterministic testing.
wire
Wire format with CRC32C checksums. Wire format for packet serialization.

Macros§

always_assert
Assert that a condition is always true, panicking on failure.
buggify
Buggify with 25% probability
buggify_with_prob
Buggify with custom probability
sometimes_assert
Assert a condition that should sometimes be true, tracking the success rate.

Structs§

AssertionStats
Statistics for a tracked assertion.
ChaosConfiguration
Configuration for chaos injection in simulations.
Endpoint
Endpoint = Address + Token.
EndpointMap
Maps endpoint tokens to message receivers.
EventQueue
A priority queue for scheduling events in chronological order.
JsonCodec
JSON codec using serde_json.
NetNotifiedQueue
Type-safe message queue with async notification.
NetTransport
Central transport coordinator (FDB NetTransport equivalent).
NetTransportBuilder
Builder for NetTransport that eliminates common footguns.
NetworkAddress
Network address (IPv4/IPv6 + port + flags).
NetworkConfiguration
Configuration for network simulation parameters
PacketHeader
Packet header for wire format.
Peer
A resilient peer that manages connections to a remote address.
PeerConfig
Configuration for peer behavior and reconnection parameters.
PeerMetrics
Metrics and state information for a peer connection.
ReplyFuture
Future that resolves when a reply is received from the server.
ReplyPromise
Promise for sending a reply to a request.
RequestEnvelope
Envelope wrapping a request with its reply endpoint.
RequestStream
Stream for receiving typed requests with reply promises.
ScheduledEvent
An event scheduled for execution at a specific simulation time.
SimNetworkProvider
Simulated networking implementation
SimProviders
Simulation providers bundle for deterministic testing.
SimRandomProvider
Random provider for simulation that uses the thread-local deterministic RNG.
SimTimeProvider
Simulation time provider that integrates with SimWorld.
SimWorld
The central simulation coordinator that manages time and event processing.
SimulationBuilder
Builder pattern for configuring and running simulation experiments.
SimulationMetrics
Core metrics collected during a simulation run.
SimulationReport
Comprehensive report of a simulation run with statistical analysis.
SleepFuture
Future that completes after a specified simulation time duration.
StateRegistry
Registry for actor state during simulation.
TokioNetworkProvider
Real Tokio networking implementation.
TokioProviders
Production providers using Tokio runtime.
TokioRandomProvider
Production random provider using thread-local RNG.
TokioReport
Report generated after running workloads with TokioRunner.
TokioRunner
Builder for executing workloads with real Tokio implementations.
TokioTaskProvider
Tokio-based task provider using spawn_local for single-threaded execution.
TokioTcpListener
Wrapper for Tokio TcpListener to implement our trait.
TokioTimeProvider
Real time provider using Tokio’s time facilities.
UID
128-bit unique identifier.
WeakSimWorld
A weak reference to a simulation world.
WorkloadTopology
Topology information provided to workloads to understand the simulation network.

Enums§

CodecError
Error type for codec operations.
ConnectFailureMode
Connection establishment failure mode for fault injection.
ConnectionStateChange
Connection state changes
Event
Events that can be scheduled in the simulation.
IterationControl
Configuration for how many iterations a simulation should run.
MessagingError
Errors that can occur in the messaging layer.
NetworkAddressParseError
Error parsing a network address from string.
NetworkOperation
Network data operations
PeerError
Errors that can occur during peer operations.
ReplyError
Errors that can occur during request-response operations.
RpcError
Unified error type for RPC operations.
SimulationError
Errors that can occur during simulation operations.
WellKnownToken
Well-known endpoint tokens.
WireError
Wire format error types.

Constants§

HEADER_SIZE
Header size: 4 (length) + 4 (checksum) + 16 (token) = 24 bytes.
MAX_PAYLOAD_SIZE
Maximum payload size (1MB).
WELL_KNOWN_RESERVED_COUNT
Number of reserved well-known token slots.

Traits§

MessageCodec
Pluggable message serialization format.
MessageReceiver
Trait for receiving deserialized messages from the transport layer.
NetworkProvider
Provider trait for creating network connections and listeners.
Providers
Bundle of all provider types for a runtime environment.
RandomProvider
Provider trait for random number generation.
TaskProvider
Provider for spawning local tasks in single-threaded context.
TcpListenerTrait
Trait for TCP listeners that can accept connections.
TimeProvider
Provider trait for time operations.

Functions§

buggify_init
Initialize buggify for simulation run
buggify_reset
Reset/disable buggify
deserialize_packet
Deserialize a packet, validating checksum.
get_assertion_results
Get current assertion statistics for all tracked assertions.
get_current_sim_seed
Get the current simulation seed.
method_endpoint
Generate method endpoint from base endpoint and index.
method_uid
Generate UID for a specific interface method.
panic_on_assertion_violations
Check assertion validation and panic if violations are found.
reset_assertion_results
Reset all assertion statistics to empty state.
reset_sim_rng
Reset the thread-local simulation RNG to a fresh state.
sample_duration
Sample a random duration from a range
send_request
Send a typed request and return a future for the response.
serialize_packet
Serialize a packet with token and payload.
set_sim_seed
Set the seed for the thread-local simulation RNG.
sim_random
Generate a random value using the thread-local simulation RNG.
sim_random_range
Generate a random value within a specified range using the thread-local simulation RNG.
sim_random_range_or_default
Generate a random value within the given range, returning the start value if the range is empty.
try_deserialize_packet
Try to deserialize from a buffer that may contain partial data.
validate_assertion_contracts
Validate that all sometimes_assert! assertions actually behave as “sometimes”.

Type Aliases§

InvariantCheck
Type alias for invariant check functions.
PeerReceiver
Type alias for the peer receiver channel. Used when taking ownership via take_receiver().
SimulationResult
A type alias for Result<T, SimulationError>.

Attribute Macros§

interface
Attribute macro for FDB-style Interface pattern.