Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Frontend refactor #161

Merged
merged 27 commits into from
Oct 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
8f9bdb2
Added session types to SDK, more types to come. Client needs to be up…
TylerBloom Aug 6, 2023
f0b2a5f
Added internals of session token. Expanded session management for Ser…
TylerBloom Aug 9, 2023
b6f30cf
Added initial impl of session management actor in SC
TylerBloom Aug 18, 2023
0378d7e
Added skeleton for account CRUD APIs
TylerBloom Aug 19, 2023
4309219
Added prototype actor model
TylerBloom Sep 2, 2023
2e04ff4
Corrected issues in SDK WASM build caused by recent refactor. Moved c…
TylerBloom Sep 7, 2023
c7cec6b
Finalized new actors in client
TylerBloom Sep 9, 2023
1601ec8
Updated SC to use new APIs and server state
TylerBloom Sep 13, 2023
cadf374
Fleshed out DB layer for session management
TylerBloom Sep 17, 2023
2843569
Starting work on refactoring viewer components.
fintanneff Jul 29, 2023
a467fca
Progress on UI refactor.
fintanneff Aug 12, 2023
e45239f
Pairings view now functional with refactor.
fintanneff Sep 1, 2023
40af0ff
Further progress on the UI refector...
fintanneff Sep 12, 2023
cc89be1
Rebase corrections
TylerBloom Sep 13, 2023
0e19dbc
Progress on refactor for the player.
fintanneff Sep 23, 2023
57089e9
Player refactor in functional state.
fintanneff Sep 28, 2023
bc89d8d
Rounds refactor seemingly in a functional state.
fintanneff Sep 28, 2023
74c5d2f
Update functions refactored.
fintanneff Oct 1, 2023
69475e8
Corrected SC state mod.rs
TylerBloom Oct 19, 2023
f476cb8
Settings refactor seemingly completed.
fintanneff Oct 20, 2023
df232b9
WASM asset get compressed when building the backend and served
CalebLItalien Oct 15, 2023
7d5e775
Implemented remaining PR suggestions.
fintanneff Oct 21, 2023
24389ec
Used TournQuery alias where applicable.
fintanneff Oct 22, 2023
53f15c4
Minor cleanup for CI
TylerBloom Oct 24, 2023
50405fc
Formatted and made clippy happy
TylerBloom Oct 24, 2023
4528afb
Updated workflows to use stable and beta toolchains. Fixed minor erro…
TylerBloom Oct 25, 2023
aa0e3f4
Correct backend build script
TylerBloom Oct 25, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/squire_core_ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,6 @@ jobs:
with:
mongodb-version: '6.0'
- run: cargo fmt --check --package squire_core
- run: cargo build --package squire_core --verbose --features="db-tests"
- run: cargo build --package squire_core --verbose
- run: cargo test --package squire_core --verbose --features="db-tests"
- run: cargo doc --package squire_core --verbose --features="db-tests"
- run: cargo doc --package squire_core --verbose
4 changes: 2 additions & 2 deletions .github/workflows/squire_sdk_ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
rust: [nightly]
rust: [stable, beta, nightly]
os: [ubuntu-latest, windows-latest, macOS-latest]
steps:
- uses: hecrj/setup-rust-action@v2
Expand All @@ -33,7 +33,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
rust: [nightly]
rust: [nightly, beta, stable]
steps:
- uses: hecrj/setup-rust-action@v2
with:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/squire_web_ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
rust: [nightly]
rust: [stable, beta, nightly]
steps:
- uses: hecrj/setup-rust-action@v2
with:
Expand Down
9 changes: 5 additions & 4 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
Cargo.lock
./cbindgen.toml
./squire_core.h

assets/*

/assets/
squire_web/dist/*
squire_web/target
.history/*
squire_web/.idea
.history/
build_outputs/*
.idea/
4 changes: 4 additions & 0 deletions squire_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,14 @@ hyper = { version = "0.14" }
shuttle-runtime = { version = "0.29.0", features = [] }
shuttle-shared-db = { version = "0.29.0", features = ["mongodb"] }
shuttle-axum = { version = "0.29.0", features = [] }
tower-http = { version = "0.4.4", features = ["cors"] }

[dev-dependencies]
# In-house
squire_tests = { path = "../squire_tests" }

tower = { version = "0.4", features = ["util"] }
hyper = { version = "0.14", features = ["full"] }

[build-dependencies]
flate2 = "1.0"
33 changes: 27 additions & 6 deletions squire_core/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,18 @@
* JS bindings. Trunk is used to compile and generate the app and the JS bindings.
*/

use std::{env, process::Command};
use std::{
env,
fs::File,
io::{BufWriter, Read, Write},
process::Command,
};

use flate2::{write::GzEncoder, Compression};

fn main() -> Result<(), i32> {
if env::var("CARGO_FEATURE_IGNORE_FRONTEND").is_ok() {
return Ok(())
return Ok(());
}

let wd = env::var("CARGO_MANIFEST_DIR").unwrap();
Expand Down Expand Up @@ -55,9 +62,23 @@ fn main() -> Result<(), i32> {

// If in debug mode, all for failed compilation of frontend.
// In release mode, require that the frontend to be functional.
if matches!(cmd.status().map(|s| s.success()), Ok(false) | Err(_)) && is_release {
Err(1)
} else {
Ok(())
if matches!(cmd.status().map(|s| s.success()), Ok(false) | Err(_)) {
eprintln!("Failed to compile frontend!");
if is_release {
return Err(1);
}
}

// Compresses the wasm package
let wasm_package = format!("{wd}/../assets/squire_web_bg.wasm");
let mut wasm_file = File::open(wasm_package).expect("Failed to open WASM file");
let mut wasm_data = Vec::new();
wasm_file.read_to_end(&mut wasm_data).unwrap();

let output_path = format!("{wd}/../assets/squire_web_bg.wasm.gz");
let output_file = File::create(output_path).unwrap();
let mut encoder = GzEncoder::new(BufWriter::new(output_file), Compression::default());
encoder.write_all(&wasm_data).unwrap();

Ok(())
}
3 changes: 2 additions & 1 deletion squire_core/src/assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ mod frontend {
use hyper::{body::Bytes, Body};

const INDEX_HTML: &str = include_str!("../../assets/index.html");
const APP_WASM: &[u8] = include_bytes!("../../assets/squire_web_bg.wasm");
const APP_WASM: &[u8] = include_bytes!("../../assets/squire_web_bg.wasm.gz");
const APP_JS: &str = include_str!("../../assets/squire_web.js");

pub async fn landing() -> Html<&'static str> {
Expand All @@ -36,6 +36,7 @@ mod frontend {
let body: Body = bytes.into();

Response::builder()
.header(header::CONTENT_ENCODING, "gzip") // Unzips the compressed file
.header(header::CONTENT_TYPE, "application/wasm")
.body(body)
.unwrap()
Expand Down
7 changes: 6 additions & 1 deletion squire_core/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use axum::{routing::get, Router};
use mongodb::Database;
use squire_sdk::{api::*, server};
use tower_http::cors::CorsLayer;

#[cfg(test)]
mod tests;
Expand All @@ -25,11 +26,15 @@ pub fn create_router(state: AppState) -> Router {
.add_route::<0, POST, Reauth, _, _>(reauth)
.add_route::<0, DELETE, Terminate, _, _>(terminate)
.into_router()
.route("/api/v1/tournaments/subscribe/other/:t_id", get(tournaments::join_gathering))
.route(
"/api/v1/tournaments/subscribe/other/:t_id",
get(tournaments::join_gathering),
)
.route("/", get(assets::landing))
.route("/squire_web_bg.wasm", get(assets::get_wasm))
.route("/squire_web.js", get(assets::get_js))
.fallback(assets::landing)
.layer(CorsLayer::permissive())
.with_state(state)
}

Expand Down
7 changes: 5 additions & 2 deletions squire_core/src/state/boilerplate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ impl Trackable<AnyUser, SessionToken> for SessionCommand {
}

impl Trackable<SessionToken, Option<watch::Receiver<SquireSession>>> for SessionCommand {
fn track(msg: SessionToken, send: OneshotSender<Option<watch::Receiver<SquireSession>>>) -> Self {
fn track(
msg: SessionToken,
send: OneshotSender<Option<watch::Receiver<SquireSession>>>,
) -> Self {
Self::Subscribe(msg, send)
}
}
Expand All @@ -48,7 +51,7 @@ impl Trackable<AnyUser, bool> for SessionCommand {

impl Debug for SessionCommand {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self{
match self {
Self::Create(value, _) => write!(f, "Create({value:?})"),
Self::Guest(_) => write!(f, "Guest()"),
Self::Get(value, _) => write!(f, "Get({value:?})"),
Expand Down
21 changes: 7 additions & 14 deletions squire_core/src/state/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,9 @@ impl ActorState for SessionStore {
async fn process(&mut self, scheduler: &mut Scheduler<Self>, msg: Self::Message) {
println!("Got session message: {msg:?}");
match msg {
SessionCommand::Create(id, send) => drop(send.send(self.create_session(scheduler, id).token)),
SessionCommand::Create(id, send) => {
drop(send.send(self.create_session(scheduler, id).token))
}
SessionCommand::Get(token, send) => drop(send.send(self.get_session(token))),
SessionCommand::Reauth(id, send) => drop(send.send(self.reauth_session(scheduler, id))),
SessionCommand::Delete(id, send) => drop(send.send(self.delete_session(scheduler, id))),
Expand Down Expand Up @@ -145,11 +147,7 @@ impl SessionStore {
digest
}

fn create_session(
&mut self,
scheduler: &mut Scheduler<Self>,
id: SquireAccountId,
) -> Session {
fn create_session(&mut self, scheduler: &mut Scheduler<Self>, id: SquireAccountId) -> Session {
let token = self.generate_session(scheduler);
let session = Session::new_with_id(token.clone(), id);
self.sessions.insert(token.clone(), session.clone());
Expand Down Expand Up @@ -254,10 +252,7 @@ impl SessionStore {
self.sessions.remove(token)
}

fn sub_to_session(
&mut self,
token: &SessionToken,
) -> Option<Watcher<SquireSession>> {
fn sub_to_session(&mut self, token: &SessionToken) -> Option<Watcher<SquireSession>> {
self.comms
.get(token)
.map(|comm| comm.subscribe())
Expand All @@ -274,8 +269,8 @@ impl SessionStore {
}

impl SessionDb {
const ACTIVE_SESSION_TABLE: &str = "ActiveSessions";
const EXPIRED_SESSION_TABLE: &str = "ExpiredSessions";
const ACTIVE_SESSION_TABLE: &'static str = "ActiveSessions";
const EXPIRED_SESSION_TABLE: &'static str = "ExpiredSessions";

pub fn new(db: Database) -> Self {
Self { db }
Expand Down Expand Up @@ -460,5 +455,3 @@ impl Session {
}
}
}


11 changes: 6 additions & 5 deletions squire_core/src/state/tournaments.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
use std::{sync::Arc, ops::Range};
use std::{ops::Range, sync::Arc};

use futures::StreamExt;
use mongodb::{
bson::{doc, spec::BinarySubtype, Binary, Document},
Collection, Database, options::{UpdateModifications, UpdateOptions, Hint, FindOptions},
options::{FindOptions, Hint, UpdateModifications, UpdateOptions},
Collection, Database,
};
use squire_sdk::{
actor::*, model::tournament::TournamentId, server::gathering::PersistMessage,
sync::TournamentManager, api::TournamentSummary,
actor::*, api::TournamentSummary, model::tournament::TournamentId,
server::gathering::PersistMessage, sync::TournamentManager,
};
use tracing::Level;

Expand Down Expand Up @@ -48,7 +49,7 @@ impl TournPersister {
}

impl TournDb {
const TOURN_INDEX_NAME: &str = "tourn_id";
const TOURN_INDEX_NAME: &'static str = "tourn_id";

pub fn new(db_conn: Database, tourn_coll: Arc<str>) -> Self {
Self {
Expand Down
4 changes: 4 additions & 0 deletions squire_lib/src/identifiers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@ impl<T> TypeId<T> {
pub fn new(id: Uuid) -> Self {
Self(id, PhantomData)
}
/// Converts type id into another type id of type U
pub fn convert<U>(self) -> TypeId<U> {
TypeId::<U>::new(self.0)
}
}

impl<T> Default for TypeId<T> {
Expand Down
4 changes: 2 additions & 2 deletions squire_lib/src/tournament.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1001,7 +1001,7 @@ impl Tournament {
}

impl TournamentSeed {
const MAGIC_SYNONYMS: &[&'static str] = &[
const MAGIC_SYNONYMS: &'static [&'static str] = &[
"Magic",
"Illusion",
"Wizardry",
Expand Down Expand Up @@ -1031,7 +1031,7 @@ impl TournamentSeed {
"Witchcraft",
];

const GATHERING_SYNONYMS: &[&'static str] = &[
const GATHERING_SYNONYMS: &'static [&'static str] = &[
"Gathering",
"Association",
"Caucus",
Expand Down
1 change: 1 addition & 0 deletions squire_sdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ server = [
"axum/json",
"axum/macros",
"axum/headers",
"tokio/full",
"headers",
"serde_json",
"cookie",
Expand Down
30 changes: 25 additions & 5 deletions squire_sdk/src/client/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ impl<UP: OnUpdate> ClientBuilder<UP, String, ()> {
let user = state.subscribe();
let client = ActorBuilder::new(state).launch();
let tourns = TournsClient::new(client.clone(), on_update);
Ok(SquireClient { client, tourns, user })
Ok(SquireClient {
client,
tourns,
user,
})
}

/// Creates a client but does not check if the URL is valid.
Expand All @@ -99,7 +103,11 @@ impl<UP: OnUpdate> ClientBuilder<UP, String, ()> {
let user = state.subscribe();
let client = ActorBuilder::new(state).launch();
let tourns = TournsClient::new(client.clone(), on_update);
SquireClient { client, tourns, user }
SquireClient {
client,
tourns,
user,
}
}
}

Expand All @@ -112,7 +120,11 @@ impl<UP: OnUpdate> ClientBuilder<UP, String, Credentials> {
let user = state.subscribe();
let client = ActorBuilder::new(state).launch();
let tourns = TournsClient::new(client.clone(), on_update);
Ok(SquireClient { client, tourns, user })
Ok(SquireClient {
client,
tourns,
user,
})
}
}

Expand All @@ -129,7 +141,11 @@ impl<UP: OnUpdate> ClientBuilder<UP, String, SquireAccount> {
let user = state.subscribe();
let client = ActorBuilder::new(state).launch();
let tourns = TournsClient::new(client.clone(), on_update);
Ok(SquireClient { client, tourns, user })
Ok(SquireClient {
client,
tourns,
user,
})
}

/// Creates a client but does not check if the URL is valid.
Expand All @@ -143,6 +159,10 @@ impl<UP: OnUpdate> ClientBuilder<UP, String, SquireAccount> {
let user = state.subscribe();
let client = ActorBuilder::new(state).launch();
let tourns = TournsClient::new(client.clone(), on_update);
SquireClient { client, tourns, user }
SquireClient {
client,
tourns,
user,
}
}
}
3 changes: 2 additions & 1 deletion squire_sdk/src/client/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ impl ActorState for NetworkState {
type Message = NetworkCommand;

async fn start_up(&mut self, scheduler: &mut Scheduler<Self>) {
let resp = self.post_request(GuestSession, [])
let resp = self
.post_request(GuestSession, [])
.map(|resp| resp.map(|resp| SessionToken::try_from(resp.headers()).ok()))
.await;
self.process(scheduler, resp.into()).await;
Expand Down
6 changes: 5 additions & 1 deletion squire_sdk/src/client/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{
use futures::Future;
use instant::{Duration, Instant};
use pin_project::pin_project;
use squire_lib::accounts::SquireAccount;
use squire_lib::{accounts::SquireAccount, identifiers::SquireAccountId};
use tokio::sync::watch::{channel, Receiver as Watcher, Sender as Broadcaster};

use crate::compat::{sleep_until, Sleep};
Expand Down Expand Up @@ -121,6 +121,10 @@ impl SessionWatcher {
pub fn session_info(&self) -> SessionInfo {
self.recv.borrow().clone()
}

pub fn get_squire_account_id(&self) -> Option<SquireAccountId> {
self.session_info().get_user().map(|acc| acc.id)
}
}

impl SessionInfo {
Expand Down
Loading