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