Skip to content

Commit

Permalink
Changed the development flow for the frontend
Browse files Browse the repository at this point in the history
  • Loading branch information
TylerBloom committed Dec 20, 2023
1 parent 07fb70e commit e73e454
Show file tree
Hide file tree
Showing 6 changed files with 82 additions and 86 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,20 @@ rustup target add wasm32-unknown-unknown
cargo shuttle run
```

For development, you will need to run the backend via Shuttle and the frontend via trunk.
The trunk process will need to be configured to proxy calls to the backend.
To run the backend, run the follow command while your working directory is `SquireCore/squire_core`:
```
cargo shuttle run
```
To run the frontend, run the following command while your working directory is `SquireCore/squire_web`:
```
trunk serve --proxy-backend http://localhost:8000/ --proxy-rewrite /api/
```
Trunk will attempt to recompile and serve the frontend when you save your changes.
If successful, the frontend will reload with the new frontend.


## Current and Future State
This repo (and STS as a whole) are still growing rapidly.
Currently, everything in this repo is focused around proving the functionality of the tournament model; however, SquireCore (and therefore SquireSDK) will soon support many more things:
Expand Down
1 change: 0 additions & 1 deletion squire_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ authors = ["TylerBloom <tylerbloom2222@gmail.com>"]

[features]
db-tests = []
ignore-frontend = []

[dependencies]
# In-House deps
Expand Down
48 changes: 19 additions & 29 deletions squire_core/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,6 @@ use std::{
use flate2::{write::GzEncoder, Compression};

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

let wd = env::var("CARGO_MANIFEST_DIR").unwrap();
let fe_path = format!("{wd}/../squire_web");

println!("cargo:rerun-if-changed={fe_path}");

// Install external dependency (in the shuttle container only)
if std::env::var("HOSTNAME")
.unwrap_or_default()
Expand All @@ -46,37 +37,36 @@ fn main() -> Result<(), i32> {
{
panic!("failed to install trunk")
}
compile_fe()
} else if env::var("PROFILE")
.map(|v| v == "release")
.unwrap_or_default()
{
compile_fe()
} else {

Check failure on line 46 in squire_core/build.rs

View workflow job for this annotation

GitHub Actions / Tests (nightly, ubuntu-latest)

Diff in /home/runner/work/SquireCore/SquireCore/squire_core/build.rs

Check failure on line 46 in squire_core/build.rs

View workflow job for this annotation

GitHub Actions / Tests (nightly, ubuntu-latest)

Diff in /home/runner/work/SquireCore/SquireCore/squire_core/build.rs
Ok(())
}

}

fn compile_fe() -> Result<(), i32> {
// Calls trunk to compile the frontend
let mut cmd = Command::new("trunk");
cmd.args(["build", "-d", "../assets", "--filehash", "false"]);

let is_release = env::var("PROFILE")
.map(|v| v == "release")
.unwrap_or_default();

if is_release {
cmd.arg("--release");
}
cmd.arg(format!("{fe_path}/index.html"));

// 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(_)) {
eprintln!("Failed to compile frontend!");
if is_release {
return Err(1);
}
cmd.arg("--release");
cmd.arg("../squire_web/index.html");
if cmd.status().is_err() {
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_file =
File::open("../assets/squire_web_bg.wasm").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 output_file = File::create("../assets/squire_web_bg.wasm.gz").unwrap();
let mut encoder = GzEncoder::new(BufWriter::new(output_file), Compression::default());
encoder.write_all(&wasm_data).unwrap();

Expand Down
84 changes: 38 additions & 46 deletions squire_core/src/assets.rs
Original file line number Diff line number Diff line change
@@ -1,51 +1,43 @@
#[allow(clippy::wildcard_imports)]
pub use frontend::*;

#[cfg(feature = "ignore-frontend")]
mod frontend {
use axum::response::Html;

pub async fn landing() -> Html<&'static str> {
Html("Frontend not compiled...")
}

pub async fn get_wasm() {}

pub async fn get_js() {}
use axum::{
response::{Html, Response},
routing::get,

Check failure on line 3 in squire_core/src/assets.rs

View workflow job for this annotation

GitHub Actions / Tests (nightly, ubuntu-latest)

Diff in /home/runner/work/SquireCore/SquireCore/squire_core/src/assets.rs

Check failure on line 3 in squire_core/src/assets.rs

View workflow job for this annotation

GitHub Actions / Tests (nightly, ubuntu-latest)

Diff in /home/runner/work/SquireCore/SquireCore/squire_core/src/assets.rs
Router,
};
use crate::state::AppState;
use http::{header, HeaderMap, HeaderValue, StatusCode};
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.gz");
const APP_JS: &str = include_str!("../../assets/squire_web.js");

pub fn inject_ui(router: Router<AppState>) -> Router<AppState> {
router
.route("/", get(landing))
.route("/squire_web_bg.wasm", get(get_wasm))
.route("/squire_web.js", get(get_js))
.fallback(landing)
}

#[cfg(all(feature = "ignore-frontend", not(debug_assertions)))]
compile_error!("In release mode, you must compile the frontend!");

#[cfg(not(feature = "ignore-frontend"))]
mod frontend {
use axum::response::Html;
use http::{header, HeaderMap, HeaderValue};

const INDEX_HTML: &str = include_str!("../../assets/index.html");
const APP_WASM: &'static [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> {
Html(INDEX_HTML)
}
pub async fn landing() -> Html<&'static str> {
Html(INDEX_HTML)
}

pub async fn get_wasm() -> (HeaderMap, &'static [u8]) {
let mut headers = HeaderMap::with_capacity(2);
headers.insert(header::CONTENT_ENCODING, HeaderValue::from_static("gzip")); // Unzips the compressed file
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/wasm"),
);
(headers, APP_WASM)
}
pub async fn get_wasm() -> (HeaderMap, &'static [u8]) {
let mut headers = HeaderMap::with_capacity(2);
headers.insert(header::CONTENT_ENCODING, HeaderValue::from_static("gzip")); // Unzips the compressed file
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/wasm"),
);
(headers, APP_WASM)
}

pub async fn get_js() -> (HeaderMap, &'static str) {
let mut headers = HeaderMap::with_capacity(1);
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/javascript;charset=utf-8"),
);
(headers, APP_JS)
}
pub async fn get_js() -> (StatusCode, HeaderMap, &'static str) {
let mut headers = HeaderMap::with_capacity(1);
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/javascript;charset=utf-8"),
);
(StatusCode::OK, headers, APP_JS)
}
19 changes: 10 additions & 9 deletions squire_core/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ use tower_http::cors::CorsLayer;
#[cfg(test)]
mod tests;

mod accounts;
#[cfg(not(debug_assertions))]
mod assets;

mod accounts;
mod session;
mod state;

Expand All @@ -16,7 +18,7 @@ use session::*;
use state::{AppState, AppStateBuilder};

pub fn create_router(state: AppState) -> Router {
server::create_router::<AppState>()
let router = server::create_router::<AppState>()
.add_route::<0, POST, RegForm, _, _>(create_account)
.add_route::<0, GET, AccountCrud, _, _>(get_account)
.add_route::<0, DELETE, AccountCrud, _, _>(delete_account)
Expand All @@ -25,13 +27,12 @@ pub fn create_router(state: AppState) -> Router {
.add_route::<0, POST, Reauth, _, _>(reauth)
.add_route::<0, DELETE, Terminate, _, _>(terminate)
.add_route::<0, GET, GetSessionStatus, _, _>(status)
.into_router()
.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)
.into_router();

#[cfg(not(debug_assertions))]
let router = assets::inject_ui(router);

router.layer(CorsLayer::permissive()).with_state(state)
}

#[shuttle_runtime::main]
Expand Down
2 changes: 1 addition & 1 deletion squire_sdk/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use crate::{
Credentials, GetRequest, ListTournaments, PostRequest, RegForm, SessionToken,
TournamentSummary,
},
compat::{log, NetworkError, NetworkResponse, Request, Sendable},
compat::{NetworkError, NetworkResponse, Request, Sendable},
model::{
accounts::SquireAccount, identifiers::TournamentId, operations::TournOp,
players::PlayerRegistry, rounds::RoundRegistry, tournament::TournamentSeed,
Expand Down

0 comments on commit e73e454

Please sign in to comment.