Skip to content

Commit

Permalink
Commit messages are hard
Browse files Browse the repository at this point in the history
  • Loading branch information
DylanRJohnston committed Aug 23, 2024
1 parent 0c8db8f commit b159771
Show file tree
Hide file tree
Showing 48 changed files with 3,025 additions and 904 deletions.
342 changes: 18 additions & 324 deletions Cargo.lock

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ macros = { path = "../macros" }
quickcheck = "1.0.3"
quickcheck_macros = "1.0.0"
rand = "0.8.5"
reqwest = { version = "0.11.27", features = ["blocking"] }
serde = "1.0.195"
serde_json = "1.0.111"
serde-wasm-bindgen = "0.6.3"
Expand All @@ -59,11 +58,12 @@ uuid = { version = "1.7.0", features = ["v4", "js", "serde"] }
wasm-bindgen = { version = "0.2", features = ["serde-serialize"] }
wasm-bindgen-futures = "0.4.39"
web-sys = { version = "0.3.67", features = ["HtmlDocument"] }
worker = { version = "0.3.1", features = ["http", "axum"] }
worker-macros = { version = "0.3.1", features = ["http"] }
worker = { version = "0.3.1", features = ["http", "axum"], optional = true }
worker-macros = { version = "0.3.1", features = ["http"], optional = true }

[features]
default = ["ssr", "native"]
wasm = ["dep:worker", "dep:worker-macros", "shared/wasm"]
native = [
"dep:tokio",
"dep:tower-http",
Expand Down
5 changes: 5 additions & 0 deletions app/src/bin/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,17 @@
#![feature(impl_trait_in_fn_trait_return)]
#![feature(more_qualified_paths)]

#[cfg(target_arch = "wasm32")]
use std::io;

#[cfg(target_arch = "wasm32")]
use worker::{console_log, event};

#[cfg(target_arch = "wasm32")]
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ConsoleWriter(Vec<u8>);

#[cfg(target_arch = "wasm32")]
impl io::Write for ConsoleWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
console_log!("{}", std::str::from_utf8(buf).unwrap());
Expand All @@ -23,6 +27,7 @@ impl io::Write for ConsoleWriter {
}
}

#[cfg(target_arch = "wasm32")]
#[event(start)]
pub fn start() {
console_error_panic_hook::set_once();
Expand Down
111 changes: 63 additions & 48 deletions app/src/handlers/on_connect.rs
Original file line number Diff line number Diff line change
@@ -1,57 +1,72 @@
use axum::{
extract::State,
response::{IntoResponse, Response},
};
use tracing::instrument;

use crate::{
extractors::GameCode,
ports::game_state::GameState,
service::InternalServerError,
};

#[cfg(target_arch = "wasm32")]
#[instrument(skip_all, err)]
pub async fn on_connect<G: GameState>(
State(game_state): State<G>,
SessionID(_session_id): SessionID,
GameCode { code }: GameCode,
) -> Result<Response, InternalServerError> {
let pair = game_state.accept_web_socket(code)?;

for event in game_state.events(code).await?.into_iter() {
pair.server.send(&event)?;
}
mod wasm {
use axum::{extract::State, response::Response};
use tracing::instrument;

use crate::{
extractors::{GameCode, SessionID},
ports::game_state::GameState,
service::InternalServerError,
};

// #[instrument(skip_all, err)]
pub async fn on_connect<G: GameState>(
State(game_state): State<G>,
SessionID(_session_id): SessionID,
GameCode { code }: GameCode,
) -> Result<Response, InternalServerError> {
let pair = game_state.accept_web_socket(code)?;

let response = Response::builder()
.status(101)
.extension(pair.client)
.body(axum::body::Body::empty());
for event in game_state.events(code).await?.into_iter() {
pair.server.send(&event)?;
}

Ok(response?)
let response = Response::builder()
.status(101)
.extension(pair.client)
.body(axum::body::Body::empty());

Ok(response?)
}
}

#[cfg(target_arch = "wasm32")]
pub use wasm::on_connect;

#[cfg(not(target_arch = "wasm32"))]
#[instrument(skip_all, err)]
pub async fn on_connect<G: GameState>(
ws: axum::extract::WebSocketUpgrade,
State(game_state): State<G>,
GameCode { code }: GameCode,
) -> Result<Response, InternalServerError> {
Ok(ws
.on_upgrade(move |mut ws| async move {
let result: anyhow::Result<()> = try {
for event in game_state.events(code).await?.into_iter() {
let message = serde_json::to_string(&event)?;
ws.send(message.into()).await?;
}
mod native {
use axum::{
extract::State,
response::{IntoResponse, Response},
};
use tracing::instrument;

use crate::{extractors::GameCode, ports::game_state::GameState, service::InternalServerError};

game_state.accept_web_socket(code, ws).await?;
};
#[instrument(skip_all, err)]
pub async fn on_connect<G: GameState>(
ws: axum::extract::WebSocketUpgrade,
State(game_state): State<G>,
GameCode { code }: GameCode,
) -> Result<Response, InternalServerError> {
Ok(ws
.on_upgrade(move |mut ws| async move {
let result: anyhow::Result<()> = try {
for event in game_state.events(code).await?.into_iter() {
let message = serde_json::to_string(&event)?;
ws.send(message.into()).await?;
}

if let Err(err) = result {
tracing::error!(?err, "error upgrading websocket")
}
})
.into_response())
game_state.accept_web_socket(code, ws).await?;
};

if let Err(err) = result {
tracing::error!(?err, "error upgrading websocket")
}
})
.into_response())
}
}

#[cfg(not(target_arch = "wasm32"))]
pub use native::on_connect;
5 changes: 1 addition & 4 deletions app/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,8 @@ pub fn into_outer_router<S: GameService>(game_service: S) -> axum::Router {
any(forward_command::<S>),
)
.with_state(game_service)
.layer(axum::middleware::from_fn(session_middleware))
.leptos_routes(&leptos_options, generate_route_list(app::App), app::App)
.layer(axum::middleware::from_fn(|req: Request, next: Next| {
next.run(req)
}));
.layer(axum::middleware::from_fn(session_middleware));

#[cfg(not(target_arch = "wasm32"))]
let router = router.fallback(crate::serve_files::file_and_error_handler);
Expand Down
14 changes: 9 additions & 5 deletions app/src/screens/host/results.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
use leptos::*;
use shared::models::projections;
use uuid::Uuid;

use crate::utils::use_events;

struct LeaderboardInfo {
name: String,
uuid: Uuid,
balance: i32,
winnings: i32,
}
Expand All @@ -21,11 +19,13 @@ pub fn results() -> impl IntoView {
let players = move || projections::players(&events());
let balances = move || projections::all_account_balances(&events());
let winnings = move || projections::winnings(&events());
let debt = move || projections::all_debt(&events());

let leaderboard = move || {
let players = players();
let winnings = winnings();
let balances = balances();
let debt = debt();

tracing::info!(?winnings);

Expand All @@ -34,8 +34,8 @@ pub fn results() -> impl IntoView {
.filter_map(|(key, value)| {
Some(LeaderboardInfo {
name: value.name,
uuid: value.session_id,
balance: balances.get(&key).copied().unwrap_or_default(),
balance: balances.get(&key).copied().unwrap_or_default()
- debt.get(&key).copied().unwrap_or_default() as i32,
winnings: winnings.get(&key).copied().unwrap_or_default(),
})
})
Expand All @@ -46,14 +46,18 @@ pub fn results() -> impl IntoView {
info
};

let game_is_finished = move || projections::game_finished(&events());

view! {
<div class="host-results-container">
<div
class="results-container"
class:invisible=timer.is_pending
class:two-columns=move || (leaderboard().len() > 7)
>
<h1>"Player Leaderboard"</h1>
<h1>
{move || if game_is_finished() { "Final Score" } else { "Player Leaderboard" }}
</h1>

{move || {
leaderboard()
Expand Down
10 changes: 9 additions & 1 deletion app/src/screens/player/join.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,15 @@ pub fn join() -> impl IntoView {
title="6 alpha-numerical characters e.g. ABC123"
uppercase=true
/>
<input type="text" name="name" prop:value="Bob" hidden/>
<TextInput
id="name"
name="Name"
pattern="[a-zA-Z]{1,10}"
minlength=1
maxlength=10
title="player name between 1-10 characters long"
value=None
/>
<input class="button" type="submit" value="Join"/>
</Form>
</div>
Expand Down
15 changes: 12 additions & 3 deletions app/src/screens/player/summary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ pub fn summary() -> impl IntoView {
.unwrap_or_default()
};

let winnings = move || {
let debt = Memo::new(move |_| projections::debt(&events(), player_id));

let winnings = Memo::new(move |_| {
projections::winnings(&events())
.get(&player_id)
.copied()
.unwrap_or_default()
};
});

let symbol = move || if winnings() >= 0 { "+" } else { "-" };
let image = move || if winnings() >= 0 { "📈" } else { "📉" };
Expand All @@ -31,7 +33,14 @@ pub fn summary() -> impl IntoView {
<h1>"Payout"</h1>
<div class="payout-image">{image}</div>
<div class="payout-amount">{symbol} " 💎" {move || winnings().abs()}</div>
<div class="payout-balance">"Funds: 💎 " {balance}</div>
<div class="payout-table">
<div>"Funds:"</div>
<div>"💎 " {balance}</div>
<div>"Debt:"</div>
<div>"💎 " {debt}</div>
<div>"Score:"</div>
<div>"💎 " {move || balance() - (debt() as i32)}</div>
</div>
</div>
</div>
}
Expand Down
8 changes: 3 additions & 5 deletions app/src/screens/router.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use std::cell::Cell;

use html::summary;
use leptos::*;
use leptos_router::{Route, Router as LeptosRouter, Routes};

use crate::{
screens::{game_wrapper::GameConnectionWrapper, host, main_menu::MainMenu, player},
utils::{reset_game_events, send_game_event, use_events, use_session_id},
utils::{send_game_event, use_events, use_session_id},
};
use shared::models::{events::Event, projections};

Expand Down Expand Up @@ -158,7 +157,6 @@ where
GameState::PreGame => pre_game().into_view(),
GameState::Race => race().into_view(),
GameState::Wait => wait().into_view(),
GameState::Summary => summary().into_view(),
GameState::FinalScreen => todo!(),
GameState::Summary | GameState::FinalScreen => summary().into_view(),
}
}
1 change: 1 addition & 0 deletions app/src/serve_files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ async fn get_static_file(
.await
{
Ok(res) => Ok(res.into_response()),
#[allow(unreachable_patterns)]
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Error serving files: {err}"),
Expand Down
4 changes: 4 additions & 0 deletions app/src/utils/err_wrapper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ use std::{convert::Infallible, fmt::Display};
use axum::{http::StatusCode, response::IntoResponse};

pub enum ErrWrapper {
#[cfg(feature = "wasm")]
Worker(worker::Error),
Axum(axum::http::Error),
Json(serde_json::Error),
JsValue(wasm_bindgen::JsValue),
Raw(String),
}

#[cfg(feature = "wasm")]
impl From<worker::Error> for ErrWrapper {
fn from(value: worker::Error) -> Self {
ErrWrapper::Worker(value)
Expand Down Expand Up @@ -49,6 +51,7 @@ impl From<Infallible> for ErrWrapper {
impl Display for ErrWrapper {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
#[cfg(feature = "wasm")]
ErrWrapper::Worker(err) => err.fmt(f),
ErrWrapper::Axum(err) => err.fmt(f),
ErrWrapper::Json(err) => err.fmt(f),
Expand All @@ -61,6 +64,7 @@ impl Display for ErrWrapper {
impl IntoResponse for ErrWrapper {
fn into_response(self) -> axum::response::Response {
match self {
#[cfg(feature = "wasm")]
ErrWrapper::Worker(err) => {
(StatusCode::INTERNAL_SERVER_ERROR, err.to_string()).into_response()
}
Expand Down
2 changes: 1 addition & 1 deletion app/src/utils/use_websocket.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use im::vector::Vector;
use leptos::{provide_context, use_context, ReadSignal, ServerFnError, Signal};
use leptos::{provide_context, use_context, ReadSignal, Signal};
use shared::models::{events::Event, game_id::GameID};

#[derive(Debug, Clone, PartialEq)]
Expand Down
12 changes: 9 additions & 3 deletions assets/pkg/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -626,8 +626,14 @@ input[type="number"] {
font-size: 40px;
}

.payout-balance {
.payout-table {
display: grid;
grid-template-columns: auto auto;
justify-items: right;
align-items: center;
font-size: 30px;
row-gap: 0.25em;
column-gap: 0.5em;
}

.server-status {
Expand Down Expand Up @@ -857,10 +863,10 @@ div .two-columns {
padding: 3em;

display: grid;
grid-template-columns: auto repeat(7, 200px);
grid-template-columns: auto repeat(7, 1fr);
grid-auto-rows: minmax(1fr, 300px);
gap: 1em;
justify-items: start;
justify-items: center;
align-items: center;
}

Expand Down
Loading

0 comments on commit b159771

Please sign in to comment.