-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbudget_chat.rs
More file actions
422 lines (348 loc) · 11.4 KB
/
Copy pathbudget_chat.rs
File metadata and controls
422 lines (348 loc) · 11.4 KB
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
use std::{collections::HashMap, net::SocketAddr, sync::Arc};
use futures::{Sink, SinkExt, Stream, StreamExt, TryStreamExt};
use protohackers_rs::run_server_with_state;
use tokio::{
net::TcpStream,
sync::{mpsc, Mutex},
};
use tokio_util::codec::{Decoder, Encoder, Framed, LinesCodec};
use tracing::error;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt::init();
run_server_with_state(8000, Room::new(), handle_client).await?;
Ok(())
}
async fn handle_client(state: Room, stream: TcpStream, address: SocketAddr) -> anyhow::Result<()> {
let (input_stream, output_stream) = Framed::new(stream, ChatCodec::new()).split();
handle_client_internal(state, address, input_stream, output_stream).await
}
async fn handle_client_internal<I, O>(
state: Room,
address: SocketAddr,
mut sink: O,
mut stream: I,
) -> anyhow::Result<()>
where
I: Stream<Item = anyhow::Result<String>> + Unpin,
O: Sink<OutgoingMessage, Error = anyhow::Error> + Unpin,
{
sink.send(OutgoingMessage::Welcome).await?;
let username = stream
.try_next()
.await?
.ok_or_else(|| anyhow::anyhow!("Error while waiting for the username"))?;
let username = match Username::parse(username) {
Ok(username) => username,
Err(e) => {
sink.send(OutgoingMessage::InvalidUsername(e.to_string()))
.await?;
return Ok(());
}
};
let mut handle = state.join(address, username).await;
loop {
tokio::select! {
Some(msg) = handle.receiver.recv() => {
if let Err(e) = sink.send(msg).await {
error!("Error sending message {}",e);
break;
}
}
result = stream.next() => match result {
Some(Ok(msg)) => {
handle.send_message(msg).await;
}
Some(Err(e)) => {
error!("Error reading messages {}",e);
break;
}
None => break,
}
};
}
handle.leave().await;
Ok(())
}
pub struct ChatCodec {
lines: LinesCodec,
}
impl ChatCodec {
pub fn new() -> Self {
Self {
lines: LinesCodec::new(),
}
}
}
impl Encoder<OutgoingMessage> for ChatCodec {
type Error = anyhow::Error;
fn encode(
&mut self,
item: OutgoingMessage,
dst: &mut bytes::BytesMut,
) -> Result<(), Self::Error> {
self.lines
.encode(item.to_string(), dst)
.map_err(anyhow::Error::from)
}
}
impl Decoder for ChatCodec {
type Item = String;
type Error = anyhow::Error;
fn decode(&mut self, src: &mut bytes::BytesMut) -> Result<Option<Self::Item>, Self::Error> {
self.lines.decode(src).map_err(anyhow::Error::from)
}
}
#[derive(Clone, derive_more::Display, PartialEq, Debug)]
pub struct Username(String);
impl Username {
pub fn parse(input: String) -> anyhow::Result<Username> {
if input.is_empty() {
anyhow::bail!("Name should be at least 1 character")
}
if input.chars().any(|c| !c.is_alphanumeric()) {
anyhow::bail!("Name should contains only alphanumeric characters")
}
Ok(Username(input))
}
pub fn inner_ref(&self) -> &String {
&self.0
}
}
#[derive(derive_more::Display, Clone, PartialEq, Debug)]
pub enum OutgoingMessage {
#[display(fmt = "Welcome to budgetchat! What shall I call you?")]
Welcome,
#[display(fmt = "* {} has entered the room", _0)]
Join(Username),
#[display(fmt = "* {} has left the room", _0)]
Leave(Username),
#[display(fmt = "[{}] {}", from, msg)]
Chat { from: Username, msg: String },
#[display(fmt = "Invalid username {}", _0)]
InvalidUsername(String),
#[display(fmt = "* The room contains: {}", "self.participants(_0)")]
Participants(Vec<Username>),
}
impl OutgoingMessage {
fn participants(&self, participants: &[Username]) -> String {
participants
.iter()
.map(|user| user.to_string())
.collect::<Vec<String>>()
.join(", ")
}
}
pub struct User {
username: Username,
sender: mpsc::UnboundedSender<OutgoingMessage>,
}
pub struct UserHandle {
username: Username,
address: SocketAddr,
receiver: mpsc::UnboundedReceiver<OutgoingMessage>,
room: Room,
}
impl UserHandle {
pub async fn send_message(&self, msg: String) {
self.room
.broadcast(
&self.address,
OutgoingMessage::Chat {
from: self.username.clone(),
msg,
},
)
.await;
}
pub async fn leave(self) {
self.room.leave(&self.address).await
}
}
#[derive(Clone)]
pub struct Room(Arc<Mutex<HashMap<SocketAddr, User>>>);
impl Room {
pub fn new() -> Room {
Room(Arc::new(Mutex::new(HashMap::new())))
}
pub async fn join(&self, addr: SocketAddr, username: Username) -> UserHandle {
let (sender, receiver) = mpsc::unbounded_channel();
let mut users = self.0.lock().await;
let names = users
.iter()
.map(|(_, user)| user.username.clone())
.collect::<Vec<Username>>();
let _ = sender.send(OutgoingMessage::Participants(names));
self.broadcast_internal(&addr, OutgoingMessage::Join(username.clone()), &mut users)
.await;
users.insert(
addr,
User {
username: username.clone(),
sender,
},
);
UserHandle {
username,
receiver,
room: self.clone(),
address: addr,
}
}
async fn leave(&self, addr: &SocketAddr) {
let mut users = self.0.lock().await;
if let Some(leaving) = users.remove(addr) {
self.broadcast_internal(addr, OutgoingMessage::Leave(leaving.username), &mut users)
.await;
}
}
async fn broadcast_internal(
&self,
addr: &SocketAddr,
msg: OutgoingMessage,
users: &mut HashMap<SocketAddr, User>,
) {
for (user_addr, user) in users.iter_mut() {
if addr != user_addr {
let _ = user.sender.send(msg.clone());
}
}
}
async fn broadcast(&self, addr: &SocketAddr, msg: OutgoingMessage) {
let mut users = self.0.lock().await;
self.broadcast_internal(addr, msg, &mut users).await;
}
}
#[cfg(test)]
mod budget_chat_tests {
use std::net::SocketAddr;
use futures::SinkExt;
use tokio::{
sync::mpsc::{self, Receiver, Sender},
task::JoinHandle,
};
use tokio_util::sync::PollSender;
use crate::{handle_client_internal, OutgoingMessage, Room, UserHandle, Username};
async fn check_message(handle: &mut UserHandle, msg: OutgoingMessage) {
assert_eq!(handle.receiver.recv().await.unwrap(), msg);
}
#[tokio::test]
async fn room_test() {
let room = Room::new();
let alice_username = Username::parse("alice".to_string()).unwrap();
let bob_username = Username::parse("bob".to_string()).unwrap();
let mut alice = room
.join("0.0.0.0:100".parse().unwrap(), alice_username.clone())
.await;
// alice should receive an empty participants list on join
check_message(&mut alice, OutgoingMessage::Participants(vec![])).await;
let mut bob = room
.join("0.0.0.0:200".parse().unwrap(), bob_username.clone())
.await;
// bob should receive participants list on join with only alice
check_message(
&mut bob,
OutgoingMessage::Participants(vec![alice_username.clone()]),
)
.await;
// alice should receive bob join notification
check_message(&mut alice, OutgoingMessage::Join(bob_username.clone())).await;
alice.send_message("Hi Bob".to_string()).await;
// bob should receive alice message
check_message(
&mut bob,
OutgoingMessage::Chat {
msg: "Hi Bob".to_string(),
from: alice_username.clone(),
},
)
.await;
alice.leave().await;
// bob should receive alice left notification
check_message(&mut bob, OutgoingMessage::Leave(alice_username.clone())).await;
}
struct UserTest {
sink_receiver: Receiver<OutgoingMessage>,
stream_sender: Option<Sender<anyhow::Result<String>>>,
handle: JoinHandle<anyhow::Result<()>>,
}
impl UserTest {
async fn send(&mut self, message: &str) {
self.stream_sender
.as_ref()
.unwrap()
.send(Ok(message.to_string()))
.await
.unwrap();
}
async fn leave(mut self) {
let stream = self.stream_sender.take();
drop(stream);
self.handle.await.unwrap().unwrap()
}
async fn check_message(&mut self, msg: OutgoingMessage) {
assert_eq!(self.sink_receiver.recv().await.unwrap(), msg);
}
}
async fn connect(room: Room, addr: &str) -> UserTest {
let (sink_tx, sink_rx) = mpsc::channel(100);
let (stream_tx, mut stream_rx) = mpsc::channel(100);
let address: SocketAddr = addr.parse().unwrap();
let stream = async_stream::stream! {
while let Some(message) = stream_rx.recv().await {
yield message
}
};
let handle = tokio::spawn(async move {
handle_client_internal(
room,
address,
PollSender::new(sink_tx).sink_map_err(anyhow::Error::from),
Box::pin(stream),
)
.await
});
UserTest {
sink_receiver: sink_rx,
stream_sender: Some(stream_tx),
handle,
}
}
#[tokio::test]
async fn example_session_test() {
let room = Room::new();
let alice_username = Username::parse("alice".to_string()).unwrap();
let bob_username = Username::parse("bob".to_string()).unwrap();
let mut alice = connect(room.clone(), "0.0.0.0:10").await;
alice.check_message(OutgoingMessage::Welcome).await;
alice.send(&alice_username.inner_ref()).await;
alice
.check_message(OutgoingMessage::Participants(vec![]))
.await;
let mut bob = connect(room.clone(), "0.0.0.0:11").await;
bob.check_message(OutgoingMessage::Welcome).await;
bob.send(&bob_username.inner_ref()).await;
bob.check_message(OutgoingMessage::Participants(vec![alice_username.clone()]))
.await;
alice
.check_message(OutgoingMessage::Join(bob_username.clone()))
.await;
alice.send("Hi bob!").await;
bob.check_message(OutgoingMessage::Chat {
msg: "Hi bob!".to_string(),
from: alice_username.clone(),
})
.await;
bob.send("Hi alice!").await;
alice
.check_message(OutgoingMessage::Chat {
msg: "Hi alice!".to_string(),
from: bob_username.clone(),
})
.await;
bob.leave().await;
alice
.check_message(OutgoingMessage::Leave(bob_username))
.await;
}
}