1 Commits

Author SHA1 Message Date
f31e87780f Merge pull request 'Add simple data store' (#3) from simple_data_store into main
All checks were successful
Build Crate / build (push) Successful in 5m7s
Reviewed-on: https://questia.dev/git/vsquad/pool-elo/pulls/3
2023-09-20 05:07:31 +00:00
19 changed files with 99 additions and 295 deletions

View File

@@ -1,2 +0,0 @@
[build]
rustflags = [ "--cfg", "engine" ]

2
.gitignore vendored
View File

@@ -6,4 +6,4 @@ static
pkg pkg
./Cargo.lock ./Cargo.lock
package-lock.json package-lock.json
/data/ data

View File

@@ -6,29 +6,18 @@ edition = "2021"
[dependencies] [dependencies]
perseus = { version = "0.4.2", features = [ "hydrate" ] } perseus = { version = "0.4.2", features = [ "hydrate" ] }
sycamore = { version = "0.8.2", features = [ sycamore = "0.8.2"
"suspense",
"web",
"wasm-bindgen-interning",
] }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
env_logger = "0.10.0" env_logger = "0.10.0"
log = "0.4.20" log = "0.4.20"
once_cell = "1.18.0" once_cell = "1.18.0"
web-sys = "0.3.64"
cfg-if = "1.0.0"
chrono = { version = "0.4.31", features = ["serde"] }
[target.'cfg(engine)'.dev-dependencies] [target.'cfg(engine)'.dev-dependencies]
fantoccini = "0.19" fantoccini = "0.19"
[target.'cfg(engine)'.dependencies] [target.'cfg(engine)'.dependencies]
tokio = { version = "1", features = [ "macros", "rt", "rt-multi-thread" ] } tokio = { version = "1", features = [ "macros", "rt", "rt-multi-thread" ] }
perseus-axum = { version = "0.4.2" } perseus-axum = { version = "0.4.2", features = [ "dflt-server" ] }
axum = "0.6"
tower-http = { version = "0.3", features = ["fs"] }
[target.'cfg(client)'.dependencies] [target.'cfg(client)'.dependencies]
wasm-bindgen = "0.2"
reqwest = { version = "0.11", features = ["json"] }

View File

@@ -23,7 +23,7 @@ https://nodejs.org/en
## 3. Install Perseus, for real-time updates while developing ## 3. Install Perseus, for real-time updates while developing
`cargo install perseus-cli` `cargo install perseus-cli`
`rustup target add wasm32-unknown-unknown` `cargo build --target wasm32-unknown-unknown`
## 4. Install tailwindcss, for styling ## 4. Install tailwindcss, for styling
@@ -43,7 +43,7 @@ To build CSS run:
`npm run build` `npm run build`
To build the project for testing, run To build the project for testing, run
`perseus serve --verbose` `perseus serve`
# Deploying the project # Deploying the project

View File

@@ -2,18 +2,24 @@ use sycamore::prelude::*;
#[derive(Prop)] #[derive(Prop)]
pub struct LayoutProps<'a, G: Html> { pub struct LayoutProps<'a, G: Html> {
/// The title of the page, which will be displayed in the header.
pub title: &'a str, pub title: &'a str,
/// The content to put inside the layout.
pub children: Children<'a, G>, pub children: Children<'a, G>,
} }
#[component] #[component]
pub fn Layout<'a, G: Html>( pub fn Layout<'a, G: Html>(
cx: Scope<'a>, cx: Scope<'a>,
LayoutProps { title: _, children }: LayoutProps<'a, G>, LayoutProps { title, children }: LayoutProps<'a, G>,
) -> View<G> { ) -> View<G> {
let children = children.call(cx); let children = children.call(cx);
// example params
// p { (title.to_string()) }
view! { cx, view! { cx,
// These elements are styled with bright colors for demonstration purposes
header { header {
div (class = "flex items-center justify-between") { div (class = "flex items-center justify-between") {
div (class = "w-full text-gray-700 md:text-center text-2xl font-semibold") { div (class = "w-full text-gray-700 md:text-center text-2xl font-semibold") {

View File

@@ -1,5 +1,2 @@
pub mod pool_match; pub mod pool_match;
pub mod user;
#[cfg(engine)]
pub mod store; pub mod store;

View File

@@ -1,56 +1,11 @@
use crate::data::user::PlayerId;
use chrono::serde::ts_seconds;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
pub type MatchId = u32; #[derive(Serialize, Deserialize, Clone)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum MatchData {
Standard8Ball {
winner: PlayerId,
loser: PlayerId,
},
Standard9Ball {
winner: PlayerId,
loser: PlayerId,
},
CutThroat {
winner: PlayerId,
losers: [PlayerId; 2],
},
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct PoolMatch { pub struct PoolMatch {
pub id: MatchId, pub players: Vec<String>,
pub data: MatchData, pub winner: String,
#[serde(with = "ts_seconds")]
pub time: DateTime<Utc>,
} }
#[derive(Serialize, Deserialize, Clone, Debug)] #[derive(Serialize, Deserialize, Clone)]
pub struct PoolMatchList { pub struct PoolMatchList {
pub pool_matches: Vec<PoolMatch>, pub pool_matches: Vec<PoolMatch>,
pub max_id: MatchId,
}
impl PoolMatch {
pub fn new(data: MatchData, time: DateTime<Utc>) -> PoolMatch {
PoolMatch { id: 0, data, time }
}
}
impl PoolMatchList {
pub fn new() -> PoolMatchList {
PoolMatchList {
pool_matches: vec![],
max_id: 0,
}
}
pub fn add_pool_match(&mut self, mut pool_match: PoolMatch) {
pool_match.id = self.max_id + 1;
self.max_id += 1;
self.pool_matches.push(pool_match);
}
} }

View File

@@ -1,9 +1,13 @@
// (Server only) In-memory data storage and persistent storage #![cfg(engine)]
use crate::data::pool_match::PoolMatchList; use std::collections::HashMap;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize}; use std::sync::Mutex;
use std::{fs, path::Path, sync::Mutex}; use serde::{Serialize, Deserialize};
use crate::data::pool_match::{PoolMatchList, PoolMatch};
use std::fs;
use std::path::Path;
#[derive(Serialize, Deserialize, Clone)] #[derive(Serialize, Deserialize, Clone)]
pub struct Store { pub struct Store {
@@ -12,23 +16,25 @@ pub struct Store {
impl Store { impl Store {
fn new() -> Store { fn new() -> Store {
fs::create_dir_all("data").unwrap(); fs::create_dir_all("data");
match Path::new("data/store.json").exists() { match Path::new("data/store.json").exists() {
false => Store { false => {
matches: PoolMatchList::new(), Store {
}, matches: PoolMatchList { pool_matches: vec![] },
}
}
true => { true => {
let contents = fs::read_to_string("data/store.json").unwrap(); let contents = fs::read_to_string("data/store.json").unwrap();
serde_json::from_str(&contents).unwrap() serde_json::from_str(&contents).unwrap()
} }
} }
} }
// TODO -> Store data
#[allow(dead_code)]
pub fn write(&self) { pub fn write(&self) {
let contents = serde_json::to_string(&self).unwrap(); let contents = serde_json::to_string(&self).unwrap();
fs::write("data/store.json", contents).unwrap(); fs::write("data/store.json", contents).unwrap();
} }
} }
pub static DATA: Lazy<Mutex<Store>> = Lazy::new(|| Mutex::new(Store::new())); pub static DATA: Lazy<Mutex<Store>> = Lazy::new(|| {
Mutex::new(Store::new())
});

View File

@@ -1,3 +0,0 @@
pub type PlayerId = u32;

View File

@@ -1 +0,0 @@
pub const MATCH: &str = "/api/post-match";

View File

@@ -1,52 +1,16 @@
mod components; mod components;
mod data;
mod endpoints;
mod error_views;
#[cfg(engine)]
mod server;
mod templates; mod templates;
mod data;
mod error_views;
use perseus::prelude::*; use perseus::prelude::*;
use sycamore::prelude::view; use sycamore::prelude::view;
cfg_if::cfg_if! { #[perseus::main(perseus_axum::dflt_server)]
if #[cfg(engine)] {
use std::net::SocketAddr;
use perseus::{
i18n::TranslationsManager,
server::ServerOptions,
stores::MutableStore,
turbine::Turbine,
};
use crate::server::routes::register_routes;
}
}
#[cfg(engine)]
pub async fn dflt_server<M: MutableStore + 'static, T: TranslationsManager + 'static>(
turbine: &'static Turbine<M, T>,
opts: ServerOptions,
(host, port): (String, u16),
) {
let addr: SocketAddr = format!("{}:{}", host, port)
.parse()
.expect("Invalid address provided to bind to.");
let mut app = perseus_axum::get_router(turbine, opts).await;
app = register_routes(app);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
#[perseus::main(dflt_server)]
pub fn main<G: Html>() -> PerseusApp<G> { pub fn main<G: Html>() -> PerseusApp<G> {
env_logger::init(); env_logger::init();
PerseusApp::new() PerseusApp::new()
.global_state_creator(crate::templates::global_state::get_global_state_creator())
.template(crate::templates::index::get_template()) .template(crate::templates::index::get_template())
.template(crate::templates::add_game_form::get_template()) .template(crate::templates::add_game_form::get_template())
.template(crate::templates::one_v_one_board::get_template()) .template(crate::templates::one_v_one_board::get_template())

View File

@@ -1,2 +0,0 @@
pub mod routes;

View File

@@ -1,34 +0,0 @@
// (Server only) Routes
use crate::{
data::{
pool_match::{PoolMatch, PoolMatchList},
store::DATA,
},
endpoints::MATCH,
};
use axum::{
extract::Json,
routing::{post, Router},
};
use std::thread;
pub fn register_routes(app: Router) -> Router {
let app = app.route(MATCH, post(post_match));
app
}
async fn post_match(Json(pool_match): Json<PoolMatch>) -> Json<PoolMatchList> {
// Update the store with the new match
let matches = thread::spawn(move || {
// Get the store
let mut data = DATA.lock().unwrap();
(*data).matches.add_pool_match(pool_match);
println!("{:?}", (*data).matches.pool_matches);
(*data).matches.clone()
})
.join()
.unwrap();
Json(matches)
}

View File

@@ -1,66 +1,21 @@
use crate::{components::layout::Layout, data::pool_match::MatchData}; use crate::components::layout::Layout;
use perseus::prelude::*; use perseus::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sycamore::prelude::*; use sycamore::prelude::*;
use web_sys::Event;
cfg_if::cfg_if! {
if #[cfg(client)] {
use crate::data::pool_match::{PoolMatch, PoolMatchList};
use crate::templates::global_state::AppStateRx;
use crate::endpoints::MATCH;
use crate::templates::get_api_path;
use chrono::Utc;
}
}
// Reactive page // Reactive page
#[derive(Serialize, Deserialize, Clone, ReactiveState)] #[derive(Serialize, Deserialize, Clone, ReactiveState)]
#[rx(alias = "PageStateRx")] #[rx(alias = "PageStateRx")]
struct PageState { struct PageState {
name: String,
} }
fn add_game_form_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, state: &'a PageStateRx) -> View<G> { fn add_game_form_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, state: &'a PageStateRx) -> View<G> {
let handle_add_match = move |_event: Event| {
#[cfg(client)]
{
// state.name.get().as_ref().clone()
spawn_local_scoped(cx, async move {
let new_match = PoolMatch::new(MatchData::Standard8Ball { winner: 1, loser: 2 }, Utc::now());
let client = reqwest::Client::new();
let new_matches = client
.post(get_api_path(MATCH).as_str())
.json(&new_match)
.send()
.await
.unwrap()
.json::<PoolMatchList>()
.await
.unwrap();
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
global_state.matches.set(new_matches);
})
}
};
view! { cx, view! { cx,
Layout(title = "Add Game Results") { Layout(title = "Add Game Results") {
div (class = "flex flex-wrap") { // Anything we put in here will be rendered inside the `<main>` block of the layout
input (bind:value = state.name, p { "Results" }
class = "appearance-none block w-full bg-gray-200 text-gray-700 border \
border-red-500 rounded py-3 px-4 mb-3 leading-tight focus:outline-none \
focus:bg-white",)
}
div (class = "flex flex-wrap") {
button(on:click = handle_add_match,
class = "flex-shrink-0 bg-teal-500 hover:bg-teal-700 border-teal-500 \
hover:border-teal-700 text-sm border-4 text-white py-1 px-2 rounded",
) {
"Add result"
}
}
} }
} }
} }
@@ -68,11 +23,9 @@ fn add_game_form_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, state: &'a PageStat
#[engine_only_fn] #[engine_only_fn]
async fn get_request_state( async fn get_request_state(
_info: StateGeneratorInfo<()>, _info: StateGeneratorInfo<()>,
_req: Request, req: Request,
) -> Result<PageState, BlamedError<std::convert::Infallible>> { ) -> Result<PageState, BlamedError<std::convert::Infallible>> {
Ok(PageState { Ok(PageState {})
name: "Ferris".to_string(),
})
} }
#[engine_only_fn] #[engine_only_fn]
@@ -82,6 +35,7 @@ fn head(cx: Scope) -> View<SsrNode> {
} }
} }
// Template // Template
pub fn get_template<G: Html>() -> Template<G> { pub fn get_template<G: Html>() -> Template<G> {

View File

@@ -1,44 +0,0 @@
// Not a page, global state that is shared between all pages
use crate::data::pool_match::PoolMatchList;
use perseus::{prelude::*, state::GlobalStateCreator};
use serde::{Deserialize, Serialize};
cfg_if::cfg_if! {
if #[cfg(engine)] {
use std::thread;
use std::ops::Deref;
use crate::data::store::DATA;
}
}
#[derive(Serialize, Deserialize, ReactiveState, Clone)]
#[rx(alias = "AppStateRx")]
pub struct AppState {
pub matches: PoolMatchList,
}
pub fn get_global_state_creator() -> GlobalStateCreator {
GlobalStateCreator::new()
.build_state_fn(get_build_state)
.request_state_fn(get_request_state)
}
#[engine_only_fn]
fn get_state() -> AppState {
let matches = thread::spawn(move || DATA.lock().unwrap().deref().matches.clone())
.join()
.unwrap();
AppState { matches }
}
#[engine_only_fn]
pub async fn get_build_state() -> AppState {
get_state()
}
#[engine_only_fn]
pub async fn get_request_state(_req: Request) -> AppState {
get_state()
}

View File

@@ -20,5 +20,8 @@ fn head(cx: Scope) -> View<SsrNode> {
} }
pub fn get_template<G: Html>() -> Template<G> { pub fn get_template<G: Html>() -> Template<G> {
Template::build("").view(index_page).head(head).build() Template::build("")
.view(index_page)
.head(head)
.build()
} }

View File

@@ -1,22 +1,4 @@
pub mod add_game_form;
pub mod global_state;
pub mod index; pub mod index;
pub mod add_game_form;
pub mod one_v_one_board; pub mod one_v_one_board;
pub mod overall_board; pub mod overall_board;
#[cfg(client)]
use perseus::utils::get_path_prefix_client;
#[allow(dead_code)]
pub fn get_api_path(path: &str) -> String {
#[cfg(engine)]
{
path.to_string()
}
#[cfg(client)]
{
let origin = web_sys::window().unwrap().origin();
let base_path = get_path_prefix_client();
format!("{}{}{}", origin, base_path, path)
}
}

View File

@@ -3,13 +3,18 @@ use perseus::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sycamore::prelude::*; use sycamore::prelude::*;
// Reactive page
#[derive(Serialize, Deserialize, Clone, ReactiveState)] #[derive(Serialize, Deserialize, Clone, ReactiveState)]
#[rx(alias = "PageStateRx")] #[rx(alias = "PageStateRx")]
struct PageState {} struct PageState {
fn one_v_one_board_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, _state: &'a PageStateRx) -> View<G> { }
fn one_v_one_board_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, state: &'a PageStateRx) -> View<G> {
view! { cx, view! { cx,
Layout(title = "1v1 Leaderboard") { Layout(title = "1v1 Leaderboard") {
// Anything we put in here will be rendered inside the `<main>` block of the layout
p { "leaderboard" } p { "leaderboard" }
} }
} }
@@ -18,7 +23,7 @@ fn one_v_one_board_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, _state: &'a PageS
#[engine_only_fn] #[engine_only_fn]
async fn get_request_state( async fn get_request_state(
_info: StateGeneratorInfo<()>, _info: StateGeneratorInfo<()>,
_req: Request, req: Request,
) -> Result<PageState, BlamedError<std::convert::Infallible>> { ) -> Result<PageState, BlamedError<std::convert::Infallible>> {
Ok(PageState {}) Ok(PageState {})
} }
@@ -30,6 +35,9 @@ fn head(cx: Scope) -> View<SsrNode> {
} }
} }
// Template
pub fn get_template<G: Html>() -> Template<G> { pub fn get_template<G: Html>() -> Template<G> {
Template::build("one-v-one-board") Template::build("one-v-one-board")
.request_state_fn(get_request_state) .request_state_fn(get_request_state)

View File

@@ -1,30 +1,40 @@
use crate::{components::layout::Layout, templates::global_state::AppStateRx}; use crate::components::layout::Layout;
use perseus::prelude::*; use perseus::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[cfg(engine)]
use crate::data::store::DATA;
#[cfg(engine)]
use std::thread;
use sycamore::prelude::*; use sycamore::prelude::*;
use crate::data::pool_match::{
PoolMatchList, PoolMatch
};
// Reactive page
#[derive(Serialize, Deserialize, Clone, ReactiveState)] #[derive(Serialize, Deserialize, Clone, ReactiveState)]
#[rx(alias = "PageStateRx")] #[rx(alias = "PageStateRx")]
struct PageState {} struct PageState {
matches: PoolMatchList,
fn overall_board_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, _state: &'a PageStateRx) -> View<G> { }
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
fn overall_board_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, state: &'a PageStateRx) -> View<G> {
view! { cx, view! { cx,
Layout(title = "Overall Leaderboard") { Layout(title = "Overall Leaderboard") {
// Anything we put in here will be rendered inside the `<main>` block of the layout
ul { ul {
(View::new_fragment( (View::new_fragment(
global_state.matches.get() state.matches.get()
.pool_matches .pool_matches
.iter() .iter()
.rev() .rev()
.enumerate() .enumerate()
.map(|(_index, item)| { .map(|(index, item)| {
let game = item.clone(); let game = item.clone();
view! { cx, view! { cx,
li { li {
(game.id) (game.winner)
} }
} }
}) })
@@ -38,9 +48,22 @@ fn overall_board_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, _state: &'a PageSta
#[engine_only_fn] #[engine_only_fn]
async fn get_request_state( async fn get_request_state(
_info: StateGeneratorInfo<()>, _info: StateGeneratorInfo<()>,
_req: Request, req: Request,
) -> Result<PageState, BlamedError<std::convert::Infallible>> { ) -> Result<PageState, BlamedError<std::convert::Infallible>> {
Ok(PageState {})
let matches = thread::spawn(move || {
let mut db = DATA.lock().unwrap();
db.matches.pool_matches.push(PoolMatch {
players: vec![],
winner: "lol".to_string(),
});
db.write();
db.matches.clone()
}).join().unwrap();
Ok(PageState {
matches
})
} }
#[engine_only_fn] #[engine_only_fn]
@@ -50,6 +73,9 @@ fn head(cx: Scope) -> View<SsrNode> {
} }
} }
// Template
pub fn get_template<G: Html>() -> Template<G> { pub fn get_template<G: Html>() -> Template<G> {
Template::build("overall-board") Template::build("overall-board")
.request_state_fn(get_request_state) .request_state_fn(get_request_state)