use crate::client::{Client, ClientEvent, ClientId};
use crate::messages::Message;
use sansio::Protocol;
use std::collections::HashMap;
use std::convert::Infallible;
use std::time::{Duration, Instant};
const MAX_ROOM_CAPACITY: usize = 2;
const LOOPBACK_CLIENT_ID: &str = "LOOPBACK_CLIENT_ID";
pub type RoomId = String;
pub struct Room {
id: RoomId,
clients: HashMap<ClientId, Client>,
register_timeout: Duration,
}
impl Room {
pub fn new(id: RoomId, register_timeout: Duration) -> Self {
Self {
id,
clients: HashMap::new(),
register_timeout,
}
}
pub fn id(&self) -> &RoomId {
&self.id
}
fn client(&mut self, now: Instant, client_id: &ClientId) -> Result<&mut Client, String> {
if !self.clients.contains_key(client_id) {
if self.clients.len() >= MAX_ROOM_CAPACITY {
return Err("Max room capacity reached".to_string());
}
let timeout = Some(now + self.register_timeout);
self.clients.insert(
client_id.clone(),
Client::new(client_id.clone(), self.id.clone(), timeout),
);
}
Ok(self
.clients
.get_mut(client_id)
.expect("client just inserted or already present"))
}
pub fn register(&mut self, now: Instant, client_id: &ClientId) -> Result<(), String> {
self.client(now, client_id)?.register()?;
if self.clients.len() > 1
&& let Some(other_id) = self
.clients
.keys()
.find(|k| k.as_str() != client_id.as_str())
.cloned()
&& let [Some(other), Some(c)] = self.clients.get_disjoint_mut([&other_id, client_id])
{
let _ = other.send_queued(c);
}
Ok(())
}
pub fn send(&mut self, now: Instant, src_id: &ClientId, msg: String) -> Result<(), String> {
self.client(now, src_id)?;
if self.clients.len() == 1 {
return self.clients.get_mut(src_id).unwrap().enqueue(msg);
}
if let Some(other_id) = self
.clients
.keys()
.find(|k| k.as_str() != src_id.as_str())
.cloned()
&& let [Some(src), Some(oc)] = self.clients.get_disjoint_mut([src_id, &other_id])
{
return src.send(oc, msg);
}
Err(format!("Corrupted room {}", self.id))
}
pub fn remove(&mut self, client_id: &ClientId) {
if let Some(mut client) = self.clients.remove(client_id) {
client.deregister();
for other in self.clients.values_mut() {
other.set_initiator(true);
}
}
}
pub fn deregister(&mut self, now: Instant, client_id: &ClientId) -> bool {
if let Some(client) = self.clients.get_mut(client_id)
&& client.registered()
{
client.deregister();
client.set_timer(Some(now + self.register_timeout));
return true;
}
false
}
pub fn remove_if_unregistered(&mut self, client_id: &ClientId) -> bool {
if self
.clients
.get(client_id)
.is_some_and(|client| !client.registered())
{
self.remove(client_id);
return true;
}
false
}
pub fn client_is_initiator(&self, client_id: &ClientId) -> bool {
self.clients
.get(client_id)
.is_some_and(Client::is_initiator)
}
pub fn add_client(
&mut self,
now: Instant,
client_id: &ClientId,
is_loopback: bool,
) -> Result<(bool, Vec<String>), String> {
if self.clients.contains_key(client_id) {
return Err("DUPLICATE_CLIENT".to_string());
}
if self.clients.len() >= MAX_ROOM_CAPACITY {
return Err("FULL".to_string());
}
let is_initiator = self.clients.is_empty();
let mut messages = Vec::new();
if !is_initiator {
for other in self.clients.values_mut() {
messages.extend(other.drain_msgs());
}
}
self.client(now, client_id)?.set_initiator(is_initiator);
if is_loopback {
if let Ok(lc) = self.client(now, &LOOPBACK_CLIENT_ID.to_string()) {
lc.set_initiator(false);
}
}
Ok((is_initiator, messages))
}
pub fn occupancy(&self) -> usize {
self.clients.len()
}
pub fn empty(&self) -> bool {
self.clients.is_empty()
}
pub fn ws_count(&self) -> usize {
self.clients.values().filter(|c| c.registered()).count()
}
}
impl Protocol<Message, Message, Infallible> for Room {
type Rout = Message;
type Wout = Message;
type Eout = Infallible;
type Error = String;
type Time = Instant;
fn handle_read(&mut self, msg: Message) -> Result<(), Self::Error> {
if let Some(c) = self.clients.get_mut(&msg.clientid) {
c.handle_read(msg)?;
}
Ok(())
}
fn poll_read(&mut self) -> Option<Self::Rout> {
for client in self.clients.values_mut() {
if let Some(msg) = client.poll_read() {
return Some(msg);
}
}
None
}
fn handle_write(&mut self, msg: Message) -> Result<(), Self::Error> {
if let Some(c) = self.clients.get_mut(&msg.clientid) {
c.handle_write(msg)?;
}
Ok(())
}
fn poll_write(&mut self) -> Option<Self::Wout> {
for client in self.clients.values_mut() {
if let Some(msg) = client.poll_write() {
return Some(msg);
}
}
None
}
fn handle_timeout(&mut self, now: Self::Time) -> Result<(), Self::Error> {
let mut expired: Vec<ClientId> = Vec::new();
for (id, c) in self.clients.iter_mut() {
c.handle_timeout(now)?;
while let Some(evt) = c.poll_event() {
match evt {
ClientEvent::Expired => expired.push(id.clone()),
}
}
}
for id in &expired {
self.remove(id);
}
Ok(())
}
fn poll_timeout(&mut self) -> Option<Self::Time> {
let mut eto: Option<Instant> = None;
for c in self.clients.values_mut() {
if let Some(next) = c.poll_timeout() {
eto = Some(eto.map_or(next, |cur| cur.min(next)));
}
}
eto
}
fn close(&mut self) -> Result<(), Self::Error> {
for c in self.clients.values_mut() {
c.close()?;
}
self.clients.clear();
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use sansio::Protocol;
fn new_room(id: &str) -> Room {
Room::new(id.to_string(), Duration::from_secs(1))
}
fn assert_message(actual: Option<Message>, room_id: &str, client_id: &str, msg: &str) {
let actual = actual.expect("expected a message");
assert_eq!(actual.roomid, room_id);
assert_eq!(actual.clientid, client_id);
assert_eq!(actual.msg, msg);
}
#[test]
fn new_room_is_empty() {
let r = new_room("abc");
assert_eq!(r.id(), "abc");
assert_eq!(r.occupancy(), 0);
}
#[test]
fn get_or_create_client() {
let now = Instant::now();
let mut r = new_room("ab");
let (id1, id2, id3) = ("1".to_string(), "2".to_string(), "3".to_string());
r.client(now, &id1)
.expect("first client")
.set_initiator(true);
assert!(r.client(now, &id1).expect("same client").is_initiator());
assert_eq!(
r.occupancy(),
1,
"client() must not recreate an existing client"
);
r.client(now, &id2).expect("second client");
assert_eq!(r.occupancy(), 2);
assert!(r.client(now, &id3).is_err());
}
#[test]
fn register_delivers_queued_message() {
let now = Instant::now();
let mut r = new_room("a");
let (id1, id2) = ("1".to_string(), "2".to_string());
r.client(now, &id1)
.unwrap()
.enqueue("hello".to_string())
.unwrap();
r.register(now, &id2).unwrap();
assert_eq!(r.occupancy(), 2);
assert!(r.client(now, &id2).unwrap().registered());
assert_message(r.poll_write(), "a", "2", "hello");
}
#[test]
fn send_queues_when_alone() {
let now = Instant::now();
let mut r = new_room("a");
let id = "1".to_string();
r.send(now, &id, "hi".to_string()).unwrap();
assert!(r.poll_write().is_none());
assert_eq!(
r.client(now, &id).unwrap().drain_msgs(),
vec!["hi".to_string()]
);
}
#[test]
fn send_delivers_when_paired() {
let now = Instant::now();
let mut r = new_room("a");
let (id1, id2) = ("1".to_string(), "2".to_string());
r.register(now, &id2).unwrap();
r.send(now, &id1, "hi".to_string()).unwrap();
assert!(r.client(now, &id1).unwrap().drain_msgs().is_empty());
assert_message(r.poll_write(), "a", "2", "hi");
}
#[test]
fn remove_deletes_client() {
let now = Instant::now();
let mut r = new_room("a");
let id = "1".to_string();
r.register(now, &id).unwrap();
r.remove(&id);
assert!(r.empty());
}
}