Skip to content

Commit

Permalink
Fix redirect
Browse files Browse the repository at this point in the history
  • Loading branch information
DylanRJohnston committed Jul 31, 2024
1 parent bbc3861 commit 6c62c76
Show file tree
Hide file tree
Showing 15 changed files with 246 additions and 132 deletions.
2 changes: 1 addition & 1 deletion flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@
cp -r assets/* site/
ln -s ../simulation/assets site/assets
export RUST_LOG=info,axum::rejection=trace
export RUST_LOG=info
SERVER_TARGET="./target/wasm32-unknown-unknown/debug/server.wasm"
CLIENT_TARGET="./target/wasm32-unknown-unknown/debug/client.wasm"
Expand Down
276 changes: 171 additions & 105 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@
"author": "",
"license": "ISC",
"dependencies": {
"wrangler": "^3.29.0"
"wrangler": "^3.67.1"
}
}
16 changes: 9 additions & 7 deletions server/src/bin/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,20 @@ use leptos::{leptos_config, LeptosOptions};
use leptos_axum::{generate_route_list, LeptosRoutes};
use tower::Service;
use tracing::instrument;
use tracing_subscriber::util::SubscriberInitExt;
use worker::{console_log, event, Env};

#[derive(Debug, Clone, PartialEq, Default)]
pub struct ConsoleWriter(Vec<u8>);

impl io::Write for ConsoleWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
console_log!("{}", std::str::from_utf8(buf).unwrap());

Ok(buf.len())
}

fn flush(&mut self) -> io::Result<()> {
let data = std::str::from_utf8(&self.0)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "data not UTF-8"))?;

console_log!("{}", data);

Ok(())
}
}
Expand All @@ -46,7 +44,9 @@ pub fn start() {
.pretty()
.with_writer(ConsoleWriter::default)
.without_time()
.init()
.init();

tracing::info!("wasm module initialised");
}

#[event(fetch)]
Expand All @@ -56,6 +56,8 @@ pub async fn fetch(
env: Env,
_ctx: worker::Context,
) -> worker::Result<http::Response<axum::body::Body>> {
tracing::info!("received request");

let leptos_options = LeptosOptions::builder()
.output_name("index")
.site_pkg_dir("pkg")
Expand Down
4 changes: 2 additions & 2 deletions server/src/durable_objects/game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ impl DurableObject for Game {
}
}

#[instrument(name = "Game::fetch", skip(self))]
#[instrument(name = "Game::fetch", skip_all)]
pub async fn fetch(&mut self, req: worker::Request) -> worker::Result<worker::Response> {
tracing::info!("fetch");
tracing::info!("request made it to durable object");

axum::Router::new()
.route("/api/object/game/by_code/:code/connect", get(on_connect))
Expand Down
28 changes: 20 additions & 8 deletions server/src/handlers/create_game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,37 @@ use std::ops::Deref;
use crate::utils::err_wrapper::ErrWrapper;
use axum::{
extract::{Request, State},
http::header::HeaderMap,
http::{header::HeaderMap, Uri},
};
use shared::models::{
commands::{self, Command},
game_id::generate_game_code,
};
use worker::{Env, HttpResponse};

#[tracing::instrument(skip_all)]
#[tracing::instrument(skip_all, err)]
#[axum::debug_handler]
#[worker::send]
pub async fn create_game(
State(env): State<Env>,
headers: HeaderMap,
uri: Uri,
_req: Request,
) -> Result<HttpResponse, ErrWrapper> {
let game_code = generate_game_code();

let mut req = Request::post(format!(
let mut do_req = Request::post(format!(
"https://DURABLE_OBJECT{}",
commands::CreateGame::url(game_code)
));

*req.headers_mut().unwrap() = headers;
req.headers_mut()
*do_req.headers_mut().unwrap() = headers;
do_req
.headers_mut()
.unwrap()
.insert("Content-Type", "application/json".parse().unwrap());

let req = req.body(serde_json::to_string(&commands::create_game::Input {
let req = do_req.body(serde_json::to_string(&commands::create_game::Input {
code: game_code,
})?)?;

Expand All @@ -42,12 +44,22 @@ pub async fn create_game(
.fetch_with_request(req.try_into()?)
.await?;

tracing::info!(status_code = ?response.status_code(), "response from durable object");

if response.status_code() != 200 {
return Ok(response.try_into()?);
}

let url = commands::CreateGame::redirect(game_code).unwrap();
let response = web_sys::Response::redirect_with_status(&url, 303)?;
let url = format!(
"https://{host}{path}",
host = uri.authority().unwrap(),
path = commands::CreateGame::redirect(game_code).unwrap()
);

let response = web_sys::Response::redirect_with_status(&url, 303).map_err(|err| {
tracing::error!(?err, ?url, "failed to construct redirect response");
err
})?;

Ok(worker::response_from_wasm(response)?)
}
17 changes: 13 additions & 4 deletions server/src/handlers/join_game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,19 @@ use std::ops::Deref;
use crate::utils::err_wrapper::ErrWrapper;
use axum::{
extract::{Request, State},
http::header::HeaderMap,
http::{header::HeaderMap, Uri},
Form,
};
use shared::models::commands::{self, Command, JoinGame};
use worker::{Env, HttpResponse};

#[tracing::instrument(skip_all)]
#[tracing::instrument(skip_all, err)]
#[axum::debug_handler]
#[worker::send]
pub async fn join_game(
State(env): State<Env>,
headers: HeaderMap,
uri: Uri,
Form(join_game): Form<<JoinGame as Command>::Input>,
) -> Result<HttpResponse, ErrWrapper> {
let mut req = Request::post(format!(
Expand All @@ -40,8 +41,16 @@ pub async fn join_game(
return Ok(response.try_into()?);
}

let url = commands::JoinGame::redirect(join_game.code).unwrap();
let response = web_sys::Response::redirect_with_status(&url, 303)?;
let url = format!(
"https://{host}{path}",
host = uri.authority().unwrap(),
path = commands::JoinGame::redirect(join_game.code).unwrap()
);

let response = web_sys::Response::redirect_with_status(&url, 303).map_err(|err| {
tracing::error!(?err, url, "failed to redirect to construct redirect");
err
})?;

Ok(worker::response_from_wasm(response)?)
}
9 changes: 8 additions & 1 deletion server/src/handlers/register_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,23 @@ pub trait CommandHandler {
}

#[worker::send]
#[tracing::instrument(skip_all, fields(session_id, input), err)]
#[tracing::instrument(skip_all, fields(session_id, input, command = type_name::<C>()), err)]
pub async fn command_handler<C: Command>(
SessionID(session_id): SessionID,
State(mut game): State<GameWrapper>,
Json(input): Json<C::Input>,
) -> Result<(), ErrWrapper> {
tracing::info!("handling command");

let (new_events, effect) = C::handle(session_id, game.events().vector().await?, input)?;
tracing::info!("processed command");

for event in new_events {
game.add_event(event).await?;
}

tracing::info!("events added");

match effect {
Some(Effect::Alarm(time)) => {
match game.state().storage().get_alarm().await? {
Expand All @@ -43,6 +48,8 @@ pub async fn command_handler<C: Command>(
None => {}
}

tracing::info!("effects processed");

Ok(())
}

Expand Down
2 changes: 2 additions & 0 deletions shared/src/models/commands/create_game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::fmt::Display;

use im::Vector;
use serde::{Deserialize, Serialize};
use tracing::instrument;
use uuid::Uuid;

use crate::models::{events::Event, game_id::GameID};
Expand Down Expand Up @@ -33,6 +34,7 @@ impl Command for CreateGame {
Some(format!("/host/{}", game_id))
}

#[instrument(name = "CreateGame::handle", err)]
fn handle(
session_id: Uuid,
events: &Vector<Event>,
Expand Down
Binary file modified simulation/assets/Scene.glb
Binary file not shown.
Binary file modified simulation/game.blend
Binary file not shown.
Binary file removed simulation/game.glb
Binary file not shown.
8 changes: 8 additions & 0 deletions simulation/src/plugins/scenes/lobby.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ pub struct LobbyPlugin;
impl Plugin for LobbyPlugin {
fn build(&self, app: &mut App) {
app.add_systems(OnEnter(SceneState::Lobby), init_camera)
.add_systems(
OnEnter(SceneState::Lobby),
|mut query: Query<&mut Visibility, With<SpotLight>>| {
for mut visibility in query.iter_mut() {
*visibility = Visibility::Hidden;
}
},
)
.add_systems(Update, spawn_racers)
.add_systems(Update, orbit_camera.run_if(in_state(SceneState::Lobby)));
}
Expand Down
2 changes: 1 addition & 1 deletion simulation/src/plugins/scenes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ fn setup_skybox(
EnvironmentMapLight {
diffuse_map: game_assets.envmap_diffuse.clone(),
specular_map: game_assets.envmap_specular.clone(),
intensity: 1500.0,
intensity: 1000.0,
},
bloom,
Tonemapping::AcesFitted,
Expand Down
12 changes: 10 additions & 2 deletions simulation/src/plugins/scenes/pregame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,15 @@ impl Plugin for PreGamePlugin {
app.register_type::<PreGameSpawnPoint>()
.register_type::<PreGameCamera>()
.add_systems(OnEnter(SceneState::PreGame), init_pregame)
.add_systems(Update, spawn_pregame_spawn_point_on_scene_load);
.add_systems(Update, spawn_pregame_spawn_point_on_scene_load)
.add_systems(
OnEnter(SceneState::PreGame),
|mut query: Query<&mut Visibility, With<SpotLight>>| {
for mut visibility in query.iter_mut() {
*visibility = Visibility::Inherited;
}
},
);
}
}

Expand Down Expand Up @@ -55,6 +63,6 @@ fn init_pregame(
let mut camera = camera.get_single_mut().unwrap();

camera.translation = position.translation;
camera.rotation = Quat::from_rotation_z(std::f32::consts::FRAC_PI_2) * position.rotation;
// Don't know why the rotation coming from blender is fucked up
camera.rotation = Quat::from_euler(EulerRot::XYZ, PI / 2.0, PI / 2.0 + 0.18, -PI / 2.0);
}

0 comments on commit 6c62c76

Please sign in to comment.