reifydb_runtime/actor/traits.rs
1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (c) 2025 ReifyDB
3
4//! Core actor trait and associated types.
5//!
6//! This module defines the fundamental abstractions for the actor model:
7//! - [`Actor`]: The trait that all actors must implement
8//! - [`Directive`]: Control flow for actor scheduling
9//! - [`ActorConfig`]: Configuration for actor behavior
10
11use crate::actor::{context::Context, system::ActorConfig};
12
13/// What the actor wants to do after handling a message.
14///
15/// This enum controls actor behavior after processing each message.
16///
17/// - **Native**: Actors run as batched tasks on a shared rayon pool. `Yield` ends the current batch and resubmits to
18/// the back of the pool queue. `Park` goes idle until a new message arrives (zero pool resource usage).
19/// - **WASM**: Messages are processed inline (synchronously), so `Yield` and `Park` are no-ops.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum Directive {
22 /// Keep processing messages immediately (up to batch limit).
23 Continue,
24
25 /// End current batch, resubmit to back of pool queue.
26 Yield,
27
28 /// Go idle until a new message arrives. The actor consumes zero pool
29 /// resources while parked.
30 Park,
31
32 /// Stop this actor permanently.
33 ///
34 /// The actor's `post_stop` hook will be called, and the actor
35 /// will be removed from the system.
36 Stop,
37}
38
39pub trait Actor: Send + Sync + 'static {
40 /// The actor's internal state (owned, not shared).
41 type State: Send + 'static;
42
43 /// Messages this actor can receive.
44 type Message: Send + 'static;
45
46 /// Create initial state. Called on start and restart.
47 fn init(&self, ctx: &Context<Self::Message>) -> Self::State;
48
49 /// Handle a single message. This is the core of the actor.
50 ///
51 /// Return `Directive` to control scheduling:
52 /// - `Continue`: Process next message immediately
53 /// - `Yield`: Give other actors a chance to run
54 /// - `Park`: Sleep until a message arrives
55 /// - `Stop`: Terminate this actor
56 fn handle(&self, state: &mut Self::State, msg: Self::Message, ctx: &Context<Self::Message>) -> Directive;
57
58 /// Called when the mailbox is empty.
59 ///
60 /// Use for:
61 /// - Background/periodic work
62 /// - Polling external state
63 /// - Cleanup tasks
64 ///
65 /// Default: Park (sleep until message arrives)
66 #[allow(unused_variables)]
67 fn idle(&self, ctx: &Context<Self::Message>) -> Directive {
68 Directive::Park
69 }
70
71 /// Called once after actor stops (always called, even on panic).
72 fn post_stop(&self) {}
73
74 /// Actor configuration. Override for custom settings.
75 fn config(&self) -> ActorConfig {
76 ActorConfig::default()
77 }
78}