File: README.md
ractor
Pronounced rak-ter
A pure-Rust actor framework. Inspired from Erlang's gen_server, with the speed + performance of Rust!
Runtime semantics
See the detailed runtime semantics and guarantees in docs/runtime-semantics.md for priority channels, supervision semantics, RPC/cluster behaviors, and recommended best practices: Semantics
Updates
- Website: Ractor has a companion website for more detailed getting-started guides along with some best practices and is updated regularly. Api docs will still be available at docs.rs however this will be a supplimentary site for
ractor. Try it out! https://slawlor.github.io/ractor/ - RustConf'24 Ractor was a key part of a presentation at RustConf'24. It's used as the basis for Meta's Rust thrift overload protection scheme. The presentation's slides are available here.
About
ractor tries to solve the problem of building and maintaining an Erlang-like actor framework in Rust. It gives
a set of generic primitives and helps automate the supervision tree and management of our actors along with the traditional actor message processing logic. It was originally designed to use the tokio runtime, however does now support the async-std runtime.
ractor is a modern actor framework written in 100% Rust.
Additionally ractor has a companion library, ractor_cluster which is needed for ractor to be deployed in a distributed (cluster-like) scenario. ractor_cluster shouldn't be considered production ready, but it is relatively stable and we'd love your feedback!
Why ractor?
There are other actor frameworks written in Rust (Actix, riker, or just actors in Tokio) plus a bunch of others like this list compiled on this Reddit post.
Ractor tries to be different by modelling more on a pure Erlang gen_server. This means that each actor can also simply be a supervisor to other actors with no additional cost (simply link them together!). Additionally we're aiming to maintain close logic with Erlang's patterns, as they work quite well and are well utilized in the industry.
Additionally we wrote ractor without building on some kind of "Runtime" or "System" which needs to be spawned. Actors can be run independently, in conjunction with other basic tokio runtimes with little additional overhead.
We currently have full support for:
- Single-threaded message processing
- Actor supervision tree
- Remote procedure calls to actors in the
rpcmodule - Timers in the
timemodule - Named actor registry (
registrymodule) from Erlang'sRegistered processes - Process groups (
ractor::pgmodule) from Erlang'spgmodule
On our roadmap is to add more of the Erlang functionality including potentially a distributed actor cluster.
Performance
Actors in ractor are generally quite lightweight and there are benchmarks which you are welcome to run on your own host system with:
cargo bench -p ractorFurther performance improvements are being tracked in #262
Installation
Install ractor by adding the following to your Cargo.toml dependencies.
[dependencies]
ractor = "0.16"The minimum supported Rust version (MSRV) of ractor is 1.85.
Features
ractor exposes the following features:
cluster, which exposes various functionality required forractor_clusterto set up and manage a cluster of actors over a network link. This is work-in-progress and is being tracked in #16.async-std, which enables usage ofasync-std's asynchronous runtime instead of thetokioruntime. Howevertokiowith thesyncfeature remains a dependency because we utilize the messaging synchronization primatives fromtokioregardless of runtime as they are not specific to thetokioruntime. This work is tracked in #173. You can remove default features to "minimize" the tokio dependencies to just the synchronization primatives.monitors, Adds support for an erlang-style monitoring api which is an alternative to direct linkage. Akin to Process Monitorsmessage_span_propogation, Propagates the span through the message between actors to keep tracing context.actor-macros, which provides opt-in attribute macros for defining actors with one small method per message variant. See the actor macro guide.
Working with Actors
Actors in ractor are very lightweight and can be treated as thread-safe. Each actor will only call one of its handler functions at a time, and they will
never be executed in parallel. Following the actor model leads to microservices with well-defined state and processing logic.
Reducing actor boilerplate
Enable the actor-macros feature to generate the Actor implementation from an inherent
implementation whose methods describe the messages they handle:
[dependencies]
ractor = { version = "0.16", features = ["actor-macros"] }struct Counter;
enum CounterMessage {
Add(u64),
Read(ractor::RpcReplyPort<u64>),
}
#[ractor::actor(message = CounterMessage, state = u64)]
impl Counter {
async fn pre_start(
&self,
_myself: ractor::ActorRef<CounterMessage>,
_arguments: (),
) -> Result<u64, ractor::ActorProcessingErr> {
Ok(0)
}
#[ractor::message(CounterMessage::Add(amount))]
fn add(&self, amount: u64, state: &mut u64) {
*state += amount;
}
#[ractor::rpc(CounterMessage::Read(reply))]
fn read(&self, state: &u64) -> u64 {
*state
}
}When focused message or RPC handlers are present, their generated dispatch is exhaustive, so
adding an unhandled enum variant is a compile error. With neither focused handlers nor a rawhandle, the actor inherits the trait's no-op message handler; this supports lifecycle- and
supervision-only actors. For local actors, message = enum CounterMessage can also generate the
enum from handler patterns and parameter types, copying handler documentation comments to the
generated variants. Focused #[ractor::supervision(...)] methods provide the same dispatch style
for supervision events, while #[ractor::rpc(...)] sends a handler's return value through the
omitted reply-port binding. The explicit trait-based API remains available when its flexibility is
preferable. See the guide and the actor_macro
example for the supported method shapes.
An example ping-pong actor might be the following
use ractor::{async_trait, cast, Actor, ActorProcessingErr, ActorRef};
/// [PingPong] is a basic actor that will print
/// ping..pong.. repeatedly until some exit
/// condition is met (a counter hits 10). Then
/// it will exit
pub struct PingPong;
/// This is the types of message [PingPong] supports
#[derive(Debug, Clone)]
pub enum Message {
Ping,
Pong,
}
impl Message {
// retrieve the next message in the sequence
fn next(&self) -> Self {
match self {
Self::Ping => Self::Pong,
Self::Pong => Self::Ping,
}
}
// print out this message
fn print(&self) {
match self {
Self::Ping => print!("ping.."),
Self::Pong => print!("pong.."),
}
}
}
#[async_trait]
// the implementation of our actor's "logic"
impl Actor for PingPong {
// An actor has a message type
type Msg = Message;
// and (optionally) internal state
type State = u8;
// Startup initialization args
type Arguments = ();
// Initially we need to create our state, and potentially
// start some internal processing (by posting a message for
// example)
async fn pre_start(
&self,
myself: ActorRef<Self::Msg>,
_: (),
) -> Result<Self::State, ActorProcessingErr> {
// startup the event processing
cast!(myself, Message::Ping)?;
// create the initial state
Ok(0u8)
}
// This is our main message handler
async fn handle(
&self,
myself: ActorRef<Self::Msg>,
message: Self::Msg,
state: &mut Self::State,
) -> Result<(), ActorProcessingErr> {
if *state < 10u8 {
message.print();
cast!(myself, message.next())?;
*state += 1;
} else {
println!();
myself.stop(None);
// don't send another message, rather stop the agent after 10 iterations
}
Ok(())
}
}
#[tokio::main]
async fn main() {
let (_actor, handle) = Actor::spawn(None, PingPong, ())
.await
.expect("Failed to start ping-pong actor");
handle
.await
.expect("Ping-pong actor failed to exit properly");
}which will output
$ cargo run
ping..pong..ping..pong..ping..pong..ping..pong..ping..pong..
$Messaging actors
The means of communication between actors is that they pass messages to each other. A developer can define any message type which is Send + 'static and it
will be supported by ractor. There are 4 concurrent message types, which are listened to in priority. They are
- Signals: Signals are the highest-priority of all and will interrupt the actor wherever processing currently is (this includes terminating async work). There
is only 1 signal today, which isSignal::Kill, and it immediately terminates all work. This includes message processing or supervision event processing. - Stop: There is also the pre-defined stop signal. You can give a "stop reason" if you want, but it's optional. Stop is a graceful exit, meaning currently executing async work will complete, and on the next message processing iteration Stop will take priority over future supervision events or regular messages. It will not terminate currently executing work, regardless of the provided reason.
- SupervisionEvent: Supervision events are messages from child actors to their supervisors in the event of their startup, death, and/or unhandled panic. Supervision events are how an actor's supervisor(parent) or peer monitors are notified of events of their children/peers and can handle lifetime events for them. If you set
panic = 'abort'in yourCargo.toml, panics will start cause program termination and not be caught in the supervision flow. - Messages: Regular, user-defined, messages are the last channel of communication to actors. They are the lowest priority of the 4 message types and denote general actor work. The first
3 messages types (signals, stop, supervision) are generally quiet unless it's a lifecycle event for the actor, but this channel is the "work" channel doing what your actor wants to do!
Ractor in distributed clusters
Ractor actors can also be used to build a distributed pool of actors, similar to Erlang's EPMD which manages inter-node connections + node naming. In our implementation, we have ractor_cluster in order to facilitate distributed ractor actors.
ractor_cluster has a single main type in it, namely the NodeServer which represents a host of a node() process. It additionally has some macros and a procedural macros to facilitate developer efficiency when building distributed actors. The NodeServer is responsible for
- Managing all incoming and outgoing
NodeSessionactors which represent a remote node connected to this host. - Managing the
TcpListenerwhich hosts the server socket to accept incoming session requests.
The bulk of the logic for node interconnections however is held in the NodeSession which manages
- The underlying TCP connection managing reading and writing to the stream.
- The authentication between this node and the connection to the peer
- Managing actor lifecycle for actors spawned on the remote system.
- Transmitting all inter-actor messages between nodes.
- Managing PG group synchronization
etc..
The NodeSession makes local actors available on a remote system by spawning RemoteActors which are essentially untyped actors that only handle serialized messages, leaving message deserialization up to the originating system. It also keeps track of pending RPC requests, to match request to response upon reply. There are special extension points in ractor which are added to specifically support RemoteActors that aren't generally meant to be used outside of the standard
Actor::spawn(Some("name".to_string()), MyActor).awaitpattern.
Designing remote-supported actors
Note not all actors are created equal. Actors need to support having their message types sent over the network link. This is done by overriding specific methods of the ractor::Message trait all messages need to support. Due to the lack of specialization support in Rust, if you choose to use ractor_cluster you'll need to derive the ractor::Message trait for all message types in your crate. However to support this, we have a few procedural macros to make this a more painless process
Deriving the basic Message trait for in-process only actors
Many actors are going to be local-only and have no need sending messages over the network link. This is the most basic scenario and in this case the default ractor::Message trait implementation is fine. You can derive it quickly with:
use ractor_cluster::RactorMessage;
use ractor::RpcReplyPort;
#[derive(RactorMessage)]
enum MyBasicMessageType {
Cast1(String, u64),
Call1(u8, i64, RpcReplyPort<Vec<String>>),
}This will implement the default ractor::Message trait for you without you having to write it out by hand.
Deriving the network serializable message trait for remote actors
If you want your actor to support remoting, then you should use a different derive statement, namely:
use ractor_cluster::RactorClusterMessage;
use ractor::RpcReplyPort;
#[derive(RactorClusterMessage)]
enum MyBasicMessageType {
Cast1(String, u64),
#[rpc]
Call1(u8, i64, RpcReplyPort<Vec<String>>),
}which adds a significant amount of underlying boilerplate (take a look yourself with cargo expand) for the implementation. But the short answer is, each enum variant needs to serialize to a byte array of arguments, a variant name, and if it's an RPC give a port that receives a byte array and de-serialize the reply back. Each of the types inside of either the arguments or reply type need to implement the ractor_cluster::BytesConvertable trait which just says this value can be written to a byte array and decoded from a byte array. If you're using prost for your message type definitions (protobuf), we have a macro to auto-implement this for your types.
ractor_cluster::derive_serialization_for_prost_type! {MyProtobufType}Besides that, just write your actor as you would. The actor itself will live where you define it and will be capable of receiving messages sent over the network link from other clusters!
Differences between an actor's "state" and `self`
Actors can (but don't need to!) have internal state. In order to facilitate this ractor gives implementors of the Actor trait the ability to define the state type for an actor. The actor's pre_start routine is what initializes and sets up this state. You can imagine doing things like
- Opening a network socket + storing the
TcpListenerin the state - Setting up a database connection + authenticating to the DB
- Initializing basic state variables (counters, stats, whatever)
Because of this and the possibility that some of these operations are fallible, pre_start captures panic's in the method during the initialization and returns them to the caller of Actor::spawn.
When designing ractor, we made the explicit decision to make a separate state type for an actor, rather than passing around a mutable self reference. The reason for this is that if we were to use a &mut self reference, creation + instantiation of the Self struct would be outside of the actor's specification (i.e. not in pre_start) and the safety it gives would be potentially lost, causing potential crashes in the caller when it maybe shouldn't.
Lastly is that we would need to change some of the ownership properties that ractor is currently based on to pass an owned self in each call, returning a Self reference which seems clunky in this context.
In the current realization an actor's self is passed as a read-only reference which shouldn't ideally contain state information, but could contain configuration / startup information if you want. However there is also Arguments to each Actor which allows passing owned values to the state of an actor. In an ideal world, all actor structs would be empty with no stored values.
Contributors
The original author of ractor is Sean Lawlor (@slawlor). To learn more about contributing to ractor please see CONTRIBUTING.md.
License
This project is licensed under MIT.
File: CLAUDE.md
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Mandatory Pre-Completion Checks
Before declaring any code change complete, you MUST run the following and resolve ALL errors and warnings:
# Format all code (fix in place)
cargo fmt --all
# Run clippy with strict settings โ ALL warnings must be resolved
cargo clippy --all -- -D clippy::all -D warningsDo NOT skip these steps. Do NOT declare a task done if either command produces errors or warnings. Fix any issues and re-run until clean.
Overview
Ractor is a pure-Rust actor framework inspired by Erlang's gen_server, providing lightweight actors with single-threaded message processing, supervision trees, and optional distributed clustering capabilities.
Workspace Structure
This is a Cargo workspace with multiple crates:
- ractor: Core actor framework library
- ractor_cluster: Distributed cluster support (experimental)
- ractor_cluster_derive: Procedural macros for cluster message serialization
- ractor_cluster_integration_tests: Integration tests for clustering
- ractor_example_entry_proc: Example entry point procedures
- ractor_playground: Playground/experimentation crate
- xtask: Build/development automation tasks
Build and Test Commands
Running Tests
# Run all tests
cargo test
# Run tests for a specific package
cargo test --package ractor
cargo test --package ractor_cluster
# Run tests with specific feature flags
cargo test --package ractor --features cluster
cargo test --package ractor --features async-std,message_span_propogation --no-default-features
cargo test --package ractor --features monitors
cargo test --package ractor --features blanket_serde
# Run a specific test
cargo test --package ractor --test <test_name>
cargo test --package ractor <test_name>CI Feature Flag Matrix
To reproduce a CI failure locally, find the matching row and run cargo test --package <flags>:
| CI Job Name | Package | Flags |
|---|---|---|
| Run the default tests | ractor | (none) |
| Test ractor with async-trait | ractor | -F async-trait |
| Test ractor without span propogation | ractor | --no-default-features -F tokio_runtime |
Test ractor with the cluster feature |
ractor | -F cluster |
Test ractor with the blanket_serde feature |
ractor | -F blanket_serde |
| Test ractor with async-std runtime | ractor | --no-default-features -F async-std,message_span_propogation |
| Test ractor with async-std runtime but no span propagation | ractor | --no-default-features -F async-std |
| Test ractor with async-std runtime and async-trait | ractor | --no-default-features -F async-std,async-trait |
| Test ractor_cluster with native async traits | ractor_cluster | (none) |
| Test ractor_cluster with async_trait | ractor_cluster | -F async-trait |
| Test ractor with the monitor API | ractor | -F monitors |
| Test ractor with output-port-v2 feature | ractor | -F output-port-v2 |
| Test ractor without output-port-v2 feature (explicit) | ractor | --no-default-features -F tokio_runtime,message_span_propogation |
CI also runs: clippy, rustfmt --check, cargo doc --lib -r, and cargo bench --no-run.
Running Benchmarks
# Run benchmarks
cargo bench -p ractor
# Compile benchmarks without running
cargo bench --no-runLinting and Formatting
# Run clippy
cargo clippy --all -- -D clippy::all -D warnings
# Run rustfmt
cargo fmt --all
# Check formatting without modifying
cargo fmt --all -- --checkDocumentation
# Build documentation
cargo doc --lib
# Build documentation in release mode
cargo doc --lib -rArchitecture
Core Actor Model
Ractor implements the actor model with these key components:
Actor: The trait defining actor behavior (
Actortrait forSendactors,ThreadLocalActorfor!Sendactors)pre_start: Initialize actor state (fallible, errors returned to spawner)post_start: Post-initialization hookhandle: Process incoming messageshandle_supervisor_evt: Handle supervision events from childrenpost_stop: Cleanup on shutdown
ActorCell: Reference-counted primitive representing an actor's communication channels
- Contains message ports (signal, stop, supervision, message)
- Manages actor lifecycle status (Unstarted, Starting, Running, Upgrading, Draining, Stopping, Stopped)
ActorRef
: Strongly-typed wrapper over ActorCell for type-safe communication - Primary interface for sending messages to actors
- Derefs to ActorCell for access to lower-level operations
Message Types
Without cluster feature: blanket impl<T: Any + Send + Sized + 'static> Message for T โ any Send + 'static type works as a message with zero boilerplate.
With cluster feature: the blanket impl is replaced by one requiring BytesConvertable. For enum message types, use derive macros:
#[derive(RactorMessage)]โ local-only actors (marks as non-serializable)#[derive(RactorClusterMessage)]โ remote-capable actors (generates serialization). Mark RPC variants with#[rpc].
RactorClusterMessage supports:
- Both tuple-style (
Variant(A, B)) and struct-style (Variant { a: A, b: B }) fields RpcReplyPort<T>at any position in#[rpc]variants (detected by type scan, not position)- Exactly one
RpcReplyPort<T>per#[rpc]variant (compile error on 0 or 2+) - Using
RpcReplyPortwithout#[rpc]produces a helpful compile error
The wire format is purely positional โ field names and port position don't affect serialization. Internal codegen variables are __-prefixed to avoid collisions with user field names.
See ractor/src/message.rs for trait definition and ractor_cluster_derive/ for the proc macros.
Message Priority System
Messages are processed in strict priority order (see docs/runtime-semantics.md):
- Signals (highest): Immediate termination (e.g.,
Signal::Kill) - Stop: Graceful shutdown request
- SupervisionEvent: Child actor lifecycle notifications
- Messages (lowest): User-defined work messages
Actor State vs Self
self: Read-only reference containing configuration/constants (ideally empty)State: Mutable state managed by the actor, initialized inpre_start
Supervision
- Actors form supervision trees through linking
- Parent actors receive
SupervisionEventmessages on child lifecycle changes - Panics in message handlers are caught and reported to supervisors (unless
panic = "abort") - Panics in
pre_startreturn errors to the spawner without starting the actor
DerivedActorRef
DerivedActorRef<TFrom> (ractor/src/actor/derived_actor.rs) wraps an ActorCell to accept a subset of an actor's message type via From conversion. This provides interface isolation โ callers only see the subset type, not the full message enum. Obtain one via actor_ref.get_derived::<SubsetType>(). Requires impl From<SubsetType> for FullMsg and impl TryFrom<FullMsg> for SubsetType.
Process Groups (pg)
ractor::pg (ractor/src/pg.rs) provides Erlang-style named process groups โ global, scope-aware collections of actors.
pg::join(group, actors)/pg::leave(group, actors)โ add/remove actors (actors auto-leave on shutdown)pg::get_members(group)/pg::get_local_members(group)โ retrieve group memberspg::which_groups()/pg::which_scopes()โ enumerate registered namespg::monitor(group, actor)/pg::demonitor(group, actor_id)โ subscribe toSupervisionEvent::ProcessGroupChanged- Scoped variants:
join_scoped,get_scoped_members,monitor_scope,demonitor_scope
Named Registry
ractor::registry (ractor/src/registry.rs) provides actor lookup by name.
- Actors with a
Some(name)passed toActor::spawnare auto-registered and auto-unregistered on drop registry::where_is(name) -> Option<ActorCell>โ look up by nameregistry::registered() -> Vec<ActorName>โ list all registered names- With
clusterfeature:pid_registrysub-module addswhere_is_pidandPidLifecycleEvent
Factory Pattern
The factory module provides worker pools for parallel job processing:
- Worker: Trait for defining job processing logic
- Factory: Manages a pool of workers with configurable routing
- Routing modes: KeyPersistent, StickyQueuer, Queuer, RoundRobin, Custom
- Queueing: DefaultQueue, PriorityQueue
- Factory handles worker lifecycle, automatically restarting failed workers
Thread-Local Actors
The thread_local module supports !Send types:
- Must use Tokio runtime with
rtfeature (relies ontokio::task::LocalSet) - Use
ThreadLocalActortrait instead ofActor - Spawn with
ractor::spawn_local()andThreadLocalActorSpawner - State does not need to be
SendorSync
Feature Flags
ractor crate features:
cluster: Exposes functionality forractor_cluster(network-distributed actors)async-std: Use async-std runtime instead of tokio (tokio sync primitives still used)monitors: Erlang-style monitoring API (alternative to direct linking)message_span_propogation: Propagate tracing spans through actor messagestokio_runtime: Tokio runtime support (default)blanket_serde: Serde serialization supportoutput-port-v2: Experimental output port v2async-trait: Use async-trait crate instead of native async traits
Default features: tokio_runtime, message_span_propogation
Cluster Support (Experimental)
- NodeServer: Manages node connections and incoming sessions
- NodeSession: Handles TCP connections, authentication, message routing, and remote actor lifecycle
- RemoteActor: Untyped actor handling serialized messages from remote nodes
- See
ractor_cluster/src/node/for implementation andractor_cluster_derive/for message serialization macros
Important Implementation Notes
Runtime Requirements
- MSRV: Rust 1.85
- Thread-local actors REQUIRE tokio runtime with
rtfeature - WASM support available (target
wasm32-unknown-unknown)
Testing
Test Organization
- Unit tests:
#[cfg(test)] mod testswithin each module - Integration tests:
ractor_cluster_integration_tests/crate - Some tests require
serial_testcrate for sequential execution
Test Utilities
ractor/src/common_test.rs provides helpers used throughout the test suite:
periodic_check(closure, timeout)โ polls aFn() -> boolevery 50ms until true or timeout (then asserts)periodic_async_check(closure, timeout)โ same but forasync Fn() -> Future<Output = bool>
Key Source Files
Critical files for understanding the architecture:
ractor/src/actor.rs: Core Actor trait and spawn logicractor/src/actor/actor_cell.rs: ActorCell and ActorPortSet (message multiplexing)ractor/src/actor/actor_ref.rs: Strongly-typed ActorRef wrapperractor/src/actor/derived_actor.rs: DerivedActorRef for interface isolationractor/src/message.rs: Message trait definition and blanket implsractor/src/concurrency.rs: Runtime-abstracted channel/timer primitives (tokio vs async-std)ractor/src/pg.rs: Process groups (named actor groups)ractor/src/registry.rs: Named actor registryractor/src/factory.rs: Worker pool patternractor/src/thread_local.rs: Thread-local actor supportractor/src/common_test.rs: Test utilities (periodic_check,periodic_async_check)ractor_cluster/src/node/: NodeServer and NodeSession implementationsractor_cluster_derive/src/ir.rs: Intermediate representation (ParsedEnum, ParsedVariant, FieldStyle, VariantKind)ractor_cluster_derive/src/parse.rs: Parsing and validation of derive inputractor_cluster_derive/src/codegen.rs: Code generation forimpl Messagedocs/runtime-semantics.md: Detailed runtime guarantees and edge cases
File: CODE_COVERAGE.md
Current code coverage
Current code coverage
File: codecov.yml
codecov:
require_ci_to_pass: false
ignore:
This is the code coverage tool.
- "xtask"
Tests are not covered
- "ractor_playground"
Tests are not covered
- "ractor/examples"
Tests are not covered
- "ractor/benches"
Tests are not covered
- "ractor_cluster_integration_tests"
Protocol is all generated code and should be excluded from code coverage
- "ractor_cluster/src/protocol"
File: CONTRIBUTING.md
Contributing to this library
We want to make contributing to this project as easy and transparent as
possible.
Be respectful
Duh.
Pull Requests
We actively welcome your pull requests!
- Fork the repo and create your branch from
main. - If you've added code that should be tested, add tests.
- If you've changed APIs, update the documentation.
- Ensure the test suite passes.
Issues
We use GitHub issues to track issues.
For reported bugs, please ensure your description is clear and has sufficient instructions to be able to reproduce the issue.
For feature requests, please try to be detailed in what you'd like to see so we can address it properly!
License
By contributing to ractor, you agree that your contributions will be
licensed under the LICENSE file in the root directory of this source tree.
File: docker-compose.yml
services:
node-a:
container_name: "node-a"
build:
context: .
dockerfile: ractor_cluster_integration_tests/Dockerfile
args:
- FEATURES=${FEATURES}
image: ractor_cluster_tests:latest
networks:
- test-net
entrypoint: ''
command: ractor_cluster_integration_tests test ${A_TEST}
environment:
RUST_LOG: debug
node-b:
depends_on:
- node-a
container_name: "node-b"
build:
context: .
dockerfile: ractor_cluster_integration_tests/Dockerfile
args:
- FEATURES=${FEATURES}
image: ractor_cluster_tests:latest
networks:
- test-net
entrypoint: ''
command: ractor_cluster_integration_tests test ${B_TEST}
environment:
RUST_LOG: debug
node-c:
depends_on:
- node-b
container_name: "node-c"
build:
context: .
dockerfile: ractor_cluster_integration_tests/Dockerfile
args:
- FEATURES=${FEATURES}
image: ractor_cluster_tests:latest
networks:
- test-net
entrypoint: ''
command: ractor_cluster_integration_tests test ${C_TEST}
environment:
RUST_LOG: debug
networks:
test-net:
external: false
File: unit-tests-for-wasm32-unknown-unknown.md
Steps to run unit tests for target `wasm32-unknown-unknown`
ractor is supposed to support wasm32-unknown-unknown in browser, but unit-tests can't be executed in CI due to some known issues (see https://github.com/rustwasm/wasm-pack/issues/1424 ). Here are steps to run unit-tests manually.
Install dependencies
rustup target add wasm32-unknown-unknown
cargo install wasm-packwasm-pack is a bundler and test executor for wasm targets.
Run unit tests in browser
Build unit-tests and start web server
wasm-pack test --firefox ./ractorWait for unit-tests to be built and server started
Interactive browsers tests are now available at http://127.0.0.1:8000
Note that interactive mode is enabled because `NO_HEADLESS`
is specified in the environment of this process. Once you're
done with testing you'll need to kill this server with
Ctrl-C.Now access http://127.0.0.1:8000 in browser.
Monitor test progress in browser
running 84 tests
test factory::queues::tests::test_priority_queueing ... ok
test factory::queues::tests::test_basic_queueing ... ok
test factory::tests::dynamic_discarding::test_dynamic_dispatch_basic ... ok
test port::output::tests::output_port_subscriber_tests::test_output_port_subscriber ... ok
test tests::test_platform_sleep_works ... ok
test tests::test_error_message_extraction ... ok
test factory::ratelim::tests::test_leaky_bucket_max ... ok
test factory::ratelim::tests::test_basic_leaky_bucket ... ok
test time::tests::test_kill_after ... ok
test time::tests::test_exit_after ... ok
test time::tests::test_send_after ... ok
test time::tests::test_intervals ... ok
test actor::tests::supervisor::draining_children_will_shutdown_parent_too ... ok
test actor::tests::supervisor::draining_children_and_wait_during_parent_shutdown ... ok
test actor::tests::supervisor::stopping_children_will_shutdown_parent_too ... ok
test actor::tests::supervisor::stopping_children_and_wait_during_parent_shutdown ... ok
test actor::tests::supervisor::test_supervisor_double_link ... ok
test actor::tests::supervisor::test_supervisor_captures_dead_childs_state ... ok
test actor::tests::supervisor::instant_supervised_spawns ... ok
test actor::tests::supervisor::test_killing_a_supervisor_terminates_children ... ok
test actor::tests::supervisor::test_supervision_error_in_supervisor_handle ... ok
test actor::tests::supervisor::test_supervision_error_in_post_stop ... ok
test actor::tests::supervisor::test_supervision_error_in_handle ... ok
test actor::tests::supervisor::test_supervision_error_in_post_startup ... ok
test factory::tests::dynamic_settings::test_dynamic_settings ... ok
test pg::tests::test_scope_monitoring ... ok
test pg::tests::test_pg_monitoring ... ok
test pg::tests::test_actor_leaves_scope_manually ... ok
test pg::tests::test_actor_leaves_pg_group_manually ... ok
test pg::tests::test_actor_leaves_scope_on_shupdown ... ok
test pg::tests::test_actor_leaves_pg_group_on_shutdown ... ok
test pg::tests::test_multiple_groups_in_multiple_scopes ... ok
test pg::tests::test_multiple_groups ... ok
test pg::tests::test_which_scoped_groups ... ok
test pg::tests::test_multiple_members_in_scoped_group ... ok
test pg::tests::test_multiple_members_in_group ... ok
test pg::tests::test_which_scopes_and_groups ... ok
test pg::tests::test_basic_group_in_named_scope ... ok
test pg::tests::test_basic_group_in_default_scope ... ok
test factory::tests::lifecycle::test_lifecycle_hooks ... ok
test factory::tests::ratelim::test_leaky_bucket_rate_limiting ... ok
test factory::tests::ratelim::test_factory_rate_limiting_custom_hash ... ok
test factory::tests::ratelim::test_factory_rate_limiting_round_robin ... ok
test factory::tests::ratelim::test_factory_rate_limiting_key_persistent ... ok
test factory::tests::ratelim::test_factory_rate_limiting_sticky_queuer ... ok
test factory::tests::ratelim::test_factory_rate_limiting_queuer ... ok
test registry::tests::test_actor_registry_unenrollment ... ok
test registry::tests::test_duplicate_registration ... ok
test registry::tests::test_basic_registation ... ok
test factory::tests::draining_requests::test_request_draining ... ok
test rpc::tests::test_multi_call ... ok
test rpc::tests::test_rpc_call_forwarding ... ok
test rpc::tests::test_rpc_call ... ok
test rpc::tests::test_rpc_cast ... ok
test port::output::tests::test_delivery ... ok
test port::output::tests::test_50_receivers ... ok
test port::output::tests::test_single_forward ... ok
test factory::tests::priority_queueing::test_basic_priority_queueing ... ok
test factory::tests::basic::test_discarding_new_records_on_queuer ... ok
test factory::tests::basic::test_stuck_workers ... ok
test factory::tests::basic::test_discarding_old_records_on_queuer ... ok
test factory::tests::basic::test_dispatch_sticky_queueing ... ok
test factory::tests::basic::test_dispatch_custom_hashing ... ok
test factory::tests::basic::test_dispatch_round_robin ... ok
test factory::tests::basic::test_dispatch_queuer ... ok
test factory::tests::basic::test_dispatch_key_persistent ... ok
test actor::tests::derived_actor_ref ... ok
test actor::tests::wait_for_death ... ok
test actor::tests::runtime_message_typing ... ok
test actor::tests::actor_drain_messages ... ok
test actor::tests::actor_post_stop_executed_before_stop_and_wait_returns ... ok
test actor::tests::actor_failing_in_spawn_err_doesnt_poison_registries ... ok
test actor::tests::kill_and_wait ... ok
test actor::tests::stop_and_wait ... ok
test actor::tests::instant_spawns ... ok
test actor::tests::test_sending_message_to_dead_actor ... ok
test actor::tests::test_sending_message_to_invalid_actor_type ... ok
test actor::tests::test_kill_terminates_supervision_work ... ok
test actor::tests::test_stop_does_not_terminate_async_work ... ok
test actor::tests::test_kill_terminates_work ... ok
test actor::tests::test_stop_higher_priority_over_messages ... ok
test actor::tests::test_error_on_start_captured ... ok
test factory::tests::dynamic_pool::test_worker_pool_adjustment_automatic ... ok
test factory::tests::dynamic_pool::test_worker_pool_adjustment_manual ... ok
test result: ok. 84 passed; 0 failed; 0 ignored; 0 filtered out; finished in 165.20sClean up
Press Ctrl + C to shutdown the web server started by wasm-pack
File: docs/actor-macros.md
Actor definition macros
The optional actor-macros feature removes the repetitive associated types and message dispatch
from an actor definition while leaving its behavior visible as ordinary Rust methods.
[dependencies]
ractor = { version = "0.16", features = ["actor-macros"] }Defining an actor
Apply #[ractor::actor] to an inherent implementation and mark each message handler with#[ractor::message]. The usual form uses an explicitly declared message enum:
use ractor::{ActorProcessingErr, ActorRef, RpcReplyPort};
struct Counter;
enum CounterMessage {
Add(i64),
Read(RpcReplyPort<i64>),
}
#[ractor::actor(
message = CounterMessage,
state = i64,
arguments = i64,
)]
impl Counter {
async fn pre_start(
&self,
_myself: ActorRef<CounterMessage>,
initial: i64,
) -> Result<i64, ActorProcessingErr> {
Ok(initial)
}
#[ractor::message(CounterMessage::Add(amount))]
fn add(&self, amount: i64, state: &mut i64) {
*state += amount;
}
#[ractor::rpc(CounterMessage::Read(reply))]
fn read(&self, state: &i64) -> i64 {
*state
}
}Either message or the generated-message form described below is required. state andarguments default to (). The macro generates theActor implementation and, when focused message or RPC handlers are present, an exhaustivematch over the message enum. Rust therefore reports a new or forgotten message variant at
compile time in focused-dispatch mode. Cargo dependency renames are detected automatically, and
non-Cargo builds default to ::ractor. The crate_path = some::path option is only necessary when
a non-Cargo build renames the dependency.
Tuple, struct, and unit variants are supported. Bindings in the attribute pattern become handler
parameters with matching names in the same order; _ can discard an unused field. Keep patterns
flat so that the method signature remains an immediate description of the message payload.
Generating local message enums
For local actors, message = [visibility] enum EnumName generates the message enum from the
handler patterns and parameter types:
struct Counter;
#[ractor::actor(
message = pub enum CounterMessage,
state = i64,
arguments = i64,
)]
impl Counter {
async fn pre_start(
&self,
_myself: ActorRef<CounterMessage>,
initial: i64,
) -> Result<i64, ActorProcessingErr> {
Ok(initial)
}
/// Add an amount to the counter.
#[ractor::message(Add { amount })]
fn add(&self, amount: i64, state: &mut i64) {
*state += amount;
}
/// Read the current counter value.
#[ractor::rpc(Read)]
fn read(&self, state: &i64) -> i64 {
*state
}
}This generates the equivalent of:
pub enum CounterMessage {
/// Add an amount to the counter.
Add { amount: i64 },
/// Read the current counter value.
Read(RpcReplyPort<i64>),
}Unit, tuple, and struct variants are supported. Every generated field must have a named binding so
the macro can find its type; _ fields are therefore only supported when using an explicit enum.
The optional visibility defaults to private and can be any normal Rust visibility, such aspub(crate). Generated enums currently do not support generic actor implementations.
Textual documentation comments (///, /** ... */, and #[doc = ...]) on message and RPC
handlers are copied to the corresponding generated variants while remaining on the methods.
Conditional cfg and textual documentation attributes retain their structure. Other method
attributes are not copied, and explicit message enums remain entirely caller-owned. Copied links
and code examples are documented in the enum variant's context, so write them as message
documentation rather than method-specific implementation notes.
The unit-form RPC attribute above describes a request with no payload. The generated enum still
contains the reply port, so Read becomes Read(RpcReplyPort). A tuple or struct RPC pattern
can instead name the reply binding explicitly, as described below.
Generated-message mode deliberately does not add cluster serialization derives or define a wire
contract. Continue using an explicit message enum for remotely serializable actors. In a build with
the cluster feature, a generated enum used only for local messaging can opt into Message with a
manual implementation:
#[cfg(feature = "cluster")]
impl ractor::Message for CounterMessage {}Handler methods
A generated handler can be synchronous or asynchronous and has this shape:
&self, [ActorRef<Message>], [bound message fields...], [&State | &mut State]The actor reference and state parameters are optional. Use &State for read-only access or&mut State to update state. A handler with no explicit return type (or -> ()) is infallible. A
handler with an explicit non-unit return type is propagated through Actor::handle with ?, so it
must support that operator; Result is the usual choice.
Lifecycle hooks such as pre_start, post_start, handle_supervisor_evt, and post_stop can be
written with their normal trait signatures inside the same implementation. If both state and
arguments are (), an omitted pre_start defaults to Ok(()); otherwise it is required.
For actors that need custom dispatch, define the normal handle method instead of any#[ractor::message] or #[ractor::rpc] methods. Raw handle and focused handlers are
intentionally mutually exclusive, keeping the dispatch path unambiguous.
An actor may also omit both forms. In that case the macro emits no handle method and inherits
the actor trait's no-op default. This is useful for actors that only run lifecycle hooks or process
focused #[ractor::supervision(...)] events. The message option is still required to select the
actor's message type; message = enum EmptyMessage produces an empty local enum when there are no
focused message or RPC handlers.
RPC handlers
Use #[ractor::rpc] when a message contains an RpcReplyPort and the handler should return its
reply directly. Exactly one named binding from the pattern must be absent from the method
parameters. That binding is the reply port; all other bindings follow the same ordering and
optional actor-reference/state rules as one-way message handlers:
enum StoreMessage {
Get {
key: String,
reply: RpcReplyPort<Option<String>>,
},
AddAndRead(i64, RpcReplyPort<i64>, i64),
}
#[ractor::rpc(StoreMessage::Get { key, reply })]
async fn get(&self, key: String, state: &StoreState) -> Option<String> {
state.get(&key).cloned()
}
#[ractor::rpc(StoreMessage::AddAndRead(left, reply, right))]
fn add_and_read(&self, left: i64, right: i64, state: &StoreState) -> i64 {
left + right + state.offset
}The reply port may occur at any tuple or struct field position. A unit pattern such as#[ractor::rpc(StoreMessage::Status)] is shorthand for an RPC with no request fields; the
explicit enum must still define Status(RpcReplyPort<Reply>). For generated message enums, the
macro adds that field automatically.
The call! and call_t! convenience forms place the reply port after their supplied tuple
arguments. For a middle-position port or a struct variant, use ActorRef::call with a closure so
the message construction remains explicit:
let result = store
.call(
|reply| StoreMessage::AddAndRead(20, reply, 22),
Some(ractor::concurrency::Duration::from_millis(100)),
)
.await?;
let value = store
.call(
|reply| StoreMessage::Get {
key: "answer".to_owned(),
reply,
},
Some(ractor::concurrency::Duration::from_millis(100)),
)
.await?;By default, the handler's complete return type is the reply type. This is intentional: a domain
result such as Result<Value, DomainError> is sent to the caller unchanged. Reply types must be
concrete; impl Trait cannot appear within them because generated message fields and reply ports
must be able to name the type.
#[ractor::rpc(StoreMessage::Validate(reply))]
fn validate(&self, state: &StoreState) -> Result<Value, DomainError> {
state.validate()
}To propagate an actor-processing error from the generated handle method instead, specify the
successful reply type explicitly. The generated dispatch applies ? to the handler call and only
sends the successful value:
#[ractor::rpc(StoreMessage::Read(reply), reply = Value)]
async fn read(&self, state: &StoreState) -> Result<Value, ActorProcessingErr> {
state.read().await
}Failure to send because the caller dropped its receiver is ignored and does not fail the actor.
Use an ordinary #[ractor::message] handler when code needs to inspect, retain, forward, or send
through the reply port manually.
Supervision handlers
Supervision events can be split into focused methods in the same way as actor messages:
#[ractor::supervision(SupervisionEvent::ActorStarted(child))]
fn child_started(&self, child: ActorCell, state: &mut SupervisorState) {
state.children.insert(child.get_id());
}
#[ractor::supervision(SupervisionEvent::ActorFailed(child, error))]
async fn child_failed(
&self,
myself: ActorRef<SupervisorMessage>,
child: ActorCell,
error: ActorProcessingErr,
state: &mut SupervisorState,
) -> Result<(), ActorProcessingErr> {
// Apply the supervisor's restart policy.
Ok(())
}Supervision handlers may be synchronous or asynchronous, may return a fallible result, and may
take an optional leading actor reference and trailing state reference. Events matched by a handler
are fully handled by that method. Unmatched events retain Ractor's default behavior, including
stopping the supervisor after an unhandled child termination or failure.
A raw handle_supervisor_evt method remains available for custom dispatch, but cannot be combined
with #[ractor::supervision(...)] methods in the same actor implementation.
Thread-local and cluster actors
Add thread_local to generate a ThreadLocalActor implementation:
#[derive(Default)]
struct UiActor;
#[ractor::actor(thread_local, message = UiMessage, state = UiState)]
impl UiActor {
// lifecycle hooks and #[ractor::message(...)] handlers
}The macro only defines actor behavior. Cluster wire compatibility remains an explicit property of
the message type: continue deriving RactorMessage for local-only cluster builds orRactorClusterMessage for remotely serializable messages. A focused actor#[ractor::rpc(...)] handler does not generate or alter the enum's cluster #[rpc] metadata,
serialization, or wire contract; those remain on the explicit message enum.
See the complete actor_macro example.
File: docs/advanced_benchmarks.md
Advanced Benchmarks for Ractor Performance Analysis
Overview
This document describes the advanced benchmark suite designed to provide deeper insights into Ractor's performance characteristics beyond the standard benchmarks.
Benchmark Categories
1. Message Size Distribution (`message_size_distribution`)
Purpose: Understand how message size affects performance and identify allocation overhead.
What it tests:
- Message processing throughput for sizes: 1B, 8B, 16B, 32B, 64B, 128B, 256B, 1KB
- Each benchmark sends 10,000 messages and measures end-to-end processing time
- Uses
Throughput::Bytesto show MB/s for comparison
Why it's useful:
- Identifies optimal message sizes - Shows where heap allocation overhead becomes significant
- Validates SBO threshold - If SBO were viable, would show which size threshold (24B, 32B, 48B) gives best results
- Cache effects - Larger messages may show degradation due to cache misses
- Baseline for optimization - Establishes cost model for different message types
Expected insights:
- Small messages (โค16B): Should be fastest per message
- Medium messages (32-64B): Likely sweet spot for throughput
- Large messages (โฅ256B): May show cache/allocation overhead
How to interpret results:
message_size_distribution/8 time: [150 ns] throughput: [533 MB/s]
message_size_distribution/64 time: [165 ns] throughput: [3.88 GB/s]- If 64B is only 10% slower than 8B โ allocation overhead is minimal
- If 256B is 50% slower than 64B โ cache effects or allocation pressure
2. Supervision Heavy Workload (`supervision_heavy`)
Purpose: Measure supervision tree overhead under realistic hierarchical actor systems.
What it tests:
- Three configurations:
depth3_breadth10: Shallow wide tree (30 total actors)depth5_breadth5: Balanced tree (775 total actors)depth10_breadth2: Deep narrow tree (2046 total actors)
- Spawns entire tree with linked supervision
- Triggers cascading shutdown from root
- Measures full lifecycle including supervision events
Why it's useful:
- Tests Phase 1.3 optimization - Validates supervision lock optimization impact
- Real-world workload - Many actor systems use hierarchical supervision
- Identifies lock contention - Deep trees stress supervision event handling
- Scalability testing - Shows how supervision overhead scales with tree size
Expected insights:
- Phase 1.3 should show improvement in wide trees (more parallel supervision events)
- Deep trees should benefit from
for_each_child()optimization (Phase 2.4) - Cascading shutdown time should scale sub-linearly with tree size
How to interpret results:
supervision_heavy/depth3_breadth10 time: [500 ยตs]
supervision_heavy/depth5_breadth5 time: [2.5 ms]
supervision_heavy/depth10_breadth2 time: [5 ms]- Compare depth5 vs depth3: Should scale ~5-10x (not 25x despite 25x more actors)
- If linear scaling โ lock contention problem
- If exponential โ algorithm issue
3. Mixed Workload (`mixed_workload_100workers_1000msgs`)
Purpose: Simulate realistic actor system with spawning, messaging, and supervision combined.
What it tests:
- Spawns coordinator actor with 100 supervised child workers
- Sends 1,000 messages to each worker (100,000 total messages)
- Workers process messages and maintain state
- Coordinator triggers graceful shutdown of all workers
- Full lifecycle: spawn โ work โ supervise โ shutdown
Why it's useful:
- Realistic benchmark - Combines all optimizations in real-world scenario
- Overall system performance - Not just isolated hot paths
- Integration testing - Ensures optimizations don't conflict
- User-facing metric - Represents actual application performance
Expected insights:
- Should show cumulative benefit of all Phase 1+2 optimizations
- Better indicator of real-world improvement than micro-benchmarks
- Helps validate that 15-20% improvement claim holds in practice
How to interpret results:
mixed_workload_100workers_1000msgs time: [85 ms]- Compare with baseline before optimizations
- Should correlate with
process_messagesbenchmark - Larger improvement โ optimizations work well together
- Smaller improvement โ overhead from other operations dominates
4. Message Send Microbenchmark (`message_send_only_10000`)
Purpose: Isolate message send operation to measure boxing overhead independent of processing.
What it tests:
- Spawns single no-op actor that doesn't process messages
- Sends 10,000 messages as fast as possible
- Measures just the send path: boxing + channel send
- Actor runs in background but doesn't process (isolates send cost)
Why it's useful:
- Hot path isolation - Removes actor processing time from equation
- Boxing overhead - Directly measures
Message::box_message()cost - Type checking cost - Shows impact of Phase 2.2 optimization
- SBO validation - Would show if inline storage helps send path
Expected insights:
- Phase 2.2 (type check removal) should improve this benchmark
- Phase 2.3 (downcast optimization) won't affect this (only receive side)
- Very low variance โ consistent boxing performance
- High variance โ potential contention in channel
How to interpret results:
message_send_only_10000 time: [50 ยตs] โ ~5ns per send- Compare with
process_messagesthroughput (~150ns per message) - Send overhead should be <10% of total message processing time
- If send is >20% โ boxing is bottleneck
5. Spawn Rate Benchmark (`spawn_rate_1000actors`)
Purpose: Measure maximum actor creation throughput.
What it tests:
- Spawns 1,000 minimal actors that immediately stop
- Waits for all to complete
- Measures pure spawn overhead without message processing
- Sequential spawning (not parallel)
Why it's useful:
- Tests Phase 1.2 optimization - Arc clone reduction during spawn
- Startup performance - Important for systems that create many actors
- Spawn overhead quantification - Shows fixed cost per actor
- Scalability baseline - Reference for how many actors you can create
Expected insights:
- Phase 1.2 should show 1-2% improvement
- Should scale linearly with actor count
- Helps understand fixed vs variable costs in spawn
How to interpret results:
spawn_rate_1000actors time: [2 ms] โ 2ยตs per actor- Compare with
create_actorsbenchmark (includes handle waiting) - Should be slightly faster since actors immediately stop
- Throughput: ~500,000 actors/second is good
- <100,000 actors/second โ spawn overhead too high
Running the Benchmarks
Run all advanced benchmarks
cargo bench --bench simple_advanced_benchmarksRun specific category
cargo bench --bench simple_advanced_benchmarks -- small_messages
cargo bench --bench simple_advanced_benchmarks -- large_messages
cargo bench --bench simple_advanced_benchmarks -- spawnCompare with SBO feature
# Baseline
cargo bench --bench simple_advanced_benchmarks -- small_messages > /tmp/baseline.txt
# With SBO
cargo bench --bench simple_advanced_benchmarks --features small-buffer-optimization -- small_messages > /tmp/sbo.txt
# Compare
critcmp baseline.txt sbo.txtGenerate flamegraphs (requires cargo-flamegraph)
cargo flamegraph --bench simple_advanced_benchmarks -- --bench small_messagesExpected Results Analysis
Phase 1+2 Optimizations (Proven)
Message Size Distribution:
- All sizes: 3-5% improvement
- Uniform across sizes (not size-dependent)
Supervision Heavy:
- Wide trees (depth3_breadth10): 5-8% improvement
- Deep trees (depth10_breadth2): 2-4% improvement
Mixed Workload:
- Overall: 12-18% improvement (cumulative effect)
Message Send:
- 2-3% improvement from type check removal
Spawn Rate:
- 1-2% improvement from Arc clone reduction
SBO Feature (Regression Found)
Message Size Distribution:
- โค32B messages: 20-30% SLOWER (enum overhead + ManuallyDrop)
32B messages: 10-15% SLOWER (larger BoxedMessage struct)
Why SBO Failed:
- Enum matching overhead on every box/unbox
- Larger struct size (80 bytes) โ worse cache locality
- ManuallyDrop wrapper overhead
- Runtime type ID + size verification
- Extra indirection in match arms
Diagnostic Workflow
Problem: Performance regression in production
- Run Mixed Workload to see overall impact
- Run Message Size Distribution to identify if message size is factor
- Run Supervision Heavy if system uses deep actor hierarchies
- Run Message Send to isolate send vs receive overhead
Problem: Optimization not showing expected gains
- Run Spawn Rate to verify spawn optimization worked
- Run Message Send to verify type check removal worked
- Run Mixed Workload to see if gains are masked by other overhead
Problem: Validating new optimization
- Run all benchmarks before change โ save results
- Implement optimization
- Run all benchmarks after change โ compare
- Use
critcmpor Criterion's built-in comparison
Adding New Benchmarks
When adding new benchmarks to this suite, ensure:
- Clear purpose - What specific aspect does it measure?
- Isolation - Does it test one thing or multiple?
- Reproducibility - Same results across runs?
- Meaningful metrics - Throughput, latency, or both?
- Documentation - Update this file with interpretation guide
Benchmark Limitations
What these DON'T test
- Memory allocations - Use
cargo instrumentsorheaptrack - Cache misses - Use
perf stat -e cache-misses - Lock contention - Use
cargo flamegraphorpprof - Network overhead - Cluster features not benchmarked here
- Real workload - Synthetic benchmarks may not match production
Complementary Tools
# Allocation profiling
cargo instruments -t Allocations --bench simple_advanced_benchmarks
# Cache analysis
perf stat -e cache-references,cache-misses cargo bench --bench simple_advanced_benchmarks
# Lock contention
cargo flamegraph --bench simple_advanced_benchmarks -- --profile-time 60
# Memory usage
heaptrack cargo bench --bench simple_advanced_benchmarksConclusion
These advanced benchmarks provide targeted insights into:
- โ Message size performance characteristics
- โ Supervision tree overhead
- โ Real-world mixed workloads
- โ Isolated hot path operations
- โ Spawn throughput
Combined with the standard benchmarks, they give a complete picture of Ractor's performance profile and help validate optimizations before production deployment.
Key Takeaway: Always benchmark with both micro-benchmarks AND realistic workloads. Phase 1+2 optimizations showed 15-20% improvement in realistic scenarios, while SBO showed 20-30% regression despite being technically correct.
File: docs/runtime-semantics.md
Runtime semantics
This document describes the runtime semantics, guarantees, and important edge-cases for ractor. It is intended to be a concise, actionable reference for developers building on ractor or ractor_cluster.
Core guarantees
- Single-message processing: An actor processes at most one message handler at a time. Handlers for a single actor are never executed in parallel.
- Message types: User message types must be
Send + 'static. For clustered usage, messages must additionally implement the network serialization traits (ractor::Messagevia derive macros, andractor_cluster::BytesConvertablefor payloads). - Pre-start initialization: Actor state is created in
pre_start.pre_startis run at spawn time and may fail; failures are returned to the caller ofActor::spawn. - Actor
selfvs state:selfis read-only and intended for configuration. Mutable actor state belongs to theStatetype returned bypre_start.
Message priority & ordering
Message delivery is multiplexed into four prioritized channels. Higher priorities are processed before lower ones:
- Signals (highest) โ e.g.,
Signal::Kill. Signals immediately interrupt processing and will terminate execution (see Signals section). - Stop โ a graceful stop request. Ongoing asynchronous work is allowed to complete; on the actor's next processing iteration Stop takes priority over supervision events and user messages.
- SupervisionEvent โ lifecycle notifications from child actors (startup, exit, panic).
- Messages (lowest) โ user-defined messages (cast/call).
Ordering guarantees:
- Per-sender FIFO: Messages sent from a single sender to a single actor are delivered in the order they were sent (FIFO) for the user message channel when using the provided
ActorRefAPIs. - Cross-sender ordering: No ordering guarantee between messages from different senders.
- Priority preemption: Higher-priority channel messages can preempt lower-priority messages in the queue. A Stop message will be processed before later-arriving user messages.
- Local vs remote: Local ordering guarantees apply for in-process messaging. On the network (ractor_cluster), ordering depends on the transport and node session behavior โ ordering can be preserved per-connection but is not guaranteed across reconnections or multi-path routing.
Signals vs Stop (behavioral differences)
- Signal (Kill)
- Highest priority and immediate.
- Terminates all work including currently executing async handlers; cancellation semantics are immediate and not graceful.
- Used for forced termination or emergency shutdowns.
- Stop
- Graceful termination: currently executing async work is allowed to finish.
- On the next message processing iteration the Stop is processed and actor will transition to exiting.
- Useful for normal shutdowns where cleanup should run.
Important: Stop does not interrupt running handlers. If you require immediate stop, send Kill.
Supervision & failure handling
- Supervision events notify supervising actors of child lifecycle events (started, exited, spawned with error, panicked).
- Panic handling:
- Panics inside
pre_startare captured and returned to the spawner. - Panics during message processing are caught and surfaced in supervision events (unless the binary is built with
panic = "abort", which will terminate the process).
- Panics inside
- Supervisors decide restart/stop policies by handling supervision events and using provided restart utilities.
RPC semantics
- RPC calls use
RpcReplyPortto correlate requests and responses. - RPCs are matched by a reply port id; the origin node holds the awaiting port and the remote node serializes the reply payload.
- On network partitions or disconnected nodes, pending RPCs may time out or fail โ the user should add timeouts and retry logic for robust behavior.
Timers & scheduling
- Timers are implemented as scheduled events that enqueue messages to the actor mailbox.
- Timer delivery follows the same priority rules (timers are user messages unless otherwise specified).
- Timers are best-effort accurate โ network latencies, scheduling, and runtime load affect delivery time.
Blocking and long-running work
- Actor handlers are asynchronous; long synchronous blocking operations will block the actor and delay its mailbox processing.
- Best practice: perform blocking operations in offloaded tasks (spawn on runtime thread pool) and send results back to the actor as messages.
Concurrency model & runtime integration
- Actors are runtime-agnostic (works with tokio and async-std). Internals use async primitives and some tokio sync types even when using async-std (see feature flags).
- Actors are cooperative: asynchronous handlers must yield to allow other tasks and timers to run.
- Actors may be scheduled across threads by the async runtime, but handler execution remains single-threaded per actor.
Mailbox semantics
- Mailboxes are bounded/unbounded depending on factory/configuration. Check the factory settings used to spawn workers/actors.
- Backpressure: when using bounded queues, attempts to send when full may fail or be delayed depending on the chosen factory/queue policy (discard, backpressure, etc.).
ractor_cluster (remote) specifics
- Remote actors are represented by
RemoteActorwrappers that contain only serialized payloads. Deserialization occurs on the owning node. NodeSessionmanages transport, authentication, and pending RPC mapping.- Network behavior:
- Ordering: per-connection ordering is generally preserved, but there is no distributed global ordering guarantee.
- Reconnects: reconnection semantics are best-effort and may result in message loss unless application-level retries/acknowledgement are implemented.
- Authentication & encryption: the cluster supports auth and TLS; these features are considered experimental and require production hardening.
- Serialization: cluster messages must implement
BytesConvertable(or be produced via procedural macros for prost types). Versioning of serialized formats should be considered for rolling upgrades.
Observability & diagnostics
- Insert tracing and metrics at:
- Mailbox enqueue/dequeue
- NodeSession read/write loops
- Supervision events and restarts
- For debugging actor lifecycles, enable debug logs and use supervision events to trace restarts and failures.
Safety gotchas & recommendations
- Do not rely on synchronous blocking inside handlers โ offload blocking work.
- Do not assume RPC or remote message delivery is reliable; always add timeouts and retries.
- Test supervision logic under stress (panics, rapid spawn/kill cycles).
- When using cluster features, add tests for auth, reconnection, and partition behavior.
Summary of best practices
- Keep actors focused and small; offload heavy work.
- Use Stop for graceful shutdowns and Kill for forced termination.
- Make RPCs resilient: set timeouts and retries.
- For production clusters: implement message-level acknowledgements or idempotency when required, and add monitoring/metrics on NodeSession and pending RPC queues.
File: ractor_cluster/README.md
ractor_cluster
A companion crate to ractor for supporting remote actors
This crate contains extensions to ractor, a pure-Rust actor framework. Inspired from Erlang's gen_server.
Website Ractor has a companion website for more detailed getting-started guides along with some best practices and is updated regularly. Api docs will still be available at docs.rs however this will be a supplimentary site for ractor. Try it out! https://slawlor.github.io/ractor/
About
ractor_cluster expands upon ractor actors to support transmission over a network link and synchronization of actors on networked clusters of actors.
Installation
Install ractor_cluster by adding the following to your Cargo.toml dependencies
[dependencies]
ractor = { version = "0.13", features = ["cluster"] }
ractor_cluster = "0.13"Ractor in distribucted clusters
Ractor actors can be built in a network-distributed pool of actors, similar to Erlang's EPMD which manages inter-node connections + node naming. In our implementation, we have ractor_cluster in order to facilitate distributed ractor actors.
ractor_cluster has a single main type in it, namely the NodeServer which represents a host of a node() process. It additionally has some macros and a procedural macros to facilitate developer efficiency when building distributed actors. The NodeServer is responsible for:
- Managing all incoming and outgoing
NodeSessionactors which represent a remote node connected to this host. - Managing the
TcpListenerwhich hosts the server socket to accept incoming session requests (with or without encryption).
The bulk of the logic for node interconnections however is held in the NodeSession which manages
- The underlying TCP connection managing reading and writing to the stream.
- The authentication between this node and the connection to the peer
- Managing actor lifecycle for actors spawned on the remote system.
- Transmitting all inter-actor messages between nodes.
- Managing PG group synchronization
etc..
The NodeSession makes local actors available on a remote system by spawning RemoteActors which are essentially untyped actors that only handle serialized messages, leaving message deserialization up to the originating system. It also keeps track of pending RPC requests, to match request to response upon reply. There are special extension points in ractor which are added to specifically support RemoteActors that aren't generally meant to be used outside of the standard
Actor::spawn(Some("name".to_string()), MyActor).awaitpattern.
Quick-start
The basics of setting up a networked cluster of actors lives in the NodeServer struct. This structure handles the low-level network ownership over a server port along with all of the lifecycle of cluster inter-connections. By spawning this single struct, you're able to accept incoming connections between hosts!
Nodes in the network are authenticated to each other with a "magic cookie" following the Erlang specification in Erlang's distribution protocol. If you want to connect to another host, you need to
- Initialize your own
NodeServer - Execute a "client-connection" to the remote
NodeServeryou're trying to connect to like
let host = "1.2.3.4";
let port = "4697";
ractor_cluster::client_connect(
&actor,
format!("{host}:{port}"),
)Similarly there is a client_connect_enc to connect to a NodeServer which is utilizing encrypted communication. That's it! If your nodes are sharing a proper magic cookie value, they should authenticate to each other and you'll see remote actors spawned on your local system which you can communciate with through the various pg or pid-based registries.
Bring Your Own Transport
If you want to run the cluster protocol over a custom transport (for example QUIC, WebSocket, SSH tunnel, or an in-memory pipe), you can implement a tiny trait and inject a connection into the NodeServer.
- Implement
ractor_cluster::ClusterBidiStreamfor your connected stream type. It just needs to split into a read and a write half that implementtokio::io::AsyncRead/AsyncWrite. - The cluster protocol framing remains identical: a big-endian length prefix followed by a prost-encoded payload. You don't need to touch authentication, control, remote actor, or PG sync logic.
- Open a connection in your app, wrap it as
ClusterBidiStream, and send it to the node server usingNodeServerMessage::ConnectionOpenedExternalor via the helperclient_connect_external.
Example:
use ractor_cluster::{ClusterBidiStream, BoxRead, BoxWrite};
use tokio::io::DuplexStream;
struct MyDuplex(DuplexStream);
impl ClusterBidiStream for MyDuplex {
fn split(self: Box<Self>) -> (BoxRead, BoxWrite) {
let (r, w) = tokio::io::split(self.0);
(Box::new(r), Box::new(w))
}
fn peer_label(&self) -> Option<String> { Some("duplex:peer".into()) }
fn local_label(&self) -> Option<String> { Some("duplex:local".into()) }
}
// elsewhere in async context
// let (a, b) = tokio::io::duplex(64 * 1024);
// node_server.cast(NodeServerMessage::ConnectionOpenedExternal { stream: Box::new(MyDuplex(a)), is_server: false })?;The existing TCP and TLS paths continue to work as before. External transports are purely additive.
Designing remote-supported actors
Note not all actors are created equal. Actors need to support having their message types sent over the network link. This is done by overriding specific methods of the ractor::Message trait all messages need to support. Due to the lack of specialization support in Rust, if you choose to use ractor_cluster you'll need to derive the ractor::Message trait for all message types in your crate. However to support this, we have a few procedural macros to make this a more painless process
Deriving the basic Message trait for in-process only actors
Many actors are going to be local-only and have no need sending messages over the network link. This is the most basic scenario and in this case the default ractor::Message trait implementation is fine. You can derive it quickly with:
use ractor_cluster::RactorMessage;
use ractor::RpcReplyPort;
#[derive(RactorMessage)]
enum MyBasicMessageType {
Cast1(String, u64),
Call1(u8, i64, RpcReplyPort<Vec<String>>),
}The will implement the default ractor::Message trait for you without you having to write it out by hand.
Deriving the network serializable message trait for remote actors
If you want your actor to support remoting, then you should use a different derive statement, namely:
use ractor_cluster::RactorClusterMessage;
use ractor::RpcReplyPort;
#[derive(RactorClusterMessage)]
enum MyBasicMessageType {
Cast1(String, u64),
#[rpc]
Call1(u8, i64, RpcReplyPort<Vec<String>>),
}which adds a significant amount of underlying boilerplate (take a look yourself with cargo expand!) for the implementation. But the short answer is, each enum variant needs to serialize to a byte array of arguments, a variant name, and if it's an RPC give a port that receives a byte array and de-serialize the reply back. Each of the types inside of either the arguments or reply type need to implement the ractor_cluster::BytesConvertable trait which just says this value can be written to a byte array and decoded from a byte array. If you're using prost for your message type definitions (protobuf), we have a macro to auto-implement this for your types.
ractor_cluster::derive_serialization_for_prost_type! {MyProtobufType}Besides that, just write your actor as you would. The actor itself will live where you define it and will be capable of receiving messages sent over the network link from other clusters!
Contributors
The original author of ractor is Sean Lawlor (@slawlor). To learn more about contributing to ractor please see CONTRIBUTING.md
License
This project is licensed under MIT.
File: ractor_cluster_integration_tests/test-ca/README.md
Rustls Test CA
This directory contains various test certificate authorities, intermediates,
end-entity, and client certificates that are used by Rustls integration tests.
You can regenerate the data in this directory by running therustls/examples/internal/test_ca.rs tool:
cargo run -p rustls --example test_caFile: xtask/README.md
This package is included here to support the automatic reporting of code coverage on
Github. To view code coverage locally:
Do this once to set it up:
rustup component add llvm-tools-preview
cargo install grcovSubsequently, run:
cargo xtask coverage --devFile: .github/dependabot.yml
To get started with Dependabot version updates, you'll need to specify which
package ecosystems to update and where the package manifests are located.
Please see the documentation for all configuration options:
https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
package-ecosystem: cargo
directory: /
schedule:
interval: dailypackage-ecosystem: github-actions
directory: /
schedule:
interval: daily
File: .github/ISSUE_TEMPLATE/bug_report.md
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''
Describe the bug
A clear and concise description of what the bug is.
To Reproduce
Steps to reproduce the behavior:
- Go to '...'
- Click on '....'
- Scroll down to '....'
- See error
Expected behavior
A clear and concise description of what you expected to happen.
Additional context
Add any other context about the problem here (e.g. Rust version, other crates imported, etc)
File: .github/ISSUE_TEMPLATE/feature_request.md
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''
Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
Describe the solution you'd like
A clear and concise description of what you want to happen.
Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.
Additional context
Add any other context or screenshots about the feature request here.
File: .github/wasm-test-runner/package.json
{
"name": "xvfb-run-test",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"puppeteer": "^24.6.1",
"xvfb": "^0.4.0"
},
"type": "module"
}
File: .github/workflows/bench.yaml
name: Benchmark Comparison
on:
pull_request:
types: [opened, reopened, synchronize]
concurrency:
group: bench-${{ github.head_ref }}
cancel-in-progress: true
jobs:
bench-base:
name: Benchmark main
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
ref: main
- name: Install stable Rust
uses: dtolnay/rust-toolchain@stable
- name: Cache cargo artifacts
uses: Swatinem/rust-cache@v2
- name: Run benchmarks on main
run: |
cargo bench -p ractor \
--bench actor \
--bench async_traits \
--bench factory \
--bench simple_advanced_benchmarks \
-- --save-baseline main
if [ -f ractor_cluster/benches/message_serialization.rs ]; then
cargo bench -p ractor_cluster \
--bench message_serialization \
-- --save-baseline main
fi
env:
CI: 1
- name: Install critcmp
run: cargo install critcmp --locked
- name: Export main baseline
run: critcmp --export main > main.json
- name: Upload main baseline
uses: actions/upload-artifact@v7
with:
name: bench-baseline-main
path: main.json
retention-days: 1 bench-pr:
name: Benchmark PR and compare
runs-on: ubuntu-latest
needs: bench-base
permissions:
pull-requests: write
steps:
- uses: actions/checkout@v7
- name: Install stable Rust
uses: dtolnay/rust-toolchain@stable
- name: Cache cargo artifacts
uses: Swatinem/rust-cache@v2
- name: Download main baseline
uses: actions/download-artifact@v8
with:
name: bench-baseline-main
- name: Run benchmarks on PR branch
run: |
cargo bench -p ractor \
--bench actor \
--bench async_traits \
--bench factory \
--bench simple_advanced_benchmarks \
-- --save-baseline pr
cargo bench -p ractor_cluster \
--bench message_serialization \
-- --save-baseline pr
env:
CI: 1
- name: Install critcmp
run: cargo install critcmp --locked
- name: Compare benchmarks
id: compare
run: |
# run the comparison twice: default multi-column output and a flattened
# list view for easier per-benchmark deltas
RESULT=$(critcmp main.json pr)
LIST=$(critcmp main.json pr --list)
echo "$RESULT"
echo
echo "Flat results (see per-benchmark deltas):"
echo "$LIST"
{
echo "result<<EOF"
echo "$RESULT"
echo "EOF"
echo "list<<EOF"
echo "$LIST"
echo "EOF"
} >> "$GITHUB_OUTPUT"
- name: Find existing benchmark comment
uses: peter-evans/find-comment@v4
id: find-comment
with:
issue-number: ${{ github.event.pull_request.number }}
comment-author: github-actions[bot]
body-includes: Benchmark Comparison
- name: Post or update benchmark comment
uses: peter-evans/create-or-update-comment@v5
with:
issue-number: ${{ github.event.pull_request.number }}
comment-id: ${{ steps.find-comment.outputs.comment-id }}
edit-mode: replace
body: |
## Benchmark Comparison (PR vs `main`)
Results (collapse to hide)
```
${{ steps.compare.outputs.result }}
```
_Note: a **negative** delta indicates the PR is faster (an
improvement); a **positive** delta means the PR is slower (a
regression). Benchmarks are grouped (e.g., `small_messages`,
`spawn_throughput`); the flattened list below shows every
individual comparison for clearer deltas._
_Benchmarks introduced by the current PR appear only in the `pr`
column. Once merged, subsequent PRs will compare them against the
`main` baseline normally._
=== per-benchmark breakdown ===
```
${{ steps.compare.outputs.list }}
```
_Benchmarks run on shared CI hardware (`ubuntu-latest`).
Differences under ~5% may be noise._File: .github/workflows/ci.yaml
name: CI
on:
push:
branches:
- main
pull_request:
types: [opened, reopened, synchronize]
jobs:
msrv:
name: Rust 1.85 MSRV
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@main
- name: Install Rust 1.85
uses: dtolnay/[email protected]
with:
targets: wasm32-unknown-unknown
- name: Check workspace defaults and all targets
run: cargo check --workspace --all-targets
- name: Check actor macros with native async traits
run: cargo check --package ractor --features actor-macros --all-targets
- name: Check async traits with Tokio
run: cargo check --package ractor --features async-trait,actor-macros --all-targets
- name: Check async traits with async-std
run: cargo check --package ractor --no-default-features --features async-std,async-trait,actor-macros --all-targets
- name: Check optional ractor APIs
run: cargo check --package ractor --features cluster,monitors,blanket_serde,output-port-v2,actor-macros --all-targets
- name: Check ractor_cluster with async traits
run: cargo check --package ractor_cluster --features async-trait
- name: Check the ractor WASM library
run: cargo check --package ractor --lib --target wasm32-unknown-unknown test:
name: ${{matrix.name}}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- name: Run the default tests
package: ractor
# flags:
- name: Test ractor with async-trait
package: ractor
flags: -F async-trait
- name: Test actor macros with native async traits
package: ractor
flags: -F actor-macros
- name: Test actor macros with async-trait
package: ractor
flags: --no-default-features -F tokio_runtime,async-trait,actor-macros
- name: Test actor macros with async-std and async-trait
package: ractor
flags: --no-default-features -F async-std,async-trait,actor-macros
- name: Test ractor without span propogation
package: ractor
flags: --no-default-features -F tokio_runtime
- name: Test ractor with the cluster feature
package: ractor
flags: -F cluster
- name: Test ractor with the blanket_serde feature
package: ractor
flags: -F blanket_serde
- name: Test ractor with async-std runtime
package: ractor
flags: --no-default-features -F async-std,message_span_propogation
- name: Test ractor with async-std runtime but no span propagation
package: ractor
flags: --no-default-features -F async-std
- name: Test ractor with async-std runtime and async-trait
package: ractor
flags: --no-default-features -F async-std,async-trait
- name: Test ractor_cluster with native async traits
package: ractor_cluster
# flags:
- name: Test ractor_cluster without message span propagation
package: ractor_cluster
flags: --no-default-features
verify_no_span: true
- name: Test ractor_cluster with async_trait
package: ractor_cluster
flags: -F async-trait
- name: Test ractor with the monitor API
package: ractor
flags: -F monitors
- name: Test ractor with output-port-v2 feature
package: ractor
flags: -F output-port-v2
- name: Test ractor without output-port-v2 feature (explicit)
package: ractor
flags: --no-default-features -F tokio_runtime,message_span_propogation
steps:
- uses: actions/checkout@main
- name: Install rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: ${{matrix.name}}
uses: actions-rs/cargo@v1
with:
command: test
args: --package ${{matrix.package}} ${{matrix.flags}}
- name: Verify message span propagation is disabled
if: matrix.verify_no_span
shell: bash
run: |
if cargo tree --package ractor_cluster --no-default-features --edges features --invert ractor \
| grep -Fq 'ractor feature "message_span_propogation"'; then
echo 'ractor/message_span_propogation was unexpectedly enabled' >&2
exit 1
fi
- name: Test everything
uses: actions-rs/cargo@v1
with:
command: test clippy:
name: Clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@main
- name: Install minimal stable with clippy
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
components: clippy
override: true
- name: Run Clippy
uses: actions-rs/cargo@v1
with:
command: clippy
args: --all -- -D clippy::all -D warnings rustfmt:
name: rustfmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@main
- name: Install minimal stable with rustfmt
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
components: rustfmt
override: true
- name: Run rustfmt
uses: actions-rs/cargo@v1
with:
command: fmt
args: --all -- --check docs:
name: docs
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@main
- name: Install minimal stable with rustfmt
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
components: rustfmt
override: true
- name: Run cargo doc on release profile
uses: actions-rs/cargo@v1
env:
RUSTDOCFLAGS: -D warnings
with:
command: doc
args: --workspace --no-deps -r benches:
name: benches
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@main
- name: Install rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: Compile benchmarks
uses: actions-rs/cargo@v1
with:
command: bench
args: --no-runFile: .github/workflows/coverage.yml
name: Code Coverage
on:
push:
branches:
- main
pull_request:
types: [opened, reopened, synchronize]
jobs:
coverage:
name: Coverage using xtask
strategy:
matrix:
os: [ubuntu-latest]
rust: [stable]
runs-on: ${{ matrix.os }}
steps:
- name: Checkout sources
uses: actions/checkout@v7
- name: Install stable toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: ${{ matrix.rust }}
override: true
components: llvm-tools-preview
- uses: Swatinem/rust-cache@v2
- name: Download grcov
run: |
mkdir -p "${HOME}/.local/bin"
curl -sL https://github.com/mozilla/grcov/releases/download/v0.8.10/grcov-x86_64-unknown-linux-gnu.tar.bz2 | tar jxf - -C "${HOME}/.local/bin"
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Exercise actor macros for coverage
env:
CARGO_INCREMENTAL: 0
RUSTFLAGS: -Cinstrument-coverage
LLVM_PROFILE_FILE: cargo-test-%p-%m.profraw
run: cargo test --package ractor --features actor-macros --test actor_macros
- name: Run xtask coverage
uses: actions-rs/cargo@v1
with:
command: run
args: --bin xtask coverage
- name: Upload to codecov.io
uses: codecov/codecov-action@v7
with:
fail_ci_if_error: true # optional (default = false)
files: coverage/*.lcov
token: ${{ secrets.CODECOV_TOKEN }} # required
verbose: true # optional (default = false)
name: ractor # optionalFile: .github/workflows/integration.yaml
name: Ractor Cluster integration tests
on:
push:
branches:
- main
paths:
- 'ractor_cluster*/'
pull_request:
types: [opened, reopened, synchronize]
paths:
- 'ractor_cluster/*'
jobs:
test:
name: Test networked cluster
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
features:
- 'blanket_serde,cluster'
- 'blanket_serde,cluster,async-trait'
steps:
- uses: actions/checkout@main
- name: Build the docker image
working-directory: .
run: |
FEATURES=${{matrix.features}} docker compose build
- name: Authentication Handshake
working-directory: .
run: |
FEATURES=${{matrix.features}} docker compose --env-file ./ractor_cluster_integration_tests/envs/auth-handshake.env up --exit-code-from node-b
- name: Process Groups
working-directory: .
run: |
FEATURES=${{matrix.features}} docker compose --env-file ./ractor_cluster_integration_tests/envs/pg-groups.env up --exit-code-from node-b
- name: Encrypted communications
working-directory: .
run: |
FEATURES=${{matrix.features}} docker compose --env-file ./ractor_cluster_integration_tests/envs/encryption.env up --exit-code-from node-b
- name: External transport
working-directory: .
run: |
FEATURES=${{matrix.features}} docker compose --env-file ./ractor_cluster_integration_tests/envs/external-transport.env up --exit-code-from node-b
- name: Transitive connections
working-directory: .
run: |
FEATURES=${{matrix.features}} docker compose --env-file ./ractor_cluster_integration_tests/envs/dist-connect.env up --exit-code-from node-cFile: .github/workflows/publish.yaml
name: Publish
on:
release:
types: [published]
jobs:
publish:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest]
rust: [stable]
steps:
- uses: hecrj/setup-rust-action@v2
with:
rust-version: ${{ matrix.rust }}
- uses: actions/checkout@main
- name: Login to crates.io
run: cargo login $CRATES_IO_TOKEN
env:
CRATES_IO_TOKEN: ${{ secrets.crates_io_token }}
- name: Dry run publish ractor_macros
run: cargo publish --dry-run --manifest-path Cargo.toml -p ractor_macros
- name: Publish ractor_macros
run: cargo publish --manifest-path Cargo.toml -p ractor_macros
env:
CARGO_REGISTRY_TOKEN: ${{ secrets.crates_io_token }}
- name: Wait for necessary ractor_macros version to be available
run: bash ./.github/workflows/wait_for_crate_dependency.sh ractor ractor_macros
- name: Dry run publish ractor
run: cargo publish --dry-run --manifest-path Cargo.toml -p ractor
- name: Publish crate ractor
run: cargo publish --manifest-path Cargo.toml -p ractor
env:
CARGO_REGISTRY_TOKEN: ${{ secrets.crates_io_token }}
- name: Dry run publish ractor_cluster_derive
run: cargo publish --dry-run --manifest-path Cargo.toml -p ractor_cluster_derive
- name: Publish ractor_cluster_derive
run: cargo publish --manifest-path Cargo.toml -p ractor_cluster_derive
env:
CARGO_REGISTRY_TOKEN: ${{ secrets.crates_io_token }}
- name: Wait for necessary ractor version to be available
run: bash ./.github/workflows/wait_for_crate_dependency.sh ractor_cluster ractor
- name: Wait for necessary ractor version to be available
run: bash ./.github/workflows/wait_for_crate_dependency.sh ractor_cluster ractor_cluster_derive
- name: Dry run publish ractor_cluster
run: cargo publish --dry-run --manifest-path Cargo.toml -p ractor_cluster
- name: Publish ractor_cluster
run: cargo publish --manifest-path Cargo.toml -p ractor_cluster
env:
CARGO_REGISTRY_TOKEN: ${{ secrets.crates_io_token }}File: .github/workflows/wasm.yaml
name: Unittests for wasm32-unknown-unknown
on:
push:
branches: [main]
workflow_dispatch:
pull_request:
types: [opened, reopened, synchronize]
jobs:
unit-test:
name: Run unit tests in browser
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@main
- name: Install rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: Install wasm-pack
run: cargo install wasm-pack
- uses: actions/setup-node@v7
with:
node-version: 20
- name: Setup test runner
run: |
cd ./.github/wasm-test-runner
npm install
- name: Run tests
run: |
export WORKING_DIR=$(pwd)
cd ./.github/wasm-test-runner
node ./index.js unit-test-output-port-v2:
name: "Run unit tests in browser (features: output-port-v2)"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@main
- name: Install rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: Install wasm-pack
run: cargo install wasm-pack
- uses: actions/setup-node@v7
with:
node-version: 20
- name: Setup test runner
run: |
cd ./.github/wasm-test-runner
npm install
- name: "Run tests (features: output-port-v2)"
env:
FEATURES_OUTPUT_PORT_V2: "true"
run: |
export WORKING_DIR=$(pwd)
cd ./.github/wasm-test-runner
node ./index.js unit-test-async-trait:
name: "Run unit tests in browser (features: async-trait)"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@main
- name: Install rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: Install wasm-pack
run: cargo install wasm-pack
- uses: actions/setup-node@v7
with:
node-version: 20
- name: Setup test runner
run: |
cd ./.github/wasm-test-runner
npm install
- name: "Run tests (features: async-trait)"
env:
FEATURES_ASYNC_TRAIT: "true"
run: |
export WORKING_DIR=$(pwd)
cd ./.github/wasm-test-runner
node ./index.js