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

258 lines
8.0 KiB
Rust
Raw Normal View History

2023-02-04 01:01:49 +00:00
//! 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.
2023-02-03 22:43:59 +00:00
use std::{
collections::HashMap,
sync::{Arc, RwLock},
};
2023-02-12 22:23:52 +00:00
use prometheus::{IntGauge, Registry as MetricsRegistry};
2023-02-03 22:43:59 +00:00
use tokio::{
sync::mpsc::{channel, Receiver, Sender},
2023-02-13 18:32:52 +00:00
sync::oneshot::{channel as oneshot, Sender as OneshotSender},
2023-02-03 22:43:59 +00:00
task::JoinHandle,
};
use crate::{
2023-02-04 01:01:49 +00:00
core::room::{RoomId, RoomRegistry},
2023-02-12 22:23:52 +00:00
prelude::*,
2023-02-13 18:32:52 +00:00
util::table::{AnonTable, Key as AnonKey},
2023-02-03 22:43:59 +00:00
};
2023-02-04 01:01:49 +00:00
/// Opaque player identifier.
2023-02-12 23:31:16 +00:00
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PlayerId(pub ByteVec);
2023-02-03 22:43:59 +00:00
2023-02-13 18:32:52 +00:00
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ConnectionId(pub AnonKey);
2023-02-13 19:16:00 +00:00
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) {
self.player_handle.join_room(room_id).await
}
}
2023-02-04 01:01:49 +00:00
/// Handle to a player actor.
2023-02-03 22:43:59 +00:00
#[derive(Clone)]
pub struct PlayerHandle {
tx: Sender<PlayerCommand>,
}
impl PlayerHandle {
2023-02-13 19:16:00 +00:00
pub async fn subscribe(&mut self) -> PlayerConnection {
let (sender, receiver) = channel(32);
2023-02-13 18:32:52 +00:00
let (promise, deferred) = oneshot();
self.tx
.send(PlayerCommand::AddSocket { sender, promise })
.await;
let connection_id = deferred.await.unwrap();
2023-02-13 19:16:00 +00:00
PlayerConnection {
connection_id,
player_handle: self.clone(),
receiver,
}
2023-02-03 22:43:59 +00:00
}
2023-02-13 18:32:52 +00:00
pub async fn send_message(
&mut self,
room_id: RoomId,
connection_id: ConnectionId,
body: String,
) {
2023-02-03 22:43:59 +00:00
self.tx
2023-02-13 18:32:52 +00:00
.send(PlayerCommand::SendMessage {
room_id,
connection_id,
body,
})
2023-02-03 22:43:59 +00:00
.await;
}
pub async fn join_room(&mut self, room_id: RoomId) {
self.tx.send(PlayerCommand::JoinRoom { room_id }).await;
}
2023-02-13 18:32:52 +00:00
pub async fn receive_message(
&mut self,
room_id: RoomId,
author: PlayerId,
connection_id: ConnectionId,
body: String,
) {
2023-02-03 22:43:59 +00:00
self.tx
.send(PlayerCommand::IncomingMessage {
room_id,
author,
2023-02-13 18:32:52 +00:00
connection_id,
2023-02-03 22:43:59 +00:00
body,
})
.await;
}
}
2023-02-04 01:01:49 +00:00
/// Player update event type which is sent to a connection handler.
2023-02-03 22:43:59 +00:00
pub enum Updates {
2023-02-13 18:32:52 +00:00
RoomJoined {
room_id: RoomId,
},
NewMessage {
author_id: PlayerId,
connection_id: ConnectionId,
room_id: RoomId,
body: String,
},
2023-02-03 22:43:59 +00:00
}
enum PlayerCommand {
AddSocket {
sender: Sender<Updates>,
2023-02-13 18:32:52 +00:00
promise: OneshotSender<ConnectionId>,
2023-02-03 22:43:59 +00:00
},
JoinRoom {
room_id: RoomId,
},
SendMessage {
room_id: RoomId,
2023-02-13 18:32:52 +00:00
connection_id: ConnectionId,
2023-02-03 22:43:59 +00:00
body: String,
},
IncomingMessage {
room_id: RoomId,
2023-02-13 18:32:52 +00:00
connection_id: ConnectionId,
2023-02-03 22:43:59 +00:00
author: PlayerId,
body: String,
},
}
2023-02-04 01:01:49 +00:00
/// Handle to a player registry — a shared data structure containing information about players.
2023-02-03 22:43:59 +00:00
#[derive(Clone)]
pub struct PlayerRegistry(Arc<RwLock<PlayerRegistryInner>>);
impl PlayerRegistry {
2023-02-12 22:23:52 +00:00
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()))?;
2023-02-03 22:43:59 +00:00
let inner = PlayerRegistryInner {
room_registry,
players: HashMap::new(),
2023-02-12 22:23:52 +00:00
metric_active_players,
2023-02-03 22:43:59 +00:00
};
2023-02-12 22:23:52 +00:00
Ok(PlayerRegistry(Arc::new(RwLock::new(inner))))
2023-02-03 22:43:59 +00:00
}
2023-02-12 23:31:16 +00:00
pub async fn get_or_create_player(&mut self, id: PlayerId) -> PlayerHandle {
2023-02-03 22:43:59 +00:00
let player = Player {
sockets: AnonTable::new(),
};
let mut inner = self.0.write().unwrap();
2023-02-13 18:32:52 +00:00
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
}
2023-02-03 22:43:59 +00:00
}
2023-02-13 19:16:00 +00:00
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
}
2023-02-03 22:43:59 +00:00
}
2023-02-04 01:01:49 +00:00
/// The player registry state representation.
2023-02-03 22:43:59 +00:00
struct PlayerRegistryInner {
room_registry: RoomRegistry,
players: HashMap<PlayerId, (PlayerHandle, JoinHandle<Player>)>,
2023-02-12 22:23:52 +00:00
metric_active_players: IntGauge,
2023-02-03 22:43:59 +00:00
}
2023-02-04 01:01:49 +00:00
/// Player actor inner state representation.
2023-02-03 22:43:59 +00:00
struct Player {
sockets: 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 fiber = tokio::task::spawn(async move {
while let Some(cmd) = rx.recv().await {
match cmd {
2023-02-13 18:32:52 +00:00
PlayerCommand::AddSocket { sender, promise } => {
let connection_id = self.sockets.insert(sender);
promise.send(ConnectionId(connection_id));
2023-02-03 22:43:59 +00:00
}
PlayerCommand::JoinRoom { room_id } => {
2023-02-12 23:31:16 +00:00
let mut room = rooms.get_or_create_room(room_id);
room.subscribe(player_id.clone(), handle.clone()).await;
2023-02-03 22:43:59 +00:00
}
2023-02-13 18:32:52 +00:00
PlayerCommand::SendMessage {
room_id,
connection_id,
body,
} => {
2023-02-03 22:43:59 +00:00
let room = rooms.get_room(room_id);
match room {
Some(mut room) => {
2023-02-13 18:32:52 +00:00
room.send_message(player_id.clone(), connection_id, body)
.await;
2023-02-03 22:43:59 +00:00
}
None => {
tracing::info!("no room found");
}
}
}
PlayerCommand::IncomingMessage {
room_id,
author,
2023-02-13 18:32:52 +00:00
connection_id,
2023-02-03 22:43:59 +00:00
body,
} => {
2023-02-13 20:58:44 +00:00
tracing::info!(
"Handling incoming message, player_id={:?}",
player_id.clone()
);
2023-02-03 22:43:59 +00:00
for socket in &self.sockets {
2023-02-13 18:32:52 +00:00
log::info!("Send message to socket");
2023-02-03 22:43:59 +00:00
socket
.send(Updates::NewMessage {
2023-02-13 18:32:52 +00:00
author_id: author.clone(),
connection_id: connection_id.clone(),
2023-02-12 23:31:16 +00:00
room_id: room_id.clone(),
2023-02-03 22:43:59 +00:00
body: body.clone(),
})
.await;
}
}
}
}
self
});
(handle_clone, fiber)
}
}