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//! - `full` — all of the above.
69//!
70//! The crate carries `#![deny(unsafe_code)]`; `memory_pool` (behind
71//! `unsafe-pool`) is the single, loudly documented exception.
72
73#![deny(unsafe_code)]
74#![warn(missing_docs)]
75
76pub mod error;
77mod executor;
78mod handle;
79mod mailbox;
80#[cfg(feature = "unsafe-pool")]
81pub mod memory_pool;
82pub mod policy;
83pub mod queue;
84mod registry;
85#[cfg(feature = "serde")]
86pub mod rpc;
87mod scheduler;
88pub mod supervisor;
89#[cfg(feature = "zero-copy")]
90pub mod zero_copy;
91
92pub use error::{Error, Result};
93pub use executor::{ActorExecutor, ExecutionResult, NullExecutor};
94pub use handle::{ActorBuilder, ActorHandle};
95pub use mailbox::{Mailbox, MailboxConfig};
96pub use policy::{NoopPolicy, ResourcePolicy};
97pub use queue::{create_local_queue, PriorityQueue, WorkQueue, WorkStealer};
98pub use registry::{ActorRegistry, ActorState, RegistryStats};
99#[cfg(feature = "serde")]
100pub use rpc::{
101 process_rpc_message, RpcClient, RpcEnvelope, RpcError, RpcHandler, RpcMessage, RpcRegistry,
102 RpcRequest, RpcResponse,
103};
104pub use scheduler::{
105 ActorScheduler, SchedulerConfig, SchedulerStats, StealerRegistry, WorkerStatsInfo,
106};
107pub use supervisor::{
108 ActorConfig, ChildSpec, ChildState, DegradationController, DegradationDecision,
109 EscalationAction, ExitReason, FnResourceMonitor, PressureLevel, ResourceMonitor, RestartPolicy,
110 StaticResourceMonitor, SupervisedChild, SupervisionStrategy, Supervisor, SupervisorError,
111 SupervisorHandle, SupervisorStats, SupervisorTree, SupervisorTreeStats,
112};
113
114use std::sync::Arc;
115use uuid::Uuid;
116
117/// Unique identifier for an actor.
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
119#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
120pub struct ActorId(pub Uuid);
121
122impl ActorId {
123 /// Generate a new random actor ID.
124 pub fn new() -> Self {
125 Self(Uuid::new_v4())
126 }
127}
128
129impl Default for ActorId {
130 fn default() -> Self {
131 Self::new()
132 }
133}
134
135/// Priority level for actor messages.
136#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
137pub enum Priority {
138 /// Low priority (background tasks)
139 Low = 0,
140 /// Normal priority (default)
141 #[default]
142 Normal = 1,
143 /// High priority (time-sensitive)
144 High = 2,
145 /// Critical priority (system messages)
146 Critical = 3,
147}
148
149/// A message sent to an actor.
150#[derive(Debug, Clone)]
151pub struct Message {
152 /// Sender actor ID (None for system messages)
153 pub sender: Option<ActorId>,
154 /// Message type/payload
155 pub payload: MessagePayload,
156 /// Message priority
157 pub priority: Priority,
158}
159
160impl Default for Message {
161 fn default() -> Self {
162 Self {
163 sender: None,
164 payload: MessagePayload::Empty,
165 priority: Priority::Normal,
166 }
167 }
168}
169
170/// Payload of a message.
171#[derive(Debug, Clone, Default)]
172pub enum MessagePayload {
173 /// Start the actor
174 Start,
175 /// Stop the actor
176 Stop,
177 /// Custom binary payload
178 Custom(Vec<u8>),
179 /// System signal
180 Signal(Signal),
181 /// Default (empty)
182 #[default]
183 Empty,
184}
185
186/// System signals.
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188pub enum Signal {
189 /// Pause execution
190 Pause,
191 /// Resume execution
192 Resume,
193 /// Restart the actor
194 Restart,
195}
196
197/// Trait for actor behavior.
198pub trait Actor: Send + Sync + 'static {
199 /// Handle a message.
200 fn handle(
201 &mut self,
202 msg: Message,
203 ctx: &ActorContext,
204 ) -> impl std::future::Future<Output = Result<()>> + Send;
205}
206
207/// Context provided to actors during message handling.
208pub struct ActorContext {
209 /// Actor's own ID
210 pub id: ActorId,
211 /// Scheduler handle for spawning work
212 scheduler: Arc<ActorScheduler>,
213}
214
215impl ActorContext {
216 /// Send a message to another actor.
217 pub async fn send(&self, target: ActorId, payload: MessagePayload) -> Result<()> {
218 self.scheduler
219 .send(
220 target,
221 Message {
222 sender: Some(self.id),
223 payload,
224 priority: Priority::Normal,
225 },
226 )
227 .await
228 }
229
230 /// Send a high-priority message to another actor.
231 pub async fn send_high(&self, target: ActorId, payload: MessagePayload) -> Result<()> {
232 self.scheduler
233 .send(
234 target,
235 Message {
236 sender: Some(self.id),
237 payload,
238 priority: Priority::High,
239 },
240 )
241 .await
242 }
243}
244
245/// Internal helper: a minimal single-threaded runtime for doctests/examples.
246#[doc(hidden)]
247pub fn rt() -> tokio::runtime::Runtime {
248 tokio::runtime::Builder::new_current_thread()
249 .enable_all()
250 .build()
251 .expect("failed to build runtime")
252}