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
use crate::{
messages::{AssignClientId, MessageFromClient, MessageFromServer},
ServiceShutdownPolicy,
};
use actix::{
dev::MessageResponse, Actor, ActorContext, AsyncContext, Context, Handler, Message, Recipient,
SpawnHandle,
};
use jamsocket::{ClientId, MessageRecipient};
use std::{collections::HashMap, time::Duration};
pub struct RoomActor {
room_id: String,
service_actor: Option<Recipient<MessageFromClient>>,
connections: HashMap<ClientId, Recipient<MessageFromServer>>,
next_id: u32,
shutdown_policy: ServiceShutdownPolicy,
shutdown_handle: Option<SpawnHandle>,
}
struct Shutdown;
impl Message for Shutdown {
type Result = ();
}
impl RoomActor {
pub fn new(
room_id: String,
service_actor: Recipient<MessageFromClient>,
shutdown_policy: ServiceShutdownPolicy,
) -> Self {
RoomActor {
room_id,
service_actor: Some(service_actor),
connections: Default::default(),
next_id: 1,
shutdown_policy,
shutdown_handle: None,
}
}
fn handle_empty_room(&mut self, ctx: &mut Context<Self>) {
match self.shutdown_policy {
ServiceShutdownPolicy::Immediate => {
log::info!(
"Shutting down service actor for {} because no clients are left.",
&self.room_id
);
ctx.stop();
}
ServiceShutdownPolicy::Never => (),
ServiceShutdownPolicy::AfterSeconds(secs) => {
self.shutdown_handle =
Some(ctx.notify_later(Shutdown, Duration::from_secs(secs.into())));
}
}
}
}
impl Actor for RoomActor {
type Context = Context<Self>;
}
impl Handler<MessageFromServer> for RoomActor {
type Result = ();
fn handle(&mut self, message: MessageFromServer, _ctx: &mut Context<Self>) {
match message.to_client {
MessageRecipient::Broadcast => {
for addr in self.connections.values() {
addr.do_send(message.clone()).unwrap();
}
}
MessageRecipient::Client(u) => {
if let Some(client_connection) = self.connections.get(&u) {
client_connection.do_send(message).unwrap();
} else {
log::warn!(
"Could not get address of user {:?}; they may have disconnected.",
u
);
}
}
}
}
}
impl Handler<MessageFromClient> for RoomActor {
type Result = ();
fn handle(&mut self, message: MessageFromClient, ctx: &mut Context<Self>) {
if let Some(service_actor) = &self.service_actor {
match &message {
MessageFromClient::Connect(client, resp) => {
self.connections.insert(*client, resp.clone());
service_actor.do_send(message).unwrap();
self.shutdown_handle.take().map(|t| ctx.cancel_future(t));
}
MessageFromClient::Disconnect(client_id) => {
self.connections.remove(client_id);
if self.connections.is_empty() {
if self.shutdown_policy != ServiceShutdownPolicy::Immediate {
service_actor.do_send(message).unwrap();
}
self.handle_empty_room(ctx);
} else {
service_actor.do_send(message).unwrap();
}
}
MessageFromClient::Message { .. } => {
service_actor.do_send(message).unwrap();
}
}
} else {
log::warn!(
"MessageFromClient received on room with no service attached ({}).",
self.room_id
);
}
}
}
impl MessageResponse<RoomActor, AssignClientId> for ClientId {
fn handle(self, _: &mut Context<RoomActor>, tx: Option<actix::dev::OneshotSender<ClientId>>) {
if let Some(tx) = tx {
if let Err(e) = tx.send(self) {
log::warn!("Error returning response to AssignClientId: {:?}", e);
}
}
}
}
impl Handler<AssignClientId> for RoomActor {
type Result = ClientId;
fn handle(&mut self, _: AssignClientId, _ctx: &mut Context<Self>) -> ClientId {
let result = self.next_id;
self.next_id += 1;
result.into()
}
}
impl Handler<Shutdown> for RoomActor {
type Result = ();
fn handle(&mut self, _: Shutdown, ctx: &mut Self::Context) -> Self::Result {
log::info!(
"Shutting down service actor for {} because no clients are left and the timeout period has elapsed.",
&self.room_id
);
ctx.stop();
}
}