Skip to main content

reifydb_runtime/actor/
traits.rs

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