Just make the entire core asynchronous

This commit is contained in:
Savanni D'Gerinel 2024-11-30 15:24:57 -05:00
parent 970e957143
commit 995390ae4b
4 changed files with 80 additions and 34 deletions

View File

@ -1,14 +1,14 @@
use std::{
collections::HashMap,
sync::{Arc, RwLock},
};
use std::{collections::HashMap, sync::Arc};
use async_std::sync::RwLock;
use mime::Mime;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use uuid::Uuid;
use crate::{
asset_db::{self, AssetId, Assets}, database::Database, types::{AppError, Message, Tabletop, RGB}
asset_db::{self, AssetId, Assets},
database::{CharacterId, Database},
types::{AppError, Message, Tabletop, RGB},
};
const DEFAULT_BACKGROUND_COLOR: RGB = RGB {
@ -50,8 +50,8 @@ impl Core {
})))
}
pub fn register_client(&self) -> String {
let mut state = self.0.write().unwrap();
pub async fn register_client(&self) -> String {
let mut state = self.0.write().await;
let uuid = Uuid::new_v4().simple().to_string();
let client = WebsocketClient { sender: None };
@ -60,13 +60,13 @@ impl Core {
uuid
}
pub fn unregister_client(&self, client_id: String) {
let mut state = self.0.write().unwrap();
pub async fn unregister_client(&self, client_id: String) {
let mut state = self.0.write().await;
let _ = state.clients.remove(&client_id);
}
pub fn connect_client(&self, client_id: String) -> UnboundedReceiver<Message> {
let mut state = self.0.write().unwrap();
pub async fn connect_client(&self, client_id: String) -> UnboundedReceiver<Message> {
let mut state = self.0.write().await;
match state.clients.get_mut(&client_id) {
Some(client) => {
@ -80,14 +80,14 @@ impl Core {
}
}
pub fn tabletop(&self) -> Tabletop {
self.0.read().unwrap().tabletop.clone()
pub async fn tabletop(&self) -> Tabletop {
self.0.read().await.tabletop.clone()
}
pub async fn get_asset(&self, asset_id: AssetId) -> Result<(Mime, Vec<u8>), AppError> {
self.0
.read()
.unwrap()
.await
.asset_store
.get(asset_id.clone())
.map_err(|err| match err {
@ -97,24 +97,24 @@ impl Core {
})
}
pub fn available_images(&self) -> Vec<AssetId> {
pub async fn available_images(&self) -> Vec<AssetId> {
self.0
.read()
.unwrap()
.await
.asset_store
.assets()
.filter_map(|(asset_id, value)| {
match mime_guess::from_path(&value).first() {
.filter_map(
|(asset_id, value)| match mime_guess::from_path(&value).first() {
Some(mime) if mime.type_() == mime::IMAGE => Some(asset_id.clone()),
_ => None,
}
})
},
)
.collect()
}
pub fn set_background_image(&self, asset: AssetId) -> Result<(), AppError> {
pub async fn set_background_image(&self, asset: AssetId) -> Result<(), AppError> {
let tabletop = {
let mut state = self.0.write().unwrap();
let mut state = self.0.write().await;
state.tabletop.background_image = Some(asset.clone());
state.tabletop.clone()
};
@ -122,8 +122,23 @@ impl Core {
Ok(())
}
pub fn publish(&self, message: Message) {
let state = self.0.read().unwrap();
pub async fn get_charsheet(
&self,
id: CharacterId,
) -> Result<Option<serde_json::Value>, AppError> {
Ok(self
.0
.write()
.await
.db
.charsheet(id)
.await
.unwrap()
.map(|cr| cr.data))
}
pub async fn publish(&self, message: Message) {
let state = self.0.read().await;
state.clients.values().for_each(|client| {
if let Some(ref sender) = client.sender {
@ -141,7 +156,10 @@ mod test {
use cool_asserts::assert_matches;
use crate::{asset_db::mocks::MemoryAssets, database::{DbConn, DiskDb}};
use crate::{
asset_db::mocks::MemoryAssets,
database::{DbConn, DiskDb},
};
fn test_core() -> Core {
let assets = MemoryAssets::new(vec![

View File

@ -77,7 +77,7 @@ impl From<String> for CharacterId {
pub struct CharsheetRow {
id: String,
gametype: String,
data: serde_json::Value,
pub data: serde_json::Value,
}
#[async_trait]
@ -172,7 +172,7 @@ impl DiskDb {
}
}
async fn db_handler(db: DiskDb, mut requestor: Receiver<DatabaseRequest>) {
async fn db_handler(db: DiskDb, requestor: Receiver<DatabaseRequest>) {
println!("Starting db_handler");
while let Ok(DatabaseRequest { tx, req }) = requestor.recv().await {
println!("Request received: {:?}", req);

View File

@ -4,7 +4,7 @@ use futures::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use warp::{http::Response, http::StatusCode, reply::Reply, ws::Message};
use crate::{asset_db::AssetId, core::Core, types::AppError};
use crate::{asset_db::AssetId, core::Core, database::CharacterId, types::AppError};
/*
pub async fn handle_auth(
@ -62,6 +62,7 @@ pub async fn handle_available_images(core: Core) -> impl Reply {
handler(async move {
let image_paths: Vec<String> = core
.available_images()
.await
.into_iter()
.map(|path| format!("{}", path.as_str()))
.collect();
@ -85,7 +86,7 @@ pub struct RegisterResponse {
pub async fn handle_register_client(core: Core, _request: RegisterRequest) -> impl Reply {
handler(async move {
let client_id = core.register_client();
let client_id = core.register_client().await;
Ok(Response::builder()
.header("Access-Control-Allow-Origin", "*")
@ -105,7 +106,10 @@ pub async fn handle_unregister_client(core: Core, client_id: String) -> impl Rep
handler(async move {
core.unregister_client(client_id);
Ok(Response::builder().status(StatusCode::NO_CONTENT).body(vec![]).unwrap())
Ok(Response::builder()
.status(StatusCode::NO_CONTENT)
.body(vec![])
.unwrap())
})
.await
}
@ -120,10 +124,10 @@ pub async fn handle_connect_websocket(
let core = core.clone();
async move {
let (mut ws_sender, _) = socket.split();
let mut receiver = core.connect_client(client_id.clone());
let mut receiver = core.connect_client(client_id.clone()).await;
tokio::task::spawn(async move {
let tabletop = core.tabletop();
let tabletop = core.tabletop().await;
let _ = ws_sender
.send(Message::text(
serde_json::to_string(&crate::types::Message::UpdateTabletop(tabletop))
@ -155,3 +159,20 @@ pub async fn handle_set_background_image(core: Core, image_name: String) -> impl
})
.await
}
pub async fn handle_get_charsheet(core: Core, charid: String) -> impl Reply {
handler(async move {
let sheet = core.get_charsheet(CharacterId::from(charid)).await.unwrap();
match sheet {
Some(sheet) => Ok(Response::builder()
.body(serde_json::to_vec(&sheet).unwrap())
.unwrap()),
None => Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(vec![])
.unwrap()),
}
})
.await
}

View File

@ -8,8 +8,7 @@ use asset_db::{AssetId, FsAssets};
use authdb::AuthError;
use database::DbConn;
use handlers::{
handle_available_images, handle_connect_websocket, handle_file, handle_register_client,
handle_set_background_image, handle_unregister_client, RegisterRequest,
handle_available_images, handle_connect_websocket, handle_file, handle_get_charsheet, handle_register_client, handle_set_background_image, handle_unregister_client, RegisterRequest
};
use warp::{
// header,
@ -161,6 +160,13 @@ pub async fn main() {
})
.with(log);
let route_get_charsheet = warp::path!("api" / "v1" / "charsheet" / String)
.and(warp::get())
.then({
let core = core.clone();
move |charid| handle_get_charsheet(core.clone(), charid)
});
let filter = route_register_client
.or(route_unregister_client)
.or(route_websocket)
@ -168,6 +174,7 @@ pub async fn main() {
.or(route_available_images)
.or(route_set_bg_image_options)
.or(route_set_bg_image)
.or(route_get_charsheet)
.recover(handle_rejection);
let server = warp::serve(filter);