rsactor 0.16.0

A Simple and Efficient In-Process Actor Model Implementation for Rust.
Documentation
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// Copyright 2022 Jeff Kim <hiking90@gmail.com>
// SPDX-License-Identifier: Apache-2.0

use crate::Actor;
use std::fmt::Debug;

/// Represents the phase during which an actor failure occurred.
///
/// This enum is used to identify which lifecycle method of an actor
/// caused a failure, enabling more precise error handling and debugging.
/// Each phase corresponds to a specific method in the [`Actor`](crate::Actor) trait.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FailurePhase {
    /// Actor failed during the [`on_start`](crate::Actor::on_start) lifecycle hook.
    OnStart,
    /// Actor failed during execution in the [`on_idle`](crate::Actor::on_idle) lifecycle hook.
    OnIdle,
    /// Actor failed during the [`on_stop`](crate::Actor::on_stop) lifecycle hook.
    OnStop,
    /// Actor failed during [`on_idle`](crate::Actor::on_idle), and then
    /// [`on_stop`](crate::Actor::on_stop) also failed during cleanup.
    /// The primary `on_idle` error is exposed via [`ActorResult::error`]; the
    /// `on_stop` error is exposed via [`ActorResult::secondary_error`].
    OnIdleThenOnStop,
}

/// Implements Display for FailurePhase to provide human-readable error messages.
///
/// This allows `FailurePhase` to be easily converted to strings for logging,
/// error reporting, and debugging purposes.
impl std::fmt::Display for FailurePhase {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FailurePhase::OnStart => write!(f, "OnStart"),
            FailurePhase::OnIdle => write!(f, "OnIdle"),
            FailurePhase::OnStop => write!(f, "OnStop"),
            FailurePhase::OnIdleThenOnStop => write!(f, "OnIdleThenOnStop"),
        }
    }
}

/// Result type returned when an actor's lifecycle completes.
///
/// `ActorResult` encapsulates the final state of an actor after its lifecycle has ended,
/// whether it completed successfully or failed. This is typically obtained when awaiting the
/// `JoinHandle` returned by [`spawn`](crate::spawn) or [`spawn_with_mailbox_capacity`](crate::spawn_with_mailbox_capacity).
/// It provides detailed information about the actor's termination state, including:
///
/// - Whether the actor completed successfully or failed
/// - Whether the actor was killed forcefully or stopped gracefully
/// - The phase in which a failure occurred (if applicable)
/// - The actor instance itself (if recoverable)
/// - The error that caused a failure (if applicable)
///
/// # Usage Patterns
///
/// ## Basic Error Handling
/// ```rust,no_run
/// # use rsactor::{Actor, ActorRef, spawn, ActorResult};
/// # use anyhow::Result;
/// # struct MyActor;
/// # impl Actor for MyActor {
/// #     type Args = ();
/// #     type Error = anyhow::Error;
/// #     type IdleEvent = ();
/// #     async fn on_start(_: (), _: &ActorRef<Self>) -> Result<Self> { Ok(MyActor) }
/// # }
/// # async fn example() -> Result<()> {
/// let (actor_ref, join_handle) = spawn::<MyActor>(());
///
/// match join_handle.await? {
///     ActorResult::Completed { actor, killed } => {
///         println!("Actor completed successfully, killed: {}", killed);
///         // Use the recovered actor instance
///     }
///     ActorResult::Failed { error, phase, .. } => {
///         eprintln!("Actor failed in phase {:?}: {}", phase, error);
///         // Handle the error appropriately
///     }
/// }
/// # Ok(())
/// # }
/// ```
///
/// ## Actor Supervision
/// ```rust,no_run
/// # use rsactor::{Actor, ActorRef, spawn, ActorResult, FailurePhase};
/// # use anyhow::Result;
/// # struct MyActor;
/// # impl Actor for MyActor {
/// #     type Args = ();
/// #     type Error = anyhow::Error;
/// #     type IdleEvent = ();
/// #     async fn on_start(_: (), _: &ActorRef<Self>) -> Result<Self> { Ok(MyActor) }
/// # }
/// # async fn restart_actor() -> Result<(ActorRef<MyActor>, tokio::task::JoinHandle<ActorResult<MyActor>>)> {
/// #     Ok(spawn::<MyActor>(()))
/// # }
/// # async fn supervision_example() -> Result<()> {
/// let (actor_ref, join_handle) = spawn::<MyActor>(());
///
/// match join_handle.await? {
///     result if result.is_startup_failed() => {
///         // Actor failed to start - may need different initialization
///         eprintln!("Startup failed, checking configuration...");
///     }
///     result if result.is_runtime_failed() => {
///         // Runtime failure - restart the actor
///         if let Some(actor) = result.into_actor() {
///             println!("Restarting actor after runtime failure...");
///             let (new_ref, new_handle) = restart_actor().await?;
///         }
///     }
///     result if result.was_killed() => {
///         // Actor was forcefully terminated
///         println!("Actor was killed - no restart needed");
///     }
///     _ => {
///         // Normal completion
///         println!("Actor completed normally");
///     }
/// }
/// # Ok(())
/// # }
/// ```
///
/// This enum is typically returned by actor supervision systems or when awaiting the
/// completion of an actor's task.
#[derive(Debug)]
pub enum ActorResult<T: Actor> {
    /// Actor completed successfully and can be recovered.
    ///
    /// This variant indicates that the actor finished its lifecycle without errors.
    Completed {
        /// The successfully completed actor instance
        actor: T,
        /// Whether the actor was killed (`true`) or stopped gracefully (`false`)
        killed: bool,
    },
    /// Actor failed during one of its lifecycle phases.
    ///
    /// This variant indicates that the actor encountered an error during execution.
    Failed {
        /// The actor instance (if recoverable), or None if not recoverable.
        /// This will be `None` specifically when the failure occurred during the [`on_start`](Actor::on_start) phase,
        /// as the actor wasn't fully initialized.
        actor: Option<T>,
        /// The error that caused the failure (the primary cause).
        ///
        /// For [`FailurePhase::OnIdleThenOnStop`] this holds the original `on_idle` error;
        /// the subsequent `on_stop` error is exposed via the `secondary_error` field
        /// (or the [`ActorResult::secondary_error`] accessor).
        error: T::Error,
        /// Secondary error, set only when a *cleanup* hook also failed after the primary failure.
        ///
        /// Currently set only for [`FailurePhase::OnIdleThenOnStop`], where it carries the
        /// `on_stop` error that was emitted while cleaning up after a failed `on_idle`.
        /// `None` for every other phase.
        secondary_error: Option<T::Error>,
        /// The lifecycle phase during which the failure occurred
        phase: FailurePhase,
        /// Whether the actor was killed (`true`) or was attempting to stop gracefully (`false`)
        killed: bool,
    },
}

/// Conversion from ActorResult to a tuple of (`Option<Actor>`, `Option<Error>`)
///
/// This allows extracting both the actor instance and error (if any) in a single operation.
/// Useful for pattern matching and destructuring in supervision contexts.
///
/// # Example
/// ```ignore
/// let (maybe_actor, maybe_error) = actor_result.into();
/// if let Some(actor) = maybe_actor {
///     // The actor is available (either completed or recovered after failure)
/// }
/// if let Some(error) = maybe_error {
///     // An error occurred
/// }
/// ```
impl<T: Actor> From<ActorResult<T>> for (Option<T>, Option<T::Error>) {
    fn from(result: ActorResult<T>) -> Self {
        match result {
            ActorResult::Completed { actor, .. } => (Some(actor), None),
            ActorResult::Failed {
                actor,
                error: cause,
                ..
            } => (actor, Some(cause)),
        }
    }
}

impl<T: Actor> ActorResult<T> {
    /// Returns `true` if the actor completed successfully.
    ///
    /// This method checks if the actor finished its lifecycle without any errors,
    /// regardless of whether it was killed or stopped normally.
    pub fn is_completed(&self) -> bool {
        matches!(self, ActorResult::Completed { .. })
    }

    /// Returns `true` if the actor was killed.
    ///
    /// An actor is considered killed if it was terminated forcefully via the [`kill()`](crate::ActorRef::kill()) method,
    /// regardless of whether it completed successfully or failed. Both `ActorResult::Completed`
    /// and `ActorResult::Failed` can have `killed: true`.
    pub fn was_killed(&self) -> bool {
        matches!(
            self,
            ActorResult::Completed { killed: true, .. } | ActorResult::Failed { killed: true, .. }
        )
    }

    /// Returns `true` if the actor stopped normally.
    ///
    /// An actor stopped normally if it completed successfully without being killed,
    /// typically by processing a `StopGracefully` message or reaching the end of its lifecycle.
    pub fn stopped_normally(&self) -> bool {
        matches!(self, ActorResult::Completed { killed: false, .. })
    }

    /// Returns `true` if the actor failed to start.
    ///
    /// This indicates that the actor failed during the [`on_start`](crate::Actor::on_start) lifecycle phase,
    /// which means it couldn't initialize properly.
    pub fn is_startup_failed(&self) -> bool {
        matches!(
            self,
            ActorResult::Failed {
                phase: FailurePhase::OnStart,
                ..
            }
        )
    }

    /// Returns `true` if the actor failed during runtime.
    ///
    /// This indicates that the actor started successfully but encountered an error
    /// during its normal operation in the [`on_idle`](crate::Actor::on_idle) lifecycle phase.
    /// Also returns `true` when `on_stop` additionally failed during cleanup
    /// ([`FailurePhase::OnIdleThenOnStop`]).
    pub fn is_runtime_failed(&self) -> bool {
        matches!(
            self,
            ActorResult::Failed {
                phase: FailurePhase::OnIdle | FailurePhase::OnIdleThenOnStop,
                ..
            }
        )
    }

    /// Returns `true` if `on_stop` also failed after an `on_idle` error.
    ///
    /// The primary `on_idle` error is exposed via [`error()`](Self::error); the
    /// `on_stop` cleanup error is exposed via [`secondary_error()`](Self::secondary_error).
    pub fn is_cleanup_failed(&self) -> bool {
        matches!(
            self,
            ActorResult::Failed {
                phase: FailurePhase::OnIdleThenOnStop,
                ..
            }
        )
    }

    /// Returns `true` if the actor failed during the stop phase.
    ///
    /// This indicates that the actor encountered an error while trying to shut down
    /// in the [`on_stop`](crate::Actor::on_stop) lifecycle phase.
    pub fn is_stop_failed(&self) -> bool {
        matches!(
            self,
            ActorResult::Failed {
                phase: FailurePhase::OnStop,
                ..
            }
        )
    }

    /// Returns the actor instance if available, regardless of the result type.
    ///
    /// If the actor completed successfully, it will always return `Some(actor)`.
    /// If the actor failed, it may return `Some(actor)` or `None` depending on
    /// when the failure occurred and if the actor instance could be recovered.
    ///
    /// If the failure occurred during the [`on_start`](crate::Actor::on_start) phase, this will return `None`
    /// since the actor was not successfully initialized.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use rsactor::{ActorResult, Actor, ActorRef};
    /// # struct MyActor;
    /// # impl Actor for MyActor {
    /// #     type Args = ();
    /// #     type Error = anyhow::Error;
    /// #     type IdleEvent = ();
    /// #     async fn on_start(_: (), _: &ActorRef<Self>) -> Result<Self, Self::Error> { Ok(MyActor) }
    /// # }
    /// # fn example(result: ActorResult<MyActor>) {
    /// if let Some(actor) = result.actor() {
    ///     // Actor instance is available - can inspect its state
    ///     println!("Actor instance recovered");
    /// } else {
    ///     // Actor failed during initialization
    ///     println!("Actor not available (startup failure)");
    /// }
    /// # }
    /// ```
    pub fn actor(&self) -> Option<&T> {
        match self {
            ActorResult::Completed { actor, .. } => Some(actor),
            ActorResult::Failed { actor, .. } => actor.as_ref(),
        }
    }

    /// Consumes the result and returns the actor instance if available.
    ///
    /// This method is similar to [`actor()`](ActorResult::actor()) but it consumes the `ActorResult`,
    /// giving ownership of the actor to the caller if available.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use rsactor::{ActorResult, Actor, ActorRef};
    /// # struct MyActor { state: String }
    /// # impl Actor for MyActor {
    /// #     type Args = ();
    /// #     type Error = anyhow::Error;
    /// #     type IdleEvent = ();
    /// #     async fn on_start(_: (), _: &ActorRef<Self>) -> Result<Self, Self::Error> {
    /// #         Ok(MyActor { state: "ready".to_string() })
    /// #     }
    /// # }
    /// # fn example(result: ActorResult<MyActor>) {
    /// if let Some(actor) = result.into_actor() {
    ///     // Take ownership of the actor for reuse or state inspection
    ///     println!("Actor final state: {}", actor.state);
    /// }
    /// # }
    /// ```
    pub fn into_actor(self) -> Option<T> {
        match self {
            ActorResult::Completed { actor, .. } => Some(actor),
            ActorResult::Failed { actor, .. } => actor,
        }
    }

    /// Returns the error if the result represents a failure.
    ///
    /// If the actor completed successfully, this returns `None`.
    /// If the actor failed, this returns `Some(error)` containing the error that caused the failure.
    pub fn error(&self) -> Option<&T::Error> {
        match self {
            ActorResult::Completed { .. } => None,
            ActorResult::Failed { error: cause, .. } => Some(cause),
        }
    }

    /// Consumes the result and returns the error if it represents a failure.
    ///
    /// This method is similar to [`error()`](ActorResult::error()) but it consumes the `ActorResult`,
    /// giving ownership of the error to the caller if available.
    pub fn into_error(self) -> Option<T::Error> {
        match self {
            ActorResult::Completed { .. } => None,
            ActorResult::Failed { error: cause, .. } => Some(cause),
        }
    }

    /// Returns the secondary error if a cleanup hook also failed.
    ///
    /// Currently populated only when [`is_cleanup_failed()`](Self::is_cleanup_failed)
    /// is `true` (phase [`FailurePhase::OnIdleThenOnStop`]). In that case, the value
    /// is the error returned by `on_stop` during cleanup; the primary `on_idle` error
    /// remains accessible via [`error()`](Self::error).
    pub fn secondary_error(&self) -> Option<&T::Error> {
        match self {
            ActorResult::Failed {
                secondary_error, ..
            } => secondary_error.as_ref(),
            ActorResult::Completed { .. } => None,
        }
    }

    /// Consumes the result and returns the secondary error if a cleanup hook also failed.
    ///
    /// See [`secondary_error()`](Self::secondary_error) for semantics.
    pub fn into_secondary_error(self) -> Option<T::Error> {
        match self {
            ActorResult::Failed {
                secondary_error, ..
            } => secondary_error,
            ActorResult::Completed { .. } => None,
        }
    }

    /// Returns true if the result represents any kind of failure.
    ///
    /// This is the logical opposite of [`is_completed()`](ActorResult::is_completed()).
    pub fn is_failed(&self) -> bool {
        !self.is_completed()
    }

    /// Returns true if the result contains an actor instance.
    ///
    /// This checks if the actor instance is available, regardless of
    /// whether the actor completed successfully or failed.
    pub fn has_actor(&self) -> bool {
        self.actor().is_some()
    }

    /// Converts to a standard Result, preserving the actor on success
    ///
    /// This transforms the `ActorResult<T>` into a `Result<T, T::Error>`,
    /// which is useful for integrating with Rust's standard error handling patterns.
    ///
    /// **Note**: This method discards information about whether the actor was killed
    /// and the failure phase. Use the individual query methods if you need this information.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use rsactor::{ActorResult, Actor, ActorRef};
    /// # struct MyActor;
    /// # impl Actor for MyActor {
    /// #     type Args = ();
    /// #     type Error = anyhow::Error;
    /// #     type IdleEvent = ();
    /// #     async fn on_start(_: (), _: &ActorRef<Self>) -> Result<Self, Self::Error> { Ok(MyActor) }
    /// # }
    /// # fn example(result: ActorResult<MyActor>) -> Result<MyActor, anyhow::Error> {
    /// // Convert to standard Result for use with ? operator
    /// let actor = result.to_result()?;
    /// Ok(actor)
    /// # }
    /// ```
    pub fn to_result(self) -> std::result::Result<T, T::Error> {
        match self {
            ActorResult::Completed { actor, .. } => Ok(actor),
            ActorResult::Failed { error: cause, .. } => Err(cause),
        }
    }
}