1
0
mirror of https://github.com/actix/examples synced 2024-11-27 16:02:57 +01:00
examples/websockets/chat-actorless/src/server.rs

302 lines
8.7 KiB
Rust
Raw Normal View History

2022-07-11 21:19:29 +02:00
//! A multi-room chat server.
use std::{
collections::{HashMap, HashSet},
2022-07-12 02:42:58 +02:00
io,
2022-07-11 21:19:29 +02:00
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
};
use rand::{thread_rng, Rng as _};
use tokio::sync::{mpsc, oneshot};
2022-07-11 21:19:29 +02:00
use crate::{ConnId, Msg, RoomId};
/// A command received by the [`ChatServer`].
#[derive(Debug)]
enum Command {
Connect {
conn_tx: mpsc::UnboundedSender<Msg>,
res_tx: oneshot::Sender<ConnId>,
},
Disconnect {
conn: ConnId,
},
List {
res_tx: oneshot::Sender<Vec<RoomId>>,
},
Join {
conn: ConnId,
room: RoomId,
res_tx: oneshot::Sender<()>,
},
Message {
msg: Msg,
conn: ConnId,
res_tx: oneshot::Sender<()>,
},
}
2022-07-11 21:19:29 +02:00
/// A multi-room chat server.
///
/// Contains the logic of how connections chat with each other plus room management.
///
/// Call and spawn [`run`](Self::run) to start processing commands.
2022-07-11 21:19:29 +02:00
#[derive(Debug)]
pub struct ChatServer {
/// Map of connection IDs to their message receivers.
sessions: HashMap<ConnId, mpsc::UnboundedSender<Msg>>,
/// Map of room name to participant IDs in that room.
rooms: HashMap<RoomId, HashSet<ConnId>>,
/// Tracks total number of historical connections established.
visitor_count: Arc<AtomicUsize>,
/// Command receiver.
cmd_rx: mpsc::UnboundedReceiver<Command>,
2022-07-11 21:19:29 +02:00
}
impl ChatServer {
pub fn new() -> (Self, ChatServerHandle) {
2022-07-11 21:19:29 +02:00
// create empty server
let mut rooms = HashMap::with_capacity(4);
// create default room
rooms.insert("main".to_owned(), HashSet::new());
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
2022-07-11 21:19:29 +02:00
(
Self {
sessions: HashMap::new(),
rooms,
visitor_count: Arc::new(AtomicUsize::new(0)),
cmd_rx,
2022-07-11 21:19:29 +02:00
},
ChatServerHandle { cmd_tx },
2022-07-11 21:19:29 +02:00
)
}
/// Send message to users in a room.
2022-07-11 21:19:29 +02:00
///
/// `skip` is used to prevent messages triggered by a connection also being received by it.
async fn send_system_message(&self, room: &str, skip: ConnId, msg: impl Into<String>) {
2022-07-11 21:19:29 +02:00
if let Some(sessions) = self.rooms.get(room) {
let msg = msg.into();
for conn_id in sessions {
if *conn_id != skip {
2022-07-11 21:19:29 +02:00
if let Some(tx) = self.sessions.get(conn_id) {
2022-07-12 02:42:58 +02:00
// errors if client disconnected abruptly and hasn't been timed-out yet
let _ = tx.send(msg.clone());
2022-07-11 21:19:29 +02:00
}
}
}
}
}
/// Send message to all other users in current room.
2022-07-11 21:19:29 +02:00
///
/// `conn` is used to find current room and prevent messages sent by a connection also being
/// received by it.
async fn send_message(&self, conn: ConnId, msg: impl Into<String>) {
if let Some(room) = self
.rooms
.iter()
.find_map(|(room, participants)| participants.contains(&conn).then_some(room))
{
2022-07-21 04:30:58 +02:00
self.send_system_message(room, conn, msg).await;
};
}
/// Register new session and assign unique ID to this session
2022-07-11 21:19:29 +02:00
async fn connect(&mut self, tx: mpsc::UnboundedSender<Msg>) -> ConnId {
log::info!("Someone joined");
// notify all users in same room
self.send_system_message("main", 0, "Someone joined").await;
2022-07-11 21:19:29 +02:00
// register session with random connection ID
let id = thread_rng().gen::<usize>();
self.sessions.insert(id, tx);
// auto join session to main room
self.rooms
.entry("main".to_owned())
.or_insert_with(HashSet::new)
.insert(id);
let count = self.visitor_count.fetch_add(1, Ordering::SeqCst);
self.send_system_message("main", 0, format!("Total visitors {count}"))
2022-07-11 21:19:29 +02:00
.await;
// send id back
id
}
/// Unregister connection from room map and broadcast disconnection message.
2022-07-11 21:19:29 +02:00
async fn disconnect(&mut self, conn_id: ConnId) {
println!("Someone disconnected");
let mut rooms: Vec<String> = Vec::new();
// remove sender
if self.sessions.remove(&conn_id).is_some() {
// remove session from all rooms
for (name, sessions) in &mut self.rooms {
if sessions.remove(&conn_id) {
rooms.push(name.to_owned());
}
}
}
// send message to other users
for room in rooms {
self.send_system_message(&room, 0, "Someone disconnected")
.await;
2022-07-11 21:19:29 +02:00
}
}
/// Returns list of created room names.
2022-07-11 21:19:29 +02:00
fn list_rooms(&mut self) -> Vec<String> {
self.rooms.keys().cloned().collect()
2022-07-11 21:19:29 +02:00
}
/// Join room, send disconnect message to old room send join message to new room.
async fn join_room(&mut self, conn_id: ConnId, room: String) {
let mut rooms = Vec::new();
// remove session from all rooms
for (n, sessions) in &mut self.rooms {
if sessions.remove(&conn_id) {
rooms.push(n.to_owned());
}
}
// send message to other users
for room in rooms {
self.send_system_message(&room, 0, "Someone disconnected")
.await;
2022-07-11 21:19:29 +02:00
}
self.rooms
.entry(room.clone())
.or_insert_with(HashSet::new)
.insert(conn_id);
self.send_system_message(&room, conn_id, "Someone connected")
.await;
2022-07-11 21:19:29 +02:00
}
2022-07-12 02:42:58 +02:00
pub async fn run(mut self) -> io::Result<()> {
2022-07-21 04:30:58 +02:00
while let Some(cmd) = self.cmd_rx.recv().await {
2022-07-12 02:42:58 +02:00
match cmd {
2022-07-11 21:19:29 +02:00
Command::Connect { conn_tx, res_tx } => {
let conn_id = self.connect(conn_tx).await;
2022-07-12 02:42:58 +02:00
let _ = res_tx.send(conn_id);
2022-07-11 21:19:29 +02:00
}
Command::Disconnect { conn } => {
self.disconnect(conn).await;
}
Command::List { res_tx } => {
2022-07-12 02:42:58 +02:00
let _ = res_tx.send(self.list_rooms());
2022-07-11 21:19:29 +02:00
}
Command::Join { conn, room, res_tx } => {
self.join_room(conn, room).await;
2022-07-12 02:42:58 +02:00
let _ = res_tx.send(());
2022-07-11 21:19:29 +02:00
}
Command::Message { conn, msg, res_tx } => {
self.send_message(conn, msg).await;
2022-07-12 02:42:58 +02:00
let _ = res_tx.send(());
2022-07-11 21:19:29 +02:00
}
}
}
2022-07-12 02:42:58 +02:00
Ok(())
2022-07-11 21:19:29 +02:00
}
}
/// Handle and command sender for chat server.
///
/// Reduces boilerplate of setting up response channels in WebSocket handlers.
#[derive(Debug, Clone)]
pub struct ChatServerHandle {
cmd_tx: mpsc::UnboundedSender<Command>,
}
impl ChatServerHandle {
/// Register client message sender and obtain connection ID.
pub async fn connect(&self, conn_tx: mpsc::UnboundedSender<String>) -> ConnId {
let (res_tx, res_rx) = oneshot::channel();
// unwrap: chat server should not have been dropped
self.cmd_tx
.send(Command::Connect { conn_tx, res_tx })
.unwrap();
// unwrap: chat server does not drop out response channel
res_rx.await.unwrap()
}
/// List all created rooms.
pub async fn list_rooms(&self) -> Vec<String> {
let (res_tx, res_rx) = oneshot::channel();
// unwrap: chat server should not have been dropped
self.cmd_tx.send(Command::List { res_tx }).unwrap();
// unwrap: chat server does not drop our response channel
res_rx.await.unwrap()
}
/// Join `room`, creating it if it does not exist.
pub async fn join_room(&self, conn: ConnId, room: impl Into<String>) {
let (res_tx, res_rx) = oneshot::channel();
// unwrap: chat server should not have been dropped
self.cmd_tx
.send(Command::Join {
conn,
room: room.into(),
res_tx,
})
.unwrap();
// unwrap: chat server does not drop our response channel
res_rx.await.unwrap();
}
/// Broadcast message to current room.
pub async fn send_message(&self, conn: ConnId, msg: impl Into<String>) {
let (res_tx, res_rx) = oneshot::channel();
// unwrap: chat server should not have been dropped
self.cmd_tx
.send(Command::Message {
msg: msg.into(),
conn,
res_tx,
})
.unwrap();
// unwrap: chat server does not drop our response channel
res_rx.await.unwrap();
}
/// Unregister message sender and broadcast disconnection message to current room.
pub fn disconnect(&self, conn: ConnId) {
// unwrap: chat server should not have been dropped
self.cmd_tx.send(Command::Disconnect { conn }).unwrap();
}
}