Skip to main content

actor_kit/
lib.rs

1//! # actor-kit
2//!
3//! A work-stealing actor runtime with OTP-style supervision, designed for
4//! hosting 100,000+ actors per node with efficient load balancing.
5//!
6//! ## How this differs from task-per-actor runtimes
7//!
8//! Most Rust actor frameworks (`ractor`, `kameo`) run each actor as its own
9//! tokio task: the async runtime multiplexes tasks onto its worker threads, and
10//! "scheduling" is just task polling. `actor-kit` takes a different approach:
11//!
12//! - **Actors are not tasks.** An actor is a registry entry (ID + state +
13//!   bounded mailbox). Work arrives as `Task` items on crossbeam deques.
14//! - **A fixed pool of OS worker threads** pulls work from (1) a priority
15//!   injector, (2) their local FIFO deque, (3) a global injector, then
16//!   (4) steals from other workers — in that order. Idle workers back off
17//!   (spin, then sleep) instead of burning a reactor tick per actor.
18//! - **Per-actor mailbox with hard backpressure.** Bounded lock-free
19//!   `ArrayQueue` + tokio `Semaphore`; senders block or fail once the
20//!   mailbox crosses its backpressure threshold (default 80% of capacity).
21//!   A hot actor cannot grow an unbounded task queue.
22//! - **Supervision is data, not tasks.** Erlang/OTP strategies
23//!   (OneForOne / OneForAll / RestForOne / SimpleOneForOne), restart
24//!   policies (Permanent / Transient / Temporary), max-restarts-within-window
25//!   rate limiting, escalation, and hierarchical [`SupervisorTree`]s are
26//!   plain data structures you drive explicitly — no hidden per-supervisor
27//!   tokio tasks, no implicit restart side effects.
28//!
29//! The trade-offs are honest: message handlers here are state-machine steps
30//! (state lives in the registry, not in an async frame), so actors that need
31//! to `.await` I/O mid-handler are a better fit for task-per-actor frameworks.
32//! This runtime shines when you have very many mostly-CPU-light actors,
33//! want predictable memory per actor, and need OTP-style fault tolerance
34//! semantics with real work stealing.
35//!
36//! ## Example
37//!
38//! ```no_run
39//! use actor_kit::{ActorBuilder, ActorScheduler, MessagePayload, SchedulerConfig};
40//! use std::sync::Arc;
41//!
42//! # fn main() -> actor_kit::Result<()> {
43//! // Create and start a 4-worker work-stealing scheduler.
44//! let scheduler = Arc::new(ActorScheduler::new(SchedulerConfig::new().workers(4)));
45//! scheduler.start()?;
46//!
47//! // Spawn an actor and start it.
48//! let handle = ActorBuilder::new().name("my-actor").spawn(&scheduler)?;
49//! # actor_kit::rt().block_on(async {
50//! handle.start().await?;
51//!
52//! // Send messages (backpressured, bounded mailbox).
53//! handle.send(MessagePayload::Custom(vec![1, 2, 3])).await?;
54//! assert!(handle.is_running());
55//! # Ok::<(), actor_kit::Error>(()) }).unwrap();
56//! # scheduler.stop();
57//! # Ok(())
58//! # }
59//! ```
60//!
61//! ## Feature flags
62//!
63//! - `std` *(default)* — passthrough; the runtime is std-based.
64//! - `serde` — typed RPC (`rpc` module), serde impls on public types.
65//! - `zero-copy` — rkyv-backed zero-copy message path (`zero_copy` module).
66//! - `unsafe-pool` — bump-allocator memory pool (`memory_pool` module).
67//!   **The only `unsafe` code in the crate lives behind this flag.**
68//! - `sim` — deterministic simulation testing (`sim` module): a seeded
69//!   single-threaded scheduler replacement, virtual clock, fault injection,
70//!   and seed-replay traces. TigerBeetle-style DST; see the `sim` module docs.
71//! - `full` — all of the above.
72//!
73//! The crate carries `#![deny(unsafe_code)]`; `memory_pool` (behind
74//! `unsafe-pool`) is the single, loudly documented exception.
75
76#![deny(unsafe_code)]
77#![warn(missing_docs)]
78// Test code asserts invariants directly; unwrap/expect keeps failures loud.
79#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
80
81pub mod error;
82mod executor;
83mod handle;
84mod mailbox;
85#[cfg(feature = "unsafe-pool")]
86pub mod memory_pool;
87pub mod policy;
88pub mod queue;
89mod registry;
90#[cfg(feature = "serde")]
91pub mod rpc;
92mod scheduler;
93// The deterministic sim module relies on invariants (unique ids, peeked
94// non-empty queues, uncontended Mutexes) where unwrap/expect is intentional.
95#[cfg_attr(feature = "sim", allow(clippy::unwrap_used))]
96#[cfg(feature = "sim")]
97pub mod sim;
98pub mod supervisor;
99#[cfg(feature = "zero-copy")]
100pub mod zero_copy;
101
102pub use error::{Error, Result};
103pub use executor::{ActorExecutor, ExecutionResult, NullExecutor};
104pub use handle::{ActorBuilder, ActorHandle};
105pub use mailbox::{Mailbox, MailboxConfig};
106pub use policy::{NoopPolicy, ResourcePolicy};
107pub use queue::{create_local_queue, PriorityQueue, WorkQueue, WorkStealer};
108pub use registry::{ActorRegistry, ActorState, RegistryStats};
109#[cfg(feature = "serde")]
110pub use rpc::{
111    process_rpc_message, RpcClient, RpcEnvelope, RpcError, RpcHandler, RpcMessage, RpcRegistry,
112    RpcRequest, RpcResponse,
113};
114pub use scheduler::{
115    ActorScheduler, SchedulerConfig, SchedulerStats, StealerRegistry, WorkerStatsInfo,
116};
117pub use supervisor::{
118    ActorConfig, ChildSpec, ChildState, DegradationController, DegradationDecision,
119    EscalationAction, ExitReason, FnResourceMonitor, PressureLevel, ResourceMonitor, RestartPolicy,
120    StaticResourceMonitor, SupervisedChild, SupervisionStrategy, Supervisor, SupervisorError,
121    SupervisorHandle, SupervisorStats, SupervisorTree, SupervisorTreeStats,
122};
123
124use std::sync::Arc;
125use uuid::Uuid;
126
127/// Unique identifier for an actor.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
129#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
130pub struct ActorId(pub Uuid);
131
132impl ActorId {
133    /// Generate a new random actor ID.
134    pub fn new() -> Self {
135        Self(Uuid::new_v4())
136    }
137}
138
139impl Default for ActorId {
140    fn default() -> Self {
141        Self::new()
142    }
143}
144
145/// Priority level for actor messages.
146#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
147pub enum Priority {
148    /// Low priority (background tasks)
149    Low = 0,
150    /// Normal priority (default)
151    #[default]
152    Normal = 1,
153    /// High priority (time-sensitive)
154    High = 2,
155    /// Critical priority (system messages)
156    Critical = 3,
157}
158
159/// A message sent to an actor.
160#[derive(Debug, Clone)]
161pub struct Message {
162    /// Sender actor ID (None for system messages)
163    pub sender: Option<ActorId>,
164    /// Message type/payload
165    pub payload: MessagePayload,
166    /// Message priority
167    pub priority: Priority,
168}
169
170impl Default for Message {
171    fn default() -> Self {
172        Self {
173            sender: None,
174            payload: MessagePayload::Empty,
175            priority: Priority::Normal,
176        }
177    }
178}
179
180/// Payload of a message.
181#[derive(Debug, Clone, Default)]
182pub enum MessagePayload {
183    /// Start the actor
184    Start,
185    /// Stop the actor
186    Stop,
187    /// Custom binary payload
188    Custom(Vec<u8>),
189    /// System signal
190    Signal(Signal),
191    /// Default (empty)
192    #[default]
193    Empty,
194}
195
196/// System signals.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub enum Signal {
199    /// Pause execution
200    Pause,
201    /// Resume execution
202    Resume,
203    /// Restart the actor
204    Restart,
205}
206
207/// Trait for actor behavior.
208pub trait Actor: Send + Sync + 'static {
209    /// Handle a message.
210    fn handle(
211        &mut self,
212        msg: Message,
213        ctx: &ActorContext,
214    ) -> impl std::future::Future<Output = Result<()>> + Send;
215}
216
217/// Context provided to actors during message handling.
218pub struct ActorContext {
219    /// Actor's own ID
220    pub id: ActorId,
221    /// Scheduler handle for spawning work
222    scheduler: Arc<ActorScheduler>,
223}
224
225impl ActorContext {
226    /// Send a message to another actor.
227    pub async fn send(&self, target: ActorId, payload: MessagePayload) -> Result<()> {
228        self.scheduler
229            .send(
230                target,
231                Message {
232                    sender: Some(self.id),
233                    payload,
234                    priority: Priority::Normal,
235                },
236            )
237            .await
238    }
239
240    /// Send a high-priority message to another actor.
241    pub async fn send_high(&self, target: ActorId, payload: MessagePayload) -> Result<()> {
242        self.scheduler
243            .send(
244                target,
245                Message {
246                    sender: Some(self.id),
247                    payload,
248                    priority: Priority::High,
249                },
250            )
251            .await
252    }
253}
254
255/// Internal helper: a minimal single-threaded runtime for doctests/examples.
256#[doc(hidden)]
257#[allow(clippy::expect_used)] // doctest support: failure here is a bug, not recoverable
258pub fn rt() -> tokio::runtime::Runtime {
259    tokio::runtime::Builder::new_current_thread()
260        .enable_all()
261        .build()
262        .expect("failed to build runtime")
263}