forked from lavina/lavina
1
0
Fork 0
lavina/src/core/player.rs

291 lines
9.3 KiB
Rust

//! Domain of chat participants.
//!
//! Player is a single user account, which is used to participate in chats,
//! including sending messages, receiving messaged, retrieving history and running privileged actions.
//! A player corresponds to a single user account. Usually a person has only one account,
//! but it is possible to have multiple accounts for one person and therefore multiple player entities.
//!
//! A player actor is a serial handler of commands from a single player. It is preferable to run all per-player validations in the player actor,
//! so that they don't overload the room actor.
use std::{
collections::HashMap,
sync::{Arc, RwLock},
};
use prometheus::{IntGauge, Registry as MetricsRegistry};
use tokio::{
sync::mpsc::{channel, Receiver, Sender},
sync::oneshot::{channel as oneshot, Sender as OneshotSender},
task::JoinHandle,
};
use crate::{
core::room::{RoomId, RoomInfo, RoomRegistry},
prelude::*,
util::table::{AnonTable, Key as AnonKey},
};
/// Opaque player identifier. Cannot contain spaces, must be shorter than 32.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PlayerId(ByteVec);
impl PlayerId {
pub fn from_bytes(bytes: ByteVec) -> Result<PlayerId> {
if bytes.len() > 32 {
return Err(fail("Nickname cannot be longer than 32 symbols"));
}
if bytes.contains(&b' ') {
return Err(anyhow::Error::msg("Nickname cannot contain spaces"));
}
Ok(PlayerId(bytes))
}
pub fn as_bytes(&self) -> &ByteVec {
&self.0
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ConnectionId(pub AnonKey);
pub struct PlayerConnection {
pub connection_id: ConnectionId,
pub receiver: Receiver<Updates>,
player_handle: PlayerHandle,
}
impl PlayerConnection {
pub async fn send_message(&mut self, room_id: RoomId, body: String) {
self.player_handle
.send_message(room_id, self.connection_id.clone(), body)
.await
}
pub async fn join_room(&mut self, room_id: RoomId) -> Result<RoomInfo> {
self.player_handle
.join_room(room_id, self.connection_id.clone())
.await
}
pub async fn send(&self, command: PlayerCommand) {
self.player_handle.send(command).await;
}
}
/// Handle to a player actor.
#[derive(Clone)]
pub struct PlayerHandle {
tx: Sender<PlayerCommand>,
}
impl PlayerHandle {
pub async fn subscribe(&self) -> PlayerConnection {
let (sender, receiver) = channel(32);
let (promise, deferred) = oneshot();
self.tx
.send(PlayerCommand::AddConnection { sender, promise })
.await;
let connection_id = deferred.await.unwrap();
PlayerConnection {
connection_id,
player_handle: self.clone(),
receiver,
}
}
pub async fn send_message(&self, room_id: RoomId, connection_id: ConnectionId, body: String) {
self.tx
.send(PlayerCommand::SendMessage {
room_id,
connection_id,
body,
})
.await;
}
pub async fn join_room(
&self,
room_id: RoomId,
connection_id: ConnectionId,
) -> Result<RoomInfo> {
let (promise, deferred) = oneshot();
self.tx
.send(PlayerCommand::JoinRoom {
room_id,
connection_id,
promise,
})
.await;
Ok(deferred.await?)
}
pub async fn send(&self, command: PlayerCommand) {
self.tx.send(command).await;
}
pub async fn update(&self, update: Updates) {
self.send(PlayerCommand::Update(update)).await;
}
}
pub enum PlayerCommand {
/** Commands from connections */
AddConnection {
sender: Sender<Updates>,
promise: OneshotSender<ConnectionId>,
},
JoinRoom {
room_id: RoomId,
connection_id: ConnectionId,
promise: Promise<RoomInfo>,
},
SendMessage {
room_id: RoomId,
connection_id: ConnectionId,
body: String,
},
GetRooms(Promise<Vec<RoomInfo>>),
/** Events from rooms */
Update(Updates),
}
/// Player update event type which is sent to a player actor and from there to a connection handler.
#[derive(Clone)]
pub enum Updates {
RoomTopicChanged {
room_id: RoomId,
new_topic: ByteVec,
},
NewMessage {
room_id: RoomId,
connection_id: ConnectionId,
author_id: PlayerId,
body: String,
},
RoomJoined {
room_id: RoomId,
new_member_id: PlayerId,
connection_id: ConnectionId,
},
}
/// Handle to a player registry — a shared data structure containing information about players.
#[derive(Clone)]
pub struct PlayerRegistry(Arc<RwLock<PlayerRegistryInner>>);
impl PlayerRegistry {
pub fn empty(
room_registry: RoomRegistry,
metrics: &mut MetricsRegistry,
) -> Result<PlayerRegistry> {
let metric_active_players =
IntGauge::new("chat_players_active", "Number of alive player actors")?;
metrics.register(Box::new(metric_active_players.clone()))?;
let inner = PlayerRegistryInner {
room_registry,
players: HashMap::new(),
metric_active_players,
};
Ok(PlayerRegistry(Arc::new(RwLock::new(inner))))
}
pub async fn get_or_create_player(&mut self, id: PlayerId) -> PlayerHandle {
let player = Player {
connections: AnonTable::new(),
};
let mut inner = self.0.write().unwrap();
if let Some((handle, _)) = inner.players.get(&id) {
handle.clone()
} else {
let (handle, fiber) = player.launch(id.clone(), inner.room_registry.clone());
inner.players.insert(id, (handle.clone(), fiber));
inner.metric_active_players.inc();
handle
}
}
pub async fn connect_to_player(&mut self, id: PlayerId) -> PlayerConnection {
let mut player_handle = self.get_or_create_player(id).await;
player_handle.subscribe().await
}
}
/// The player registry state representation.
struct PlayerRegistryInner {
room_registry: RoomRegistry,
players: HashMap<PlayerId, (PlayerHandle, JoinHandle<Player>)>,
metric_active_players: IntGauge,
}
/// Player actor inner state representation.
struct Player {
connections: AnonTable<Sender<Updates>>,
}
impl Player {
fn launch(
mut self,
player_id: PlayerId,
mut rooms: RoomRegistry,
) -> (PlayerHandle, JoinHandle<Player>) {
let (tx, mut rx) = channel(32);
let handle = PlayerHandle { tx };
let handle_clone = handle.clone();
let mut my_rooms = HashMap::new();
let fiber = tokio::task::spawn(async move {
while let Some(cmd) = rx.recv().await {
match cmd {
PlayerCommand::AddConnection { sender, promise } => {
let connection_id = self.connections.insert(sender);
promise.send(ConnectionId(connection_id));
}
PlayerCommand::JoinRoom {
room_id,
connection_id,
promise,
} => {
let mut room = rooms.get_or_create_room(room_id.clone());
room.subscribe(player_id.clone(), connection_id, handle.clone())
.await;
my_rooms.insert(room_id.clone(), room.clone());
let members = room.get_members().await;
promise.send(RoomInfo {
id: room_id,
members,
topic: b"some topic lol".to_vec(),
});
}
PlayerCommand::SendMessage {
room_id,
connection_id,
body,
} => {
let room = rooms.get_room(&room_id);
match room {
Some(mut room) => {
room.send_message(player_id.clone(), connection_id, body)
.await;
}
None => {
tracing::info!("no room found");
}
}
}
PlayerCommand::GetRooms(promise) => {
let mut response = vec![];
for (_, handle) in &my_rooms {
response.push(handle.get_room_info().await);
}
promise.send(response);
}
PlayerCommand::Update(update) => {
log::info!(
"Player received an update, broadcasting to {} connections",
self.connections.len()
);
for connection in &self.connections {
connection.send(update.clone()).await;
}
}
}
}
self
});
(handle_clone, fiber)
}
}