-
Notifications
You must be signed in to change notification settings - Fork 2
/
room.rs
350 lines (313 loc) · 12.5 KB
/
room.rs
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
use std::collections::{HashMap, HashSet};
use tokio::sync::broadcast;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use crate::{
messages::StateChange,
messages::{ClientMessages, RoomStateChange, ServerMessages},
types::{Story, StoryPoints, Winner},
};
pub const CHANNEL_SIZE: usize = 100;
/// The state that a Room can be in
#[derive(Debug)]
enum RoomState {
/// Waiting for a vote
Idle,
/// Actually voting
Voting(CurrentVote),
}
#[derive(Debug)]
pub struct SubscriptionRequest {
pub winner: Winner,
pub response: oneshot::Sender<SubscriptionResponse>,
}
#[derive(Debug)]
pub struct SubscriptionData {
pub message_receive: broadcast::Receiver<ServerMessages>,
pub winners: Vec<Winner>,
pub leader: Option<Winner>,
}
#[derive(Debug)]
pub enum SubscriptionResponse {
Ok(SubscriptionData),
WinnerExists,
}
#[derive(Debug, Clone)]
struct CurrentVote {
pub story: Story,
pub votes: HashMap<Winner, StoryPoints>,
}
impl CurrentVote {
pub fn new(story: &Story) -> Self {
Self {
story: story.clone(),
votes: HashMap::new(),
}
}
}
/// Struct containing a client message and a channel to send a result
#[derive(Debug)]
pub struct ClientMessageRequest {
pub message: ClientMessages,
pub response_channel: oneshot::Sender<anyhow::Result<()>>,
}
/// Implementation of a room
pub struct Room {
current_state: RoomState,
/// Current participants in the room
participants: HashSet<Winner>,
/// Incoming message that need to be processed
incoming: mpsc::Receiver<ClientMessageRequest>,
/// Outgoing message that will be processed by the clients
outgoing: broadcast::Sender<ServerMessages>,
/// Receives subscription request
subscription_receiver: mpsc::Receiver<SubscriptionRequest>,
/// Current leader of the room
leader: Option<Winner>,
}
impl Room {
/// Create a new room
pub fn new(
subscription_receiver: mpsc::Receiver<SubscriptionRequest>,
incoming: mpsc::Receiver<ClientMessageRequest>,
outgoing: broadcast::Sender<ServerMessages>,
) -> Self {
Room {
participants: HashSet::new(),
current_state: RoomState::Idle,
incoming,
outgoing,
subscription_receiver,
leader: None,
}
}
/// Sets the leader, and notify over channel
fn set_leader(&mut self, winner: &Winner) {
// Set new leader, send outgoing messages
self.leader = Some(winner.clone());
// Send a message that the leader has changed
self.send_server_message(ServerMessages::RoomParticipantsChange((
winner.clone(),
StateChange::Leader,
)));
}
/// Subscribe to this room
fn subscribe(&mut self, subscription_request: &SubscriptionRequest) -> SubscriptionResponse {
if !self.participants.contains(&subscription_request.winner) {
// Insert participant if it does not exist
self.participants
.insert(subscription_request.winner.clone());
// Get all participants
let winners = self
.participants
.iter()
.map(|winner| winner.clone())
.collect::<Vec<Winner>>();
// Set a new leader if it does not exist
if self.leader.is_none() {
self.set_leader(&subscription_request.winner);
}
// Send the subscription response
let response = SubscriptionResponse::Ok(SubscriptionData {
message_receive: self.outgoing.subscribe(),
winners,
leader: self.leader.clone(),
});
// Broadcast that someone has entered, do this after creating the response or the
// subscriber misses the message
self.send_server_message(ServerMessages::RoomParticipantsChange((
subscription_request.winner.clone(),
StateChange::Enter,
)));
response
} else {
SubscriptionResponse::WinnerExists
}
}
/// Unsubscribe from the room
fn unsubscribe(&mut self, winner: &Winner) {
self.participants.remove(winner);
// Notify the rest that someone has left
self.send_server_message(ServerMessages::RoomParticipantsChange((
winner.clone(),
StateChange::Leave,
)));
// Set a new leader if it is available
if self.participants.len() > 0 {
// Get the first next leader
let new_leader = self.participants.iter().next().unwrap().clone();
// Set it as the new leader
self.set_leader(&new_leader)
}
}
/// Receive message from the incoming channel
async fn receive_incoming_messages(&mut self) -> ClientMessageRequest {
self.incoming
.recv()
.await
.expect("Could not receive incoming messages")
}
/// Send a server messages
fn send_server_message(&mut self, message: ServerMessages) {
// Ignore if we are unable to send, it's okay if no one is listening
let _ = self.outgoing.send(message);
}
/// Set a new room state
fn set_room_state(&mut self, room_state: RoomState) {
// Update the current state
self.current_state = room_state;
let change = match self.current_state {
RoomState::Idle => ServerMessages::RoomStateChange(RoomStateChange::Idle),
RoomState::Voting(_) => ServerMessages::RoomStateChange(RoomStateChange::Voting),
};
// Send a change message
self.send_server_message(change);
}
}
impl Room {
/// Main loop of the room that is running
pub async fn run(&mut self) {
loop {
match &self.current_state {
// Waiting for connections and for votes, or leadership changes
RoomState::Idle => self.idle().await,
// In voting state
RoomState::Voting(current_vote) => {
let current_vote = current_vote.clone();
self.voting(current_vote).await;
}
}
}
}
/// The loop to run when running in idle mode
async fn idle(&mut self) {
while let RoomState::Idle = self.current_state {
tokio::select! {
// Subscriber future
Some(req) = self.subscription_receiver.recv() => {
println!("Received subscription");
let response = self.subscribe(&req);
req.response
.send(response)
.expect("Could not send subscription response");
println!("Subscription sent");
},
// Incoming messages future
Some(msg) = self.incoming.recv() => {
println!("Processing server messages");
let response_channel = msg.response_channel;
match msg.message {
ClientMessages::LeaveRoom(winner) => self.unsubscribe(&winner),
// A new vote is requested
ClientMessages::StartVote(story) => {
response_channel.send(Ok(())).expect("Could not send 'StartVote' result");
// TODO do a leader check here
self.send_server_message(ServerMessages::RoomStateChange(RoomStateChange::Voting));
self.current_state = RoomState::Voting(CurrentVote::new(&story));
}
// Ignore these messages for now
_ => {},
}
}
}
}
}
/// Handles the voting loop
async fn voting(&mut self, mut vote: CurrentVote) {
println!("Starting vote on story {}", vote.story.title);
// Notify clients that a vote has started
self.send_server_message(ServerMessages::StartVote(vote.story.clone()));
println!("Waiting for votes");
// Wait for votes to come in
while self.participants.len() > vote.votes.len() {
let ClientMessageRequest {
message,
response_channel,
} = self.receive_incoming_messages().await;
match message {
// Process actual vote
ClientMessages::Vote((winner, story, story_points)) => {
println!("Vote received for {} by {:?}", story.title, winner);
if story == vote.story {
vote.votes.insert(winner.clone(), story_points.clone());
println!(
"Received {}/{} votes",
vote.votes.len(),
self.participants.len()
);
}
// Communicate that a vote has been cast
response_channel
.send(Ok(()))
.expect("Could not send response");
self.send_server_message(ServerMessages::VoteCast((winner, story_points)));
}
ClientMessages::LeaveRoom(winner) =>
// Leaving room, so unsubscribe, we do not need to include participant for the count
{
self.unsubscribe(&winner)
}
// Other messages cannot be processed in this state
_ => response_channel
.send(Err(anyhow::anyhow!(
"Cant process this message when in 'Voting' state"
)))
.expect("Could not sends response"),
}
}
println!("Votes received");
// Broadcast results, let everyone know
self.send_server_message(ServerMessages::VotesReceived(vote.votes.clone()));
// Start a fight between participants if the votes are unequal
// This check checks if the min and the max of the vector are the same
// if they are they only contain the same votes
// skip this if there is only a single participant as well
if vote.votes.len() > 1
&& vote.votes.iter().map(|a| a.1).max() != vote.votes.iter().map(|a| a.1).min()
{
// Choose highest and lowest winners to do a fight
let highest_entry = vote.votes.iter().max_by(|x, y| x.1.cmp(y.1));
let lowest_entry = vote.votes.iter().min_by(|x, y| x.1.cmp(y.1));
if highest_entry.is_some() && lowest_entry.is_some() {
let highest_winner = highest_entry.unwrap().0;
let lowest_winner = lowest_entry.unwrap().0;
// Send out a fight message
self.send_server_message(ServerMessages::Fight((
highest_entry.unwrap().0.clone(),
lowest_entry.unwrap().0.clone(),
)));
// Wait for the fight to be resolved
let mut fight_resolved = false;
while !fight_resolved
&& self.participants.contains(highest_winner)
&& self.participants.contains(lowest_winner)
{
let ClientMessageRequest {
message,
response_channel,
} = self.receive_incoming_messages().await;
match message {
ClientMessages::FightResolved => {
fight_resolved = true;
response_channel
.send(Ok(()))
.expect("Could not send response");
self.send_server_message(ServerMessages::FightResolved);
}
ClientMessages::LeaveRoom(winner) => {
// Leaving room, so unsubscribe, we do not need to include participant for the count
self.unsubscribe(&winner)
}
_ => response_channel
.send(Err(anyhow::anyhow!(
"Can't process this message when in 'Fighting' state"
)))
.expect("Could not sends response"),
}
}
}
}
// Back to Idle state
self.set_room_state(RoomState::Idle);
}
}