atomr_core/actor/traits.rs
1//! Core `Actor` trait and message envelope.
2
3use async_trait::async_trait;
4
5use super::context::Context;
6use super::sender::Sender;
7use crate::supervision::SupervisorStrategy;
8
9/// Envelope that carries a user message plus a typed [`Sender`].
10///
11/// `M` is the actor's user message type. The [`Sender`] preserves the
12/// origin's identity end-to-end (no `Any::downcast` on reply paths) —
13/// see `docs/idiomatic-rust.md` (P-1) and Phase 1 of
14/// `docs/full-port-plan.md`.
15pub struct MessageEnvelope<M> {
16 pub message: M,
17 pub sender: Sender,
18}
19
20impl<M> MessageEnvelope<M> {
21 pub fn new(message: M) -> Self {
22 Self { message, sender: Sender::None }
23 }
24
25 /// Construct with a typed [`Sender`].
26 pub fn with_typed_sender(message: M, sender: Sender) -> Self {
27 Self { message, sender }
28 }
29}
30
31/// The user-facing `Actor` trait.
32///
33/// is expressed here as: each actor has an
34/// associated `Msg` type (typically an enum) and implements an async
35/// `handle` that matches on it.
36#[async_trait]
37pub trait Actor: Sized + Send + 'static {
38 type Msg: Send + 'static;
39
40 /// Process a single message.
41 async fn handle(&mut self, ctx: &mut Context<Self>, msg: Self::Msg);
42
43 /// Called once before the first message.
44 async fn pre_start(&mut self, _ctx: &mut Context<Self>) {}
45
46 /// Called after the actor has been stopped.
47 async fn post_stop(&mut self, _ctx: &mut Context<Self>) {}
48
49 /// Called when the actor is about to be restarted by the supervisor.
50 async fn pre_restart(&mut self, _ctx: &mut Context<Self>, _err: &str) {}
51
52 /// Called after a restart.
53 async fn post_restart(&mut self, _ctx: &mut Context<Self>, _err: &str) {}
54
55 /// Called when a watched actor terminates. The `path` argument is
56 /// the path of the actor that just stopped. Default is a no-op.
57 /// Implementations may translate this into a user-visible message
58 /// (the Python binding does this for `Terminated` events).
59 async fn on_terminated(&mut self, _ctx: &mut Context<Self>, _path: &super::path::ActorPath) {}
60
61 /// The supervisor strategy this actor applies to its own children.
62 fn supervisor_strategy(&self) -> SupervisorStrategy {
63 SupervisorStrategy::default()
64 }
65}