1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
use crate::actor::ActorId;
use crate::compute::{ComputeError, ComputeHandle, Task, TaskId};
use crate::error::RuntimeError;
use crate::runtime::MessageEnvelope;
use crate::timer::{TimerHandle, TimerId};
use std::collections::HashMap;
use std::sync::{Arc, RwLock, atomic::AtomicBool};
type SenderMap = Arc<RwLock<HashMap<ActorId, crossbeam_channel::Sender<MessageEnvelope>>>>;
type ReplySender = crossbeam_channel::Sender<Box<dyn std::any::Any + Send>>;
/// Request to spawn a new child actor (Pattern 2 dynamic supervision).
#[cfg(feature = "hot_code_loading")]
pub struct SpawnRequest {
/// Module name to look up in CodeManager for the current vtable
pub module_name: String,
/// Initial state bytes for the child actor
pub initial_state: Vec<u8>,
}
/// Context provided to actor handlers.
pub struct ActorContext {
actor_id: ActorId,
_sender: crossbeam_channel::Sender<MessageEnvelope>,
senders: Option<SenderMap>,
reply_sender: Option<ReplySender>,
compute_sender: Option<crossbeam_channel::Sender<Task>>,
timer_handle: Option<TimerHandle>,
#[cfg(feature = "hot_code_loading")]
spawn_tx: Option<crossbeam_channel::Sender<SpawnRequest>>,
}
impl ActorContext {
pub(crate) fn new(
actor_id: ActorId,
sender: crossbeam_channel::Sender<MessageEnvelope>,
) -> Self {
Self {
actor_id,
_sender: sender,
senders: None,
reply_sender: None,
compute_sender: None,
timer_handle: None,
#[cfg(feature = "hot_code_loading")]
spawn_tx: None,
}
}
pub(crate) fn set_senders(&mut self, senders: SenderMap) {
self.senders = Some(senders);
}
pub(crate) fn set_reply_sender(&mut self, reply_sender: Option<ReplySender>) {
self.reply_sender = reply_sender;
}
pub(crate) fn set_compute_sender(&mut self, compute_sender: crossbeam_channel::Sender<Task>) {
self.compute_sender = Some(compute_sender);
}
#[cfg(feature = "hot_code_loading")]
pub(crate) fn set_spawn_child_req_tx(
&mut self,
tx: crossbeam_channel::Sender<crate::actor::context::SpawnRequest>,
) {
self.spawn_tx = Some(tx);
}
pub(crate) fn set_timer_handle(&mut self, timer_handle: TimerHandle) {
self.timer_handle = Some(timer_handle);
}
/// Get the ID of the current actor.
pub fn actor_id(&self) -> ActorId {
self.actor_id
}
/// Send a fire-and-forget message to another actor.
///
/// This is the actor-to-actor messaging primitive. Messages are queued
/// in the target actor's mailbox and delivered asynchronously.
///
/// # Errors
///
/// - [`RuntimeError::ActorNotFound`] if `target` doesn't exist.
/// - [`RuntimeError::RuntimeStopped`] if the runtime has shut down.
pub fn send_to<M: Send + 'static>(
&self,
target: ActorId,
message: M,
) -> Result<(), crate::error::RuntimeError> {
let senders = self
.senders
.as_ref()
.ok_or(crate::error::RuntimeError::RuntimeStopped)?;
let senders = senders
.read()
.map_err(|_| crate::error::RuntimeError::RuntimeStopped)?;
let sender = senders
.get(&target)
.ok_or(crate::error::RuntimeError::ActorNotFound(target))?;
sender
.send(MessageEnvelope::Message(Box::new(message)))
.map_err(|_| crate::error::RuntimeError::RuntimeStopped)
}
/// Reply to the sender of the current request.
///
/// If the current message was sent via [`crate::Runtime::request`], this sends
/// the reply back to the caller. If the message was fire-and-forget,
/// this is a no-op.
pub fn reply<M: Send + 'static>(&self, message: M) -> Result<(), crate::error::RuntimeError> {
if let Some(ref reply_tx) = self.reply_sender {
reply_tx
.send(Box::new(message))
.map_err(|_| crate::error::RuntimeError::RuntimeStopped)
} else {
Ok(())
}
}
/// Returns `true` if the current message was sent as a request
/// (i.e., the sender expects a reply via [`ActorContext::reply`]).
pub fn is_request(&self) -> bool {
self.reply_sender.is_some()
}
/// Submit a CPU-intensive task to the compute pool.
///
/// Returns a `ComputeHandle` that can be used to receive the result.
/// The actor should store this handle and poll it later (e.g., on the next message).
/// This is non-blocking — the task runs on a compute worker thread.
pub fn spawn_compute<F, T>(&self, job: F) -> Result<ComputeHandle<T>, ComputeError>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
let sender = self
.compute_sender
.as_ref()
.ok_or(ComputeError::SchedulerShutdown)?;
let (result_sender, result_receiver) = crossbeam_channel::bounded(1);
let cancelled = Arc::new(AtomicBool::new(false));
let task = Task {
id: TaskId::new(),
job: Box::new(move || Box::new(job()) as Box<dyn std::any::Any + Send>),
result_sender,
created_at: std::time::Instant::now(),
cancelled: cancelled.clone(),
};
sender
.send(task)
.map_err(|_| ComputeError::SchedulerShutdown)?;
Ok(ComputeHandle::new(result_receiver, cancelled))
}
/// Schedule a one-shot timer that sends a message to this actor after a delay.
///
/// Returns a [`TimerId`] that can be passed to [`ActorContext::cancel_timer`]
/// to cancel the timer before it fires.
pub fn schedule_timer<M: Send + 'static>(
&self,
duration: std::time::Duration,
message: M,
) -> Result<TimerId, RuntimeError> {
let handle = self
.timer_handle
.as_ref()
.ok_or(RuntimeError::RuntimeStopped)?;
Ok(handle.schedule_timer(duration, self.actor_id, message))
}
/// Schedule a periodic timer that sends a message to this actor at intervals.
///
/// The message must be `Clone + Send + Sync` because it is cloned for
/// each tick. Returns a [`TimerId`] for cancellation.
pub fn schedule_interval<M: Clone + Send + Sync + 'static>(
&self,
interval: std::time::Duration,
message: M,
) -> Result<TimerId, RuntimeError> {
let handle = self
.timer_handle
.as_ref()
.ok_or(RuntimeError::RuntimeStopped)?;
Ok(handle.schedule_interval(interval, self.actor_id, message))
}
/// Cancel a previously scheduled timer.
pub fn cancel_timer(&self, timer_id: TimerId) {
if let Some(ref handle) = self.timer_handle {
handle.cancel_timer(timer_id);
}
}
/// Spawn a child actor using the current hot code loading version.
///
/// This is the Pattern 2 dynamic supervision primitive. The supervisor
/// sends a spawn request to the runtime via a channel. The runtime
/// processes this request using the `ActorFactory` (which always uses
/// the current version from `CodeManager`).
///
/// The child actor will be spawned with the **current** version of the
/// module — so after a hot code upgrade, new children automatically use
/// the new code.
///
/// This is non-blocking: the request is sent via the channel and the
/// runtime handles the actual spawn.
///
/// # Errors
///
/// - [`RuntimeError::RuntimeStopped`] if the spawn channel is not configured
/// (i.e., the `hot_code_loading` feature is not enabled) or the runtime
/// has shut down.
#[cfg(feature = "hot_code_loading")]
#[cfg_attr(docsrs, doc(cfg(feature = "hot_code_loading")))]
pub fn spawn_child(
&self,
module_name: &str,
initial_state: Vec<u8>,
) -> Result<(), RuntimeError> {
let tx = self.spawn_tx.as_ref().ok_or(RuntimeError::RuntimeStopped)?;
tx.send(SpawnRequest {
module_name: module_name.to_string(),
initial_state,
})
.map_err(|_| RuntimeError::RuntimeStopped)
}
}