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
//! WeakRecipient example
//!
//! With a weak recipient you can register any client actor's addrs with a
//! service and still get cleaned up correctly when the client actor is
//! stopped. In contrast to a `WeakAddr` the Service is not bound to know
//! exactly which type of client actor is registering itself.

use std::time::{Duration, Instant};

use actix::{prelude::*, Actor, Context, WeakRecipient};

#[derive(Message, Debug)]
#[rtype(result = "()")]
pub struct TimePing(Instant);

#[derive(Message, Debug)]
#[rtype(result = "()")]
pub struct RegisterForTime(pub WeakRecipient<TimePing>);

#[derive(Debug, Default)]
pub struct TimeService {
    clients: Vec<WeakRecipient<TimePing>>,
}

impl TimeService {
    fn send_tick(&mut self, _ctx: &mut Context<Self>) {
        for client in self.clients.iter() {
            if let Some(client) = client.upgrade() {
                client.do_send(TimePing(Instant::now()));
                println!("⏰ sent ping to client {:?}", client);
            } else {
                println!("⏰ client can no longer be upgraded");
            }
        }

        // gc
        self.clients = self
            .clients
            .drain(..)
            .filter(|c| c.upgrade().is_some())
            .collect();
        println!("⏰ service has {} clients", self.clients.len());
    }
}

impl Actor for TimeService {
    type Context = Context<Self>;

    fn started(&mut self, ctx: &mut Self::Context) {
        println!("⏰ starting TimeService");
        ctx.run_interval(Duration::from_millis(1_000), Self::send_tick);
    }

    fn stopping(&mut self, _ctx: &mut Self::Context) -> Running {
        println!("⏰ stopping TimeService");
        Running::Stop
    }

    fn stopped(&mut self, _ctx: &mut Self::Context) {
        println!("⏰ stopped TimeService");
    }
}

impl Handler<RegisterForTime> for TimeService {
    type Result = ();

    fn handle(
        &mut self,
        RegisterForTime(client): RegisterForTime,
        _ctx: &mut Self::Context,
    ) -> Self::Result {
        println!("⏰ received registration");
        self.clients.push(client);
    }
}

impl Supervised for TimeService {}
impl SystemService for TimeService {}

#[derive(Debug, Default)]
pub struct ClientA;

impl Actor for ClientA {
    type Context = Context<Self>;

    fn started(&mut self, ctx: &mut Self::Context) {
        println!("🐰 starting ClientA");
        TimeService::from_registry()
            .send(RegisterForTime(ctx.address().downgrade().recipient()))
            .into_actor(self)
            .then(|_, _slf, _| fut::ready(()))
            .spawn(ctx);
    }

    fn stopping(&mut self, _ctx: &mut Self::Context) -> Running {
        println!("🐰 stopping ClientA");
        Running::Stop
    }

    fn stopped(&mut self, _ctx: &mut Self::Context) {
        println!("🐰 stopped ClientA");
    }
}

impl Handler<TimePing> for ClientA {
    type Result = ();

    fn handle(&mut self, msg: TimePing, _ctx: &mut Self::Context) -> Self::Result {
        println!("🐰 ClientA received ping: {:?}", msg.0);
    }
}

#[derive(Debug, Default)]
pub struct ClientB;

impl Actor for ClientB {
    type Context = Context<Self>;

    fn started(&mut self, ctx: &mut Self::Context) {
        println!("🐇 starting ClientB");
        TimeService::from_registry()
            .send(RegisterForTime(ctx.address().downgrade().recipient()))
            .into_actor(self)
            .then(|_, _slf, _| fut::ready(()))
            .spawn(ctx);
    }

    fn stopping(&mut self, _ctx: &mut Self::Context) -> Running {
        println!("🐇  stopping ClientB");
        Running::Stop
    }

    fn stopped(&mut self, _ctx: &mut Self::Context) {
        println!("🐇 stopped ClientB");
    }
}

impl Handler<TimePing> for ClientB {
    type Result = ();

    fn handle(&mut self, msg: TimePing, _ctx: &mut Self::Context) -> Self::Result {
        println!("🐇  ClientB received ping: {:?}", msg);
    }
}

#[actix::main]
async fn main() {
    {
        println!("🎩 creating client client A");
        let _client_a = ClientA.start();
        {
            println!("🎩 creating client client B");
            let _client_b = ClientB.start();

            println!("🎩 press Ctrl-C to stop client B");
            tokio::signal::ctrl_c().await.unwrap();
            println!("🎩 Ctrl-C received, stopping client");
        }

        println!("🎩 press Ctrl-C to stop client A");
        tokio::signal::ctrl_c().await.unwrap();
        println!("🎩 Ctrl-C received, stopping client");
    }

    tokio::signal::ctrl_c().await.unwrap();
    println!("🎩 Ctrl-C received, shutting down");
    System::current().stop();
}