forked from lavina/lavina
73 lines
2.7 KiB
Rust
73 lines
2.7 KiB
Rust
use http_body_util::{BodyExt, Full};
|
|
use hyper::body::Bytes;
|
|
use hyper::{Method, Request, Response};
|
|
|
|
use super::Or5xx;
|
|
use crate::http::{empty_204_request, malformed_request, player_not_found, room_not_found};
|
|
use lavina_core::clustering::room::{paths, JoinRoomReq, SendMessageReq};
|
|
use lavina_core::player::PlayerId;
|
|
use lavina_core::room::RoomId;
|
|
use lavina_core::LavinaCore;
|
|
|
|
// TODO move this into core
|
|
|
|
pub async fn route(core: &LavinaCore, request: Request<hyper::body::Incoming>) -> Option<Response<Full<Bytes>>> {
|
|
match (request.method(), request.uri().path()) {
|
|
(&Method::POST, paths::JOIN) => Some(endpoint_cluster_join_room(request, core).await.or5xx()),
|
|
(&Method::POST, paths::ADD_MESSAGE) => Some(endpoint_cluster_add_message(request, core).await.or5xx()),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
#[tracing::instrument(skip_all, name = "endpoint_cluster_join_room")]
|
|
async fn endpoint_cluster_join_room(
|
|
request: Request<hyper::body::Incoming>,
|
|
core: &LavinaCore,
|
|
) -> lavina_core::prelude::Result<Response<Full<Bytes>>> {
|
|
let str = request.collect().await?.to_bytes();
|
|
let Ok(req) = serde_json::from_slice::<JoinRoomReq>(&str[..]) else {
|
|
return Ok(malformed_request());
|
|
};
|
|
tracing::info!("Incoming request: {:?}", &req);
|
|
let Ok(room_id) = RoomId::try_from(req.room_id) else {
|
|
dbg!(&req.room_id);
|
|
return Ok(room_not_found());
|
|
};
|
|
let Ok(player_id) = PlayerId::from(req.player_id) else {
|
|
dbg!(&req.player_id);
|
|
return Ok(player_not_found());
|
|
};
|
|
core.cluster_join_room(room_id, &player_id).await?;
|
|
Ok(empty_204_request())
|
|
}
|
|
|
|
#[tracing::instrument(skip_all, name = "endpoint_cluster_add_message")]
|
|
async fn endpoint_cluster_add_message(
|
|
request: Request<hyper::body::Incoming>,
|
|
core: &LavinaCore,
|
|
) -> lavina_core::prelude::Result<Response<Full<Bytes>>> {
|
|
let str = request.collect().await?.to_bytes();
|
|
let Ok(req) = serde_json::from_slice::<SendMessageReq>(&str[..]) else {
|
|
return Ok(malformed_request());
|
|
};
|
|
tracing::info!("Incoming request: {:?}", &req);
|
|
let Ok(created_at) = chrono::DateTime::parse_from_rfc3339(req.created_at) else {
|
|
dbg!(&req.created_at);
|
|
return Ok(malformed_request());
|
|
};
|
|
let Ok(room_id) = RoomId::try_from(req.room_id) else {
|
|
dbg!(&req.room_id);
|
|
return Ok(room_not_found());
|
|
};
|
|
let Ok(player_id) = PlayerId::from(req.player_id) else {
|
|
dbg!(&req.player_id);
|
|
return Ok(player_not_found());
|
|
};
|
|
let res = core.cluster_send_room_message(room_id, &player_id, req.message.into(), created_at.to_utc()).await?;
|
|
if let Some(_) = res {
|
|
Ok(empty_204_request())
|
|
} else {
|
|
Ok(room_not_found())
|
|
}
|
|
}
|