basic_actor/
basic_actor.rs

1use actor12::prelude::*;
2use actor12::{spawn, Envelope, MpscChannel, Init, Exec};
3use std::future::Future;
4
5// Define a simple counter actor
6pub struct Counter {
7    count: i32,
8}
9
10// Messages the counter can handle
11#[derive(Debug)]
12pub struct Increment;
13
14#[derive(Debug)]
15pub struct GetCount;
16
17// Actor implementation
18impl Actor for Counter {
19    type Spec = i32; // initial count
20    type Message = Envelope<(), anyhow::Result<()>>; // Simple envelope for increment
21    type Channel = MpscChannel<Self::Message>;
22    type Cancel = ();
23    type State = ();
24
25    fn state(_spec: &Self::Spec) -> Self::State {}
26
27    fn init(ctx: Init<'_, Self>) -> impl Future<Output = Result<Self, Self::Cancel>> + Send + 'static {
28        let initial_count = ctx.spec;
29        async move {
30            println!("Counter actor initialized with count: {}", initial_count);
31            Ok(Counter { count: initial_count })
32        }
33    }
34
35    async fn handle(&mut self, _ctx: Exec<'_, Self>, msg: Self::Message) {
36        self.count += 1;
37        println!("Count incremented to: {}", self.count);
38        let _ = msg.reply.send(Ok(()));
39    }
40}
41
42// Define a separate counter for getting count
43pub struct CounterReader {
44    counter_value: i32,
45}
46
47impl Actor for CounterReader {
48    type Spec = i32;
49    type Message = Envelope<(), anyhow::Result<i32>>;
50    type Channel = MpscChannel<Self::Message>;
51    type Cancel = ();
52    type State = ();
53
54    fn state(_spec: &Self::Spec) -> Self::State {}
55
56    fn init(ctx: Init<'_, Self>) -> impl Future<Output = Result<Self, Self::Cancel>> + Send + 'static {
57        let initial_count = ctx.spec;
58        async move {
59            Ok(CounterReader { counter_value: initial_count })
60        }
61    }
62
63    async fn handle(&mut self, _ctx: Exec<'_, Self>, msg: Self::Message) {
64        println!("Current count requested: {}", self.counter_value);
65        let _ = msg.reply.send(Ok(self.counter_value));
66    }
67}
68
69#[tokio::main]
70async fn main() -> anyhow::Result<()> {
71    // Spawn a counter actor with initial value 0
72    let counter = spawn::<Counter>(0);
73
74    // Send increment messages
75    counter.send(()).await?;
76    counter.send(()).await?;
77    counter.send(()).await?;
78
79    println!("Sent 3 increment messages");
80
81    // For demonstration, we'll just show that we can increment
82    // A real multi-message actor would use the Multi<A> pattern
83    // as shown in the integration tests
84
85    Ok(())
86}