From d1ddb405c81251b3e554db1a21e531ad29be1837 Mon Sep 17 00:00:00 2001 From: Sebastian Moser Date: Sun, 17 May 2026 14:23:34 +0200 Subject: [PATCH] moved generated,spacetime into it's own package + many other things --- Cargo.lock | 89 ++++---- Cargo.toml | 3 +- flake.nix | 2 +- md | 90 +++++++- packages/ac_mize_macros/src/lib.rs | 12 ++ packages/generated/Cargo.toml | 11 + packages/generated/src/lib.rs | 2 + .../src/spacetime}/action_type.rs | 0 .../src/spacetime}/activities_table.rs | 0 .../src/spacetime}/activity_type.rs | 0 .../src/spacetime}/add_activity_reducer.rs | 0 .../src/spacetime}/log_event_type.rs | 0 .../src/spacetime}/log_events_table.rs | 0 .../src/spacetime}/mod.rs | 0 .../src/spacetime}/next_action_reducer.rs | 0 .../src/spacetime}/profile_type.rs | 0 .../src/spacetime}/profiles_table.rs | 0 .../src/spacetime}/remove_activity_reducer.rs | 0 .../spacetime}/set_activity_name_reducer.rs | 0 .../src/spacetime}/task_part_table.rs | 0 .../src/spacetime}/task_part_type.rs | 0 .../src/spacetime}/task_type.rs | 0 .../src/spacetime}/tasks_table.rs | 0 .../src/spacetime}/update_activity_reducer.rs | 0 .../src/spacetime}/update_upcoming_reducer.rs | 0 packages/marts/Cargo.toml | 14 +- packages/{ppc => marts}/auth/client.rs | 85 +++----- packages/marts/c2vi/mod.rs | 75 ++++++- packages/marts/cli/mod.rs | 4 +- packages/marts/habitica.rs | 3 +- packages/marts/lib.rs | 14 +- packages/{ppc => marts}/spacetime.rs | 6 +- packages/mize/src/core/config.rs | 30 --- packages/mize/src/core/error.rs | 2 +- packages/mize/src/core/instance/mod.rs | 90 ++++---- packages/mize/src/core/instance/module.rs | 60 ------ packages/mize/src/core/instance/tests.rs | 4 +- packages/mize/src/core/item.rs | 49 +++-- packages/mize/src/lib.rs | 22 +- packages/mize/src/platform/os/cli.rs | 17 +- packages/mize/src/platform/os/mod.rs | 195 +++++++++--------- packages/ppc/Cargo.toml | 16 +- packages/ppc/lib.rs | 76 ++++++- packages/ppc/platform/os/main.rs | 18 +- packages/ppc/platform/os/server.rs | 2 - packages/ppc/platform/os/ui/mod.rs | 53 +---- packages/ppc/timetrack/mod.rs | 56 +++-- .../{ppc/spacetimedb => spacetime}/Cargo.toml | 2 +- .../{ppc/spacetimedb => spacetime}/src/lib.rs | 7 +- 49 files changed, 610 insertions(+), 499 deletions(-) create mode 100644 packages/generated/Cargo.toml create mode 100644 packages/generated/src/lib.rs rename packages/{ppc/generated => generated/src/spacetime}/action_type.rs (100%) rename packages/{ppc/generated => generated/src/spacetime}/activities_table.rs (100%) rename packages/{ppc/generated => generated/src/spacetime}/activity_type.rs (100%) rename packages/{ppc/generated => generated/src/spacetime}/add_activity_reducer.rs (100%) rename packages/{ppc/generated => generated/src/spacetime}/log_event_type.rs (100%) rename packages/{ppc/generated => generated/src/spacetime}/log_events_table.rs (100%) rename packages/{ppc/generated => generated/src/spacetime}/mod.rs (100%) rename packages/{ppc/generated => generated/src/spacetime}/next_action_reducer.rs (100%) rename packages/{ppc/generated => generated/src/spacetime}/profile_type.rs (100%) rename packages/{ppc/generated => generated/src/spacetime}/profiles_table.rs (100%) rename packages/{ppc/generated => generated/src/spacetime}/remove_activity_reducer.rs (100%) rename packages/{ppc/generated => generated/src/spacetime}/set_activity_name_reducer.rs (100%) rename packages/{ppc/generated => generated/src/spacetime}/task_part_table.rs (100%) rename packages/{ppc/generated => generated/src/spacetime}/task_part_type.rs (100%) rename packages/{ppc/generated => generated/src/spacetime}/task_type.rs (100%) rename packages/{ppc/generated => generated/src/spacetime}/tasks_table.rs (100%) rename packages/{ppc/generated => generated/src/spacetime}/update_activity_reducer.rs (100%) rename packages/{ppc/generated => generated/src/spacetime}/update_upcoming_reducer.rs (100%) rename packages/{ppc => marts}/auth/client.rs (84%) rename packages/{ppc => marts}/spacetime.rs (83%) delete mode 100644 packages/mize/src/core/instance/module.rs rename packages/{ppc/spacetimedb => spacetime}/Cargo.toml (90%) rename packages/{ppc/spacetimedb => spacetime}/src/lib.rs (96%) diff --git a/Cargo.lock b/Cargo.lock index d4dc50f..3febf0f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -625,9 +625,9 @@ dependencies = [ [[package]] name = "bytestring" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "113b4343b5f6617e7ad401ced8de3cc8b012e73a594347c307b90db3e9271289" +checksum = "86566c496f2f47d9b8147a4c8b02ffdb69c919fe0c2b2e7195d22cbba0e635c9" dependencies = [ "bytes", "serde_core", @@ -2829,6 +2829,13 @@ dependencies = [ "x11", ] +[[package]] +name = "generated" +version = "0.1.0" +dependencies = [ + "spacetimedb-sdk", +] + [[package]] name = "generational-box" version = "0.5.6" @@ -4261,12 +4268,16 @@ dependencies = [ "dioxus", "flume 0.12.0", "futures", + "generated", "mize", + "openidconnect", "reqwest 0.13.2", "rusqlite", "serde", "serde_json", + "spacetimedb-sdk", "tokio", + "webbrowser", ] [[package]] @@ -4435,6 +4446,14 @@ dependencies = [ "wee_alloc", ] +[[package]] +name = "mize-spacetime" +version = "0.1.0" +dependencies = [ + "log", + "spacetimedb", +] + [[package]] name = "mize_macros" version = "0.1.0" @@ -5261,6 +5280,7 @@ dependencies = [ "dioxus-ssr 0.5.6", "dioxus-web", "flume 0.12.0", + "generated", "html-escape", "js-sys", "marts", @@ -5280,15 +5300,6 @@ dependencies = [ "url", "wasm-bindgen", "web-sys", - "webbrowser", -] - -[[package]] -name = "ppc-spacetime" -version = "0.1.0" -dependencies = [ - "log", - "spacetimedb", ] [[package]] @@ -6673,9 +6684,9 @@ dependencies = [ [[package]] name = "spacetimedb" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "591f9068644aab6808e7612a869dedde7eeb26df78027a19bc9dc597cc649678" +checksum = "1306cc3a9ed9c89f43b263614a529357cc53a067e3d06c1cbb485e3b577b118b" dependencies = [ "anyhow", "bytemuck", @@ -6696,9 +6707,9 @@ dependencies = [ [[package]] name = "spacetimedb-bindings-macro" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f68bf4810d838be622c13efd4cd64e0a9ce8cd340deaa730f0c92caee845f9" +checksum = "51567ec01cd323438a00c134c16f26ffcde5f9dbe6a42a52e54578285bf49d73" dependencies = [ "heck 0.4.1", "humantime", @@ -6710,18 +6721,18 @@ dependencies = [ [[package]] name = "spacetimedb-bindings-sys" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c2fe9f4124a599c9deae8f8231be3ae5a49bc5b2eef5e04c04b2632cf4cc0b4" +checksum = "3b40fa1bea26664085febe2b4455568c8b47dea2cb0245406b27e30963df2ba1" dependencies = [ "spacetimedb-primitives", ] [[package]] name = "spacetimedb-client-api-messages" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02a18c2e145f61ad498f8094a2231e09f8d39a3dde09defa716075dbcb8c7e85" +checksum = "dfc9eeb20a555bad07029cbee4efe3a305cb5c1e40e21a07cbbbbed16a106014" dependencies = [ "bytes", "bytestring", @@ -6741,9 +6752,9 @@ dependencies = [ [[package]] name = "spacetimedb-data-structures" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e4035c17ddbfc8c49a659bd6fb265b0a2a11115d1b4ad1963bccfad75cdfb4b" +checksum = "748fd5850a757823c5b8948065d9e4dc5092968a051aa3f34f170e91d95e493b" dependencies = [ "ahash", "crossbeam-queue", @@ -6756,9 +6767,9 @@ dependencies = [ [[package]] name = "spacetimedb-lib" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "672c0dd16feced67155a0dee7bd38d30f7725321c8177cb871a21c3d8749ae97" +checksum = "5612611d09d358f535438275d2a0d6a5e2fa56fa583dcfdbeddd623974df1d5e" dependencies = [ "anyhow", "bitflags 2.11.0", @@ -6780,9 +6791,9 @@ dependencies = [ [[package]] name = "spacetimedb-memory-usage" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c00614eb981354ee6b31661ec47002d3fc274f9d4543279dd6ee8692cdd8266" +checksum = "1c3a0d08fc5d8688a47e3ffcb803275519663b7ea1fba7ad25e608182de4ec6d" dependencies = [ "decorum", "ethnum", @@ -6790,9 +6801,9 @@ dependencies = [ [[package]] name = "spacetimedb-metrics" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef6f7f6b24932505a696b75b7e5e60646ab1d76eeb8d2f95f04948562c965b5e" +checksum = "ca2d647201339aa17ba438a07463e96ed64ba214fb0c182588e262b055efa7f3" dependencies = [ "arrayvec", "itertools 0.12.1", @@ -6802,9 +6813,9 @@ dependencies = [ [[package]] name = "spacetimedb-primitives" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dba5d7497d54aa8d4254f78a0bef12606bb05e62f8dea8b69abc9b241508e8b7" +checksum = "9b668b51e7318207ae7eebcd4cae0c5d43bf713e7f229ac309ea2614a486ffde" dependencies = [ "bitflags 2.11.0", "either", @@ -6816,18 +6827,18 @@ dependencies = [ [[package]] name = "spacetimedb-query-builder" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d04c6e41e05273f14405ac6f429477626677d46528b561a509b7b78b45128f30" +checksum = "0186b1a2b3bf25bdd0f2676b61801fd754013ca6a58e1e24cc5148945388bc9d" dependencies = [ "spacetimedb-lib", ] [[package]] name = "spacetimedb-sats" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfde33ec86d80881da8b00c42096bf0382bef8e1bc35e9b6faaa42d77cbf503c" +checksum = "11780ed69f178bf3784b7599da5171450e4b7ac6fd66b79e2e1861c867cef1a6" dependencies = [ "anyhow", "arrayvec", @@ -6858,9 +6869,9 @@ dependencies = [ [[package]] name = "spacetimedb-schema" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b03b34a38bd39f3f60a0687efafb942355bd9f6026b88a38c7c9ec904e944f1" +checksum = "1e4e9f8aa596e0e7034f0c8b3649d3fa3cc7bde340761519c3a3c60f10ec8888" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -6889,9 +6900,9 @@ dependencies = [ [[package]] name = "spacetimedb-sdk" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e7302851fec72929ffef976125f51971b0ec76be2730e27705a8e544f2ce159" +checksum = "41e82f20034b8aaeaa081871b07895aab45be1f0fc35e114ab64ae8e7e5c1a54" dependencies = [ "anymap3", "base64 0.21.7", @@ -6921,9 +6932,9 @@ dependencies = [ [[package]] name = "spacetimedb-sql-parser" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7cbb9a837ac5f1ddb0cfb745159dea276dcf456244452f5a90684e5184f1f31" +checksum = "ec5c77a2d4e3f42ede59598c56cb81a0fe54fd1974e2707f7140d1d5f41d08a7" dependencies = [ "derive_more 0.99.20", "spacetimedb-lib", diff --git a/Cargo.toml b/Cargo.toml index 0bfc2ba..9a5958b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,7 @@ members = [ "packages/marts", "packages/mize", "packages/ppc", - "packages/ppc/spacetimedb", + "packages/spacetime", + "packages/generated", ] resolver = "2" diff --git a/flake.nix b/flake.nix index e559440..cd01998 100644 --- a/flake.nix +++ b/flake.nix @@ -43,7 +43,7 @@ let }; -in rec { +in { ############################## PACKAGES ############################## packages = rec { diff --git a/md b/md index e3c7a80..b801083 100755 --- a/md +++ b/md @@ -5,12 +5,28 @@ MIZE_SRC="/home/me/work/mize" # hardcoded for now RSYNC_EXCLUDES="--exclude=node_modules --exclude=target --exclude=mize_config.toml --exclude=rust_dist --exclude=deno_dist --exclude=dist --exclude=result --exclude=pkg" function main { + if [[ "$1" == "gen" ]]; then + generate_sources + fi + + if [[ "$1" == "dsp" ]]; then + deploy_spacetime + fi + if [[ "$1" == "dlu" ]]; then deploy_lush fi if [[ "$1" == "dma" ]]; then - deploy_main_website + deploy_main + fi + + if [[ "$1" == "dmac" ]]; then + deploy_mac + fi + + if [[ "$1" == "dpw" ]]; then + deploy_ppc_website fi if [[ "$1" == "dmo" ]]; then @@ -18,6 +34,68 @@ function main { fi } +function deploy_spacetime { + spacetime publish -p $MIZE_SRC/packages/spacetime +} + +function generate_sources { + echo "mize: Generating sources..." + mkdir -p $MIZE_SRC/packages/generated/src/spacetime + + # Generate Cargo.toml and lib.rs +cat << 'EOF' > $MIZE_SRC/packages/generated/Cargo.toml +[package] +name = "generated" +version = "0.1.0" +edition = "2021" + +[lib] +name = "generated" +path = "src/lib.rs" + +[dependencies] +spacetimedb-sdk = "2.1.0" +EOF + echo -e 'pub mod spacetime;\n' > $MIZE_SRC/packages/generated/src/lib.rs + + # Generate spacetime client bindings + spacetime generate -p $MIZE_SRC/packages/spacetime -o $MIZE_SRC/packages/generated/src/spacetime --lang rust +} + +function deploy_main { + cargo build --manifest-path $MIZE_SRC/packages/mize/Cargo.toml --release + cargo build --manifest-path $MIZE_SRC/packages/ppc/Cargo.toml --release --features desktop + + cp $MIZE_SRC/target/release/mize ~/here/mize/ + cp $MIZE_SRC/target/release/libppc_part.so ~/here/mize/ + cp $MIZE_SRC/md ~/here/mize/ + cp $MIZE_SRC/target/release/ppc ~/here/mize/ + + systemctl --user restart mize +} + +function deploy_mac { + echo "c2vi: Deploying to mac..." + + # Copy files to mac + rsync -r -u -v -a --delete --include=".git/" --include=".git/**" --mkpath $RSYNC_EXCLUDES $MIZE_SRC mac:here + + # compile + ssh mac << EOF + if ! tmux has-session -t ppc-deploy 2>/dev/null; then + echo "Created new tmux session...." + tmux new-session -d -s ppc-deploy "nix develop git+file:///home/me/here/mize#buildShell" + tmux send-keys -t ppc-deploy "cargo build --manifest-path /home/me/here/mize/packages/mize/Cargo.toml" Enter + tmux send-keys -t ppc-deploy "cargo build --features desktop --manifest-path /home/me/here/mize/packages/ppc/Cargo.toml" Enter + tmux send-keys -t ppc-deploy "systemctl --user restart mize" Enter + else + echo "using existing session..." + tmux send-keys -t ppc-deploy "cargo build --manifest-path /home/me/here/mize/packages/mize/Cargo.toml" Enter + tmux send-keys -t ppc-deploy "cargo build --features desktop --manifest-path /home/me/here/mize/packages/ppc/Cargo.toml" Enter + tmux send-keys -t ppc-deploy "systemctl --user restart mize" Enter + fi +EOF +} function deploy_lush { echo "c2vi: Deploying to lush..." @@ -30,19 +108,21 @@ function deploy_lush { if ! tmux has-session -t ppc-deploy 2>/dev/null; then echo "Created new tmux session...." tmux new-session -d -s ppc-deploy "nix develop git+file:///home/me/here/mize#buildShell" - tmux send-keys -t ppc-deploy "cargo build --featuers desktop --manifest-path /home/me/here/mize/packages/mize/Cargo.toml" Enter + tmux send-keys -t ppc-deploy "cargo build --manifest-path /home/me/here/mize/packages/mize/Cargo.toml" Enter + tmux send-keys -t ppc-deploy "cargo build --features desktop --manifest-path /home/me/here/mize/packages/ppc/Cargo.toml" Enter tmux send-keys -t ppc-deploy "systemctl --user restart mize" Enter else echo "using existing session..." - tmux send-keys -t ppc-deploy "cargo build --features desktop --manifest-path /home/me/here/mize/packages/mize/Cargo.toml" Enter + tmux send-keys -t ppc-deploy "cargo build --manifest-path /home/me/here/mize/packages/mize/Cargo.toml" Enter + tmux send-keys -t ppc-deploy "cargo build --features desktop --manifest-path /home/me/here/mize/packages/ppc/Cargo.toml" Enter tmux send-keys -t ppc-deploy "systemctl --user restart mize" Enter fi EOF } -function deploy_main_website { - echo "c2vi: Deploying website to fes" +function deploy_ppc_website { + echo "c2vi: Deploying ppc website to fes" # compile cargo build --release --no-default-features --features server --manifest-path $MIZE_SRC/packages/ppc/Cargo.toml diff --git a/packages/ac_mize_macros/src/lib.rs b/packages/ac_mize_macros/src/lib.rs index 001c79f..72be2c5 100644 --- a/packages/ac_mize_macros/src/lib.rs +++ b/packages/ac_mize_macros/src/lib.rs @@ -33,6 +33,9 @@ pub fn mize_part(attr: TokenStream, item: TokenStream) -> TokenStream { .into(); } + let part_getter_fn_name_str = format!("get_mize_part_{}", part_name); + let part_getter_fn_name = syn::Ident::new(&part_getter_fn_name_str, struct_name.span()); + let expanded = quote! { #input @@ -64,6 +67,15 @@ pub fn mize_part(attr: TokenStream, item: TokenStream) -> TokenStream { } } + use mize::instance::MizePartCreateThisSucks; + + impl MizePartCreateThisSucks for #struct_name {} + + // the function to get the part from a .so file + extern "C" fn #part_getter_fn_name(part: &mut Box, mut mize: Mize) { + #struct_name::create_this_sucks(&mut mize); + } + /* impl std::ops::Deref for mize::MizePartGuard<#struct_name> { type Target = #struct_name; diff --git a/packages/generated/Cargo.toml b/packages/generated/Cargo.toml new file mode 100644 index 0000000..e333cfa --- /dev/null +++ b/packages/generated/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "generated" +version = "0.1.0" +edition = "2021" + +[lib] +name = "generated" +path = "src/lib.rs" + +[dependencies] +spacetimedb-sdk = "2.1.0" diff --git a/packages/generated/src/lib.rs b/packages/generated/src/lib.rs new file mode 100644 index 0000000..42efbb5 --- /dev/null +++ b/packages/generated/src/lib.rs @@ -0,0 +1,2 @@ +pub mod spacetime; + diff --git a/packages/ppc/generated/action_type.rs b/packages/generated/src/spacetime/action_type.rs similarity index 100% rename from packages/ppc/generated/action_type.rs rename to packages/generated/src/spacetime/action_type.rs diff --git a/packages/ppc/generated/activities_table.rs b/packages/generated/src/spacetime/activities_table.rs similarity index 100% rename from packages/ppc/generated/activities_table.rs rename to packages/generated/src/spacetime/activities_table.rs diff --git a/packages/ppc/generated/activity_type.rs b/packages/generated/src/spacetime/activity_type.rs similarity index 100% rename from packages/ppc/generated/activity_type.rs rename to packages/generated/src/spacetime/activity_type.rs diff --git a/packages/ppc/generated/add_activity_reducer.rs b/packages/generated/src/spacetime/add_activity_reducer.rs similarity index 100% rename from packages/ppc/generated/add_activity_reducer.rs rename to packages/generated/src/spacetime/add_activity_reducer.rs diff --git a/packages/ppc/generated/log_event_type.rs b/packages/generated/src/spacetime/log_event_type.rs similarity index 100% rename from packages/ppc/generated/log_event_type.rs rename to packages/generated/src/spacetime/log_event_type.rs diff --git a/packages/ppc/generated/log_events_table.rs b/packages/generated/src/spacetime/log_events_table.rs similarity index 100% rename from packages/ppc/generated/log_events_table.rs rename to packages/generated/src/spacetime/log_events_table.rs diff --git a/packages/ppc/generated/mod.rs b/packages/generated/src/spacetime/mod.rs similarity index 100% rename from packages/ppc/generated/mod.rs rename to packages/generated/src/spacetime/mod.rs diff --git a/packages/ppc/generated/next_action_reducer.rs b/packages/generated/src/spacetime/next_action_reducer.rs similarity index 100% rename from packages/ppc/generated/next_action_reducer.rs rename to packages/generated/src/spacetime/next_action_reducer.rs diff --git a/packages/ppc/generated/profile_type.rs b/packages/generated/src/spacetime/profile_type.rs similarity index 100% rename from packages/ppc/generated/profile_type.rs rename to packages/generated/src/spacetime/profile_type.rs diff --git a/packages/ppc/generated/profiles_table.rs b/packages/generated/src/spacetime/profiles_table.rs similarity index 100% rename from packages/ppc/generated/profiles_table.rs rename to packages/generated/src/spacetime/profiles_table.rs diff --git a/packages/ppc/generated/remove_activity_reducer.rs b/packages/generated/src/spacetime/remove_activity_reducer.rs similarity index 100% rename from packages/ppc/generated/remove_activity_reducer.rs rename to packages/generated/src/spacetime/remove_activity_reducer.rs diff --git a/packages/ppc/generated/set_activity_name_reducer.rs b/packages/generated/src/spacetime/set_activity_name_reducer.rs similarity index 100% rename from packages/ppc/generated/set_activity_name_reducer.rs rename to packages/generated/src/spacetime/set_activity_name_reducer.rs diff --git a/packages/ppc/generated/task_part_table.rs b/packages/generated/src/spacetime/task_part_table.rs similarity index 100% rename from packages/ppc/generated/task_part_table.rs rename to packages/generated/src/spacetime/task_part_table.rs diff --git a/packages/ppc/generated/task_part_type.rs b/packages/generated/src/spacetime/task_part_type.rs similarity index 100% rename from packages/ppc/generated/task_part_type.rs rename to packages/generated/src/spacetime/task_part_type.rs diff --git a/packages/ppc/generated/task_type.rs b/packages/generated/src/spacetime/task_type.rs similarity index 100% rename from packages/ppc/generated/task_type.rs rename to packages/generated/src/spacetime/task_type.rs diff --git a/packages/ppc/generated/tasks_table.rs b/packages/generated/src/spacetime/tasks_table.rs similarity index 100% rename from packages/ppc/generated/tasks_table.rs rename to packages/generated/src/spacetime/tasks_table.rs diff --git a/packages/ppc/generated/update_activity_reducer.rs b/packages/generated/src/spacetime/update_activity_reducer.rs similarity index 100% rename from packages/ppc/generated/update_activity_reducer.rs rename to packages/generated/src/spacetime/update_activity_reducer.rs diff --git a/packages/ppc/generated/update_upcoming_reducer.rs b/packages/generated/src/spacetime/update_upcoming_reducer.rs similarity index 100% rename from packages/ppc/generated/update_upcoming_reducer.rs rename to packages/generated/src/spacetime/update_upcoming_reducer.rs diff --git a/packages/marts/Cargo.toml b/packages/marts/Cargo.toml index 9a68aed..5443d43 100644 --- a/packages/marts/Cargo.toml +++ b/packages/marts/Cargo.toml @@ -19,13 +19,19 @@ serde = "1.0.228" serde_json = "1.0.149" rusqlite = { version = "0.31", features = ["bundled"], optional = true } dioxus = { version = "0.7.1", optional = true } +spacetimedb-sdk = "2.1.0" +generated = { path = "../generated/" } +webbrowser = { version = "1.2.0", optional = true } +openidconnect = { version = "4", features = ["reqwest", "rustls-tls"], optional = true } [features] -default = ["target-os", "desktop", "server"] -target-os = [ "clap", "mize/target-os", "rusqlite", "dioxus" ] -desktop = ["dioxus/desktop"] -server = [] +default = ["target-os", "desktop", "server", "client", "target-js",] +target-os = [ "clap", "mize/target-os", "rusqlite", "dioxus", "dep:webbrowser" ] target-js = [ "mize/target-js" ] +target-obsidian = [ "target-js" ] +desktop = ["dioxus/desktop"] +client = [ "dep:openidconnect" ] +server = [] clap = ["dep:clap"] [lib] diff --git a/packages/ppc/auth/client.rs b/packages/marts/auth/client.rs similarity index 84% rename from packages/ppc/auth/client.rs rename to packages/marts/auth/client.rs index 87484a0..42e7f93 100644 --- a/packages/ppc/auth/client.rs +++ b/packages/marts/auth/client.rs @@ -1,23 +1,13 @@ -use base64::{ - Engine, - alphabet::STANDARD, - engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig}, +use chrono::{DateTime, TimeDelta, Utc}; +use mize::{ + item::ItemData, mize_err, mize_part, Mize, MizeError, MizePart, MizePartCreate, MizeResult, }; -use chrono::{DateTime, Local, NaiveDateTime, TimeDelta, Utc}; -use dioxus::{fullstack::ClientResponse, html::ol}; -use mize::{Mize, MizeError, MizePart, MizeResult, item::ItemData, mize_err, mize_part}; use openidconnect::{ - AccessToken, AuthorizationCode, ClientId, CsrfToken, DeviceAuthorizationResponse, - EmptyExtraDeviceAuthorizationFields, IssuerUrl, Nonce, OAuth2TokenResponse, PkceCodeChallenge, - PkceCodeVerifier, RedirectUrl, RefreshToken, Scope, TokenResponse, - core::{CoreAuthenticationFlow, CoreClient, CoreProviderMetadata}, + ClientId, DeviceAuthorizationResponse, EmptyExtraDeviceAuthorizationFields, IssuerUrl, + OAuth2TokenResponse, RefreshToken, Scope, TokenResponse, }; use serde::{Deserialize, Serialize}; -use std::{ - io::{self, Write}, - path::PathBuf, - thread, -}; +use std::{path::PathBuf, thread}; // console_log macro // that can be copied into other files for debugging purposes @@ -56,6 +46,8 @@ pub struct ClientSecrets { expiry: DateTime, } +impl MizePartCreate for ClientAuth {} + impl MizePart for ClientAuth { fn name(&self) -> &'static str { "client_auth" @@ -97,20 +89,17 @@ impl ClientAuth { pub fn start_refresh_thread(&mut self) -> MizeResult<()> { let mut mize_clone = self.mize.clone(); - self.mize.spawn_background("auth.refresh", move || { - loop { - let auth = mize_clone.get_part_native::("auth")?; - let to_sleep = Utc::now() - - auth.secrets.as_ref().unwrap().expiry.clone() - - TimeDelta::minutes(20); - drop(auth); - println!("refresh_thread: going to sleep for: {}", to_sleep); - thread::sleep(to_sleep.to_std()?); - println!("refresh_thread: sleeping done"); - let mut auth = mize_clone.get_part_native::("auth")?; - auth.refresh()?; - drop(auth); - } + self.mize.spawn_background("auth.refresh", move || loop { + let auth = mize_clone.get_part_native::("auth")?; + let to_sleep = + Utc::now() - auth.secrets.as_ref().unwrap().expiry.clone() - TimeDelta::minutes(20); + drop(auth); + println!("refresh_thread: going to sleep for: {}", to_sleep); + thread::sleep(to_sleep.to_std()?); + println!("refresh_thread: sleeping done"); + let mut auth = mize_clone.get_part_native::("auth")?; + auth.refresh()?; + drop(auth); })?; Ok(()) } @@ -128,7 +117,7 @@ pub fn client_auth(mize: &mut Mize) -> MizeResult<()> { }; // do a refresh if the tokens have expired - if (secrets.is_some() && secrets.unwrap().expiry < Utc::now()) { + if secrets.is_some() && secrets.clone().unwrap().expiry < Utc::now() { secrets = Some( mize.spawn_async_blocking("refresh_low", refresh_flow(mize.clone(), secrets.unwrap()))?, ); @@ -136,7 +125,7 @@ pub fn client_auth(mize: &mut Mize) -> MizeResult<()> { #[cfg(feature = "target-os")] { - let mut cli = mize.get_part_native::("cli")?; + let mut cli = mize.get_part_native::("cli")?; cli.subcommand(Command::new("login"), |_, mut mize| { let mut auth = mize.get_part_native::("client_auth")?; println!("secrets: {:?}", auth.secrets); @@ -206,14 +195,8 @@ fn write_secrets(mize: &mut Mize, secrets: &ClientSecrets) -> MizeResult<()> { Ok(()) } -#[derive(Serialize, Deserialize)] -struct Combined<'a> { - code: &'a str, - state: &'a str, -} - -use openidconnect::DeviceAuthorizationUrl; use openidconnect::reqwest::Client as HttpClient; +use openidconnect::DeviceAuthorizationUrl; use std::time::Duration; async fn refresh_flow(mut mize: Mize, old_secrets: ClientSecrets) -> MizeResult { @@ -231,14 +214,14 @@ async fn refresh_flow(mut mize: Mize, old_secrets: ClientSecrets) -> MizeResult< struct MyExtraProviderMetadata { device_authorization_endpoint: String, } - use openidconnect::AdditionalProviderMetadata; - use openidconnect::ProviderMetadata; use openidconnect::core::{ CoreAuthDisplay, CoreClaimName, CoreClaimType, CoreClient, CoreClientAuthMethod, - CoreDeviceAuthorizationResponse, CoreGrantType, CoreJsonWebKey, CoreJsonWebKeyType, - CoreJsonWebKeyUse, CoreJweContentEncryptionAlgorithm, CoreJweKeyManagementAlgorithm, - CoreJwsSigningAlgorithm, CoreResponseMode, CoreResponseType, CoreSubjectIdentifierType, + CoreGrantType, CoreJsonWebKey, CoreJweContentEncryptionAlgorithm, + CoreJweKeyManagementAlgorithm, CoreResponseMode, CoreResponseType, + CoreSubjectIdentifierType, }; + use openidconnect::AdditionalProviderMetadata; + use openidconnect::ProviderMetadata; impl AdditionalProviderMetadata for MyExtraProviderMetadata {} type MyProviderMetadata = ProviderMetadata< MyExtraProviderMetadata, @@ -302,14 +285,14 @@ async fn auth_flow(mut mize: Mize) -> MizeResult { struct MyExtraProviderMetadata { device_authorization_endpoint: String, } - use openidconnect::AdditionalProviderMetadata; - use openidconnect::ProviderMetadata; use openidconnect::core::{ CoreAuthDisplay, CoreClaimName, CoreClaimType, CoreClient, CoreClientAuthMethod, - CoreDeviceAuthorizationResponse, CoreGrantType, CoreJsonWebKey, CoreJsonWebKeyType, - CoreJsonWebKeyUse, CoreJweContentEncryptionAlgorithm, CoreJweKeyManagementAlgorithm, - CoreJwsSigningAlgorithm, CoreResponseMode, CoreResponseType, CoreSubjectIdentifierType, + CoreGrantType, CoreJsonWebKey, CoreJweContentEncryptionAlgorithm, + CoreJweKeyManagementAlgorithm, CoreResponseMode, CoreResponseType, + CoreSubjectIdentifierType, }; + use openidconnect::AdditionalProviderMetadata; + use openidconnect::ProviderMetadata; impl AdditionalProviderMetadata for MyExtraProviderMetadata {} type MyProviderMetadata = ProviderMetadata< MyExtraProviderMetadata, @@ -372,7 +355,7 @@ async fn auth_flow(mut mize: Mize) -> MizeResult { #[cfg(feature = "target-os")] { - if let Some(uri_complete) = details.verification_uri_complete() { + if let Some(_) = details.verification_uri_complete() { let _ = webbrowser::open(details.verification_uri_complete().unwrap().secret()); } } @@ -382,7 +365,7 @@ async fn auth_flow(mut mize: Mize) -> MizeResult { .request_async( &http_client, async |dur: Duration| { - tokio::time::sleep(dur); + tokio::time::sleep(dur).await; }, None, ) diff --git a/packages/marts/c2vi/mod.rs b/packages/marts/c2vi/mod.rs index 6ffbfcf..1882855 100644 --- a/packages/marts/c2vi/mod.rs +++ b/packages/marts/c2vi/mod.rs @@ -5,10 +5,21 @@ use clap::{Arg, Command}; use rusqlite::{params, Connection}; use serde_json::{json, Value}; -use mize::{mize_err, mize_part, Mize, MizeError, MizePart, MizeResult}; +use dioxus::prelude::*; +use mize::{mize_err, mize_part, Mize, MizeError, MizePart, MizePartCreate, MizeResult}; use crate::cli::CliPart; use crate::habitica::Habitica; +use crate::SpacetimePart; +use generated::spacetime::{ + activitiesQueryTableAccess, next_action, remove_activity, task_partQueryTableAccess, + update_activity, update_upcoming, Action, ActivitiesTableAccess, Activity, DbConnection, + TaskPart, TaskPartTableAccess, +}; +use spacetimedb_sdk::{ + credentials, DbContext, Error, Event, Identity, Status, SubscriptionHandle, Table, + TableWithPrimaryKey, +}; mod dashboard; @@ -24,6 +35,7 @@ impl MizePart for C2vi { mize.new_opt("c2vi.local_storage_path"); } } +impl MizePartCreate for C2vi {} impl C2vi { fn with_db(&self, f: F) -> MizeResult @@ -42,12 +54,67 @@ impl C2vi { } pub fn c2vi(mize: &mut Mize) -> MizeResult<()> { - #[cfg(feature = "client")] - c2vi_client(mize)?; + #[cfg(feature = "desktop")] + if mize + .get_config("c2vi.dash.enable")? + .as_bool() + .unwrap_or(false) + { + // refresh the credentials every 23h + // as this is basically running as a daemon + use crate::auth::client::ClientAuth; + let mut auth = mize.get_part_native::("auth")?; + auth.refresh()?; + auth.start_refresh_thread()?; + drop(auth); + + launch_c2vi_dashboard(mize); + } Ok(()) } +#[cfg(feature = "desktop")] +pub fn launch_c2vi_dashboard(mize: &mut Mize) { + use dioxus::desktop::{muda::Menu, Config, WindowBuilder}; + let mize_clone = mize.clone(); + LaunchBuilder::new() + .with_context_provider(move || Box::new(mize_clone.clone())) + .with_cfg(desktop! { + Config::new().with_window(WindowBuilder::new().with_decorations(false).with_title("PPC")) + }) + .launch(c2vi_dash_main); +} + +pub fn c2vi_dash_main() -> Element { + let mut current = use_signal_sync(|| "".to_string()); + use_effect(move || { + let mut mize = use_context::(); + let mut spacetime = mize.get_part_native::("spacetime").unwrap(); + let con = spacetime.con(); + con.subscription_builder() + .on_applied(move |ctx| { + let data = ctx.db.task_part().identity().find(&ctx.identity()).unwrap(); + current.set(data.current.name.clone()); + }) + .add_query(|q| q.from.task_part()) + .subscribe(); + con.db + .task_part() + .on_update(move |_, old: &TaskPart, new: &TaskPart| { + current.set(new.current.name.clone()); + }); + }); + rsx! { + div { + style: "text-align: center; padding: 2rem; font-size: 50px;", + p { + "{current}" + } + } + } +} + pub fn c2vi_client(mize: &mut Mize) -> MizeResult<()> { //let storage_path = mize.get_config("c2vi.local_storage_path")?.as_ let storage_path = "/home/me/work/app-data/ppc"; @@ -97,7 +164,7 @@ fn setup_tables(conn: &Connection) -> MizeResult<()> { fn register_subcommands(cli: &mut CliPart) { cli.subcommand( Command::new("c2vi-dash").about("Run the c2vi dashboard gui"), - |_matches, mut mize| Ok(dioxus::launch(dashboard::main)), + |_matches, mut _mize| Ok(dioxus::launch(dashboard::main)), ); cli.subcommand( Command::new("bed").about("Command to run when c2vi goes to bed"), diff --git a/packages/marts/cli/mod.rs b/packages/marts/cli/mod.rs index d9ff528..4edcd36 100644 --- a/packages/marts/cli/mod.rs +++ b/packages/marts/cli/mod.rs @@ -1,7 +1,7 @@ use clap::{ArgMatches, Command}; use std::collections::HashMap; -use mize::{mize_part, Mize, MizePart, MizeResult}; +use mize::{mize_part, Mize, MizePart, MizePartCreate, MizeResult}; #[mize_part("cli")] #[derive(Default)] @@ -28,6 +28,8 @@ pub fn cli(mize: &mut Mize) -> MizeResult<()> { mize.add_part(Box::new(cli_part)) } +impl MizePartCreate for CliPart {} + impl MizePart for CliPart { fn init(&mut self, _mize: &mut Mize) -> MizeResult<()> { Ok(()) diff --git a/packages/marts/habitica.rs b/packages/marts/habitica.rs index 9a57aab..8701acc 100644 --- a/packages/marts/habitica.rs +++ b/packages/marts/habitica.rs @@ -1,5 +1,5 @@ use chrono::{DateTime, Utc}; -use mize::{mize_err, mize_part, Mize, MizeError, MizePart, MizeResult}; +use mize::{mize_err, mize_part, Mize, MizeError, MizePart, MizePartCreate, MizeResult}; use reqwest::{blocking::Client, blocking::Response, header, Method}; use serde_json::{json, Value}; use std::thread::sleep; @@ -20,6 +20,7 @@ pub fn habitica(mize: &mut Mize) -> MizeResult<()> { })) } +impl MizePartCreate for Habitica {} impl MizePart for Habitica { fn opts(&self, mize: &mut Mize) { mize.new_opt("habitica.api_url"); diff --git a/packages/marts/lib.rs b/packages/marts/lib.rs index cf7e1a2..85eec02 100644 --- a/packages/marts/lib.rs +++ b/packages/marts/lib.rs @@ -1,6 +1,3 @@ - -use mize::MizeResult; - #[cfg(feature = "target-os")] mod cli; #[cfg(feature = "target-os")] @@ -16,6 +13,17 @@ pub mod c2vi; #[cfg(feature = "target-os")] pub use c2vi::*; +#[cfg(feature = "target-os")] +pub mod spacetime; +#[cfg(feature = "target-os")] +pub use spacetime::*; + +pub mod auth { + pub mod client; + pub use client::*; +} +pub use auth::*; + //#[cfg(feature = "target-os")] //pub mod js; //#[cfg(feature = "target-os")] diff --git a/packages/ppc/spacetime.rs b/packages/marts/spacetime.rs similarity index 83% rename from packages/ppc/spacetime.rs rename to packages/marts/spacetime.rs index af38e39..c17cee3 100644 --- a/packages/ppc/spacetime.rs +++ b/packages/marts/spacetime.rs @@ -1,6 +1,7 @@ -use mize::{Mize, MizeError, MizePart, MizeResult, mize_part}; +use mize::{mize_part, Mize, MizePart, MizePartCreate, MizeResult}; -use crate::{auth::client::ClientAuth, generated::DbConnection}; +use crate::auth::client::ClientAuth; +use generated::spacetime::DbConnection; #[mize_part] #[derive(Default)] @@ -9,6 +10,7 @@ pub struct SpacetimePart { con: Option, } +impl MizePartCreate for SpacetimePart {} impl MizePart for SpacetimePart { fn name(&self) -> &'static str { "spacetime" diff --git a/packages/mize/src/core/config.rs b/packages/mize/src/core/config.rs index c51f35b..ec92373 100644 --- a/packages/mize/src/core/config.rs +++ b/packages/mize/src/core/config.rs @@ -45,35 +45,5 @@ pub fn gather_config(mize: &mut Mize) -> MizeResult<()> { part.as_deref().unwrap().opts(&mut mize.clone()); } - // populate values from config files - let config_file_paths = env::var("MIZE_CONFIG_FILES")?; - for config_file_path in config_file_paths.split(":") { - println!("reading config file: {config_file_path}"); - let content = std::fs::read_to_string(config_file_path)?; - let mut data = ItemData::from_toml(content.as_str())?; - for path in data.get_paths_recursive()? { - let mut conf_name = path.replace("/", "."); - if conf_name.starts_with(".") { - conf_name.remove(0); - } - let val = data.get_path(path.split("/").filter(|s| s != &"").collect::>())?; - match config_opts.get_mut(&conf_name) { - Some(opt) => { - opt.val = Some(val); - } - None => { - config_opts.insert( - conf_name.clone(), - ConfigOpt { - name: conf_name, - val: Some(val), - thunk: None, - }, - ); - } - }; - } - } - Ok(()) } diff --git a/packages/mize/src/core/error.rs b/packages/mize/src/core/error.rs index 3afea1f..543e6c2 100644 --- a/packages/mize/src/core/error.rs +++ b/packages/mize/src/core/error.rs @@ -125,7 +125,7 @@ impl MizeError { } pub fn log(self) -> MizeError { - error!("MizeError envountered!"); + error!("MizeError encountered!"); if let Some(ref location) = self.code_location { error!("[ {} ] {}", "LOCATION".yellow(), location); diff --git a/packages/mize/src/core/instance/mod.rs b/packages/mize/src/core/instance/mod.rs index ee158d8..a755318 100644 --- a/packages/mize/src/core/instance/mod.rs +++ b/packages/mize/src/core/instance/mod.rs @@ -25,8 +25,8 @@ use crate::instance::updater::Operation; use crate::instance::updater::{updater_thread, updater_thread_async}; use crate::item::{Item, ItemData}; use crate::memstore::MemStore; +use crate::mize_err; use crate::proto::MizeMessage; -use crate::{mize_err, Module}; use self::connection::{ConnListener, Connection}; use self::updater::handle_operation; @@ -40,7 +40,6 @@ use core::future::Future; use std::thread::JoinHandle; pub mod connection; -pub mod module; pub mod msg_thread; pub mod store; pub mod subscription; @@ -61,13 +60,12 @@ pub struct Mize { connections: Arc>>, next_con_id: Arc>, subs: Arc>>>, - pub(crate) modules: Arc>>>, pub(crate) id_pool: Arc>, pub(crate) namespace_pool: Arc>, pub(crate) parts: Arc>>>>, - - part_names: Arc>>, + //pub(crate) platform: Arc>>, // should we do that instead of all the #cfg(faturs=targt-smth) in lib.rs + part_names: Arc>>, // exists, so that we know the ordering in which parts were loaded pub(crate) config_opts: Arc>>, @@ -166,11 +164,40 @@ pub trait MizePartGenerated { } pub trait MizePartCreate: MizePartCreateGenerated + MizePart + 'static { - fn create(mize: &mut Mize) -> Box { - Box::new(Self::create_generated(mize.clone())) + fn create(mize: &mut Mize) -> MizeResult> { + Ok(Box::new(Self::create_generated(mize.clone()))) } } +pub trait MizePartCreateThisSucks: MizePartCreate + MizePart + 'static { + fn create_this_sucks(mize: &mut Mize) -> MizeResult> { + Self::create(mize) + } +} + +pub struct EmptyPart { + pub(crate) mize: Mize, +} +impl MizePartGenerated for EmptyPart { + fn name_generated(&self) -> &'static str { + "empty" + } + fn get_mize_generated(&mut self) -> &mut Mize { + &mut self.mize + } + fn as_any_generated(&self) -> &dyn Any { + self + } + fn as_any_mut_generated(&mut self) -> &mut dyn Any { + self + } + fn into_any_generated(self: Box) -> Box { + self + } +} + +impl MizePart for EmptyPart {} + #[async_trait] pub trait MizePart: MizePartGenerated { fn name(&self) -> &'static str { @@ -236,7 +263,6 @@ impl Mize { self_namespace, op_tx, namespace_pool: Arc::new(Mutex::new(namespace_pool_raw)), - modules: Arc::new(Mutex::new(HashMap::new())), threads: Arc::new(Mutex::new(Vec::new())), next_thread_id: Arc::new(Mutex::new(0)), next_con_id: Arc::new(Mutex::new(1)), @@ -337,7 +363,7 @@ impl Mize { } pub fn init(&mut self) -> MizeResult<()> { - // gather options + // gather config options from all parts gather_config(self)?; // platform specific init code @@ -345,21 +371,19 @@ impl Mize { // end of platform specific init code - // load the modules, ad specified in the load_modules config - match self.get("0/config/load_modules")?.value_string() { - Ok(modules_to_load) => { - for module in modules_to_load.split(" ") { - #[cfg(feature = "target-wasm ")] - console_log!("loading module in Instance::init() ... {}", module); - self.load_module(module)?; + // load the modules, as specified in the parts config + match self.get_config("parts")?.value_string() { + Ok(parts_to_load) => { + for part_name in parts_to_load.split(" ") { + self.load_part(part_name)?; } } Err(err) => { - // no load_modules option is set + // no parts to load } } - debug!("INSTANCE INIT DONE"); + debug!("MIZE INIT DONE"); Ok(()) } @@ -515,29 +539,25 @@ impl Mize { Ok(id) } - pub fn load_module(&mut self, name: &str) -> MizeResult<()> { - crate::platform::any::load_module(self, name, None) + pub fn load_part(&mut self, name: &str) -> MizeResult<()> { + if let Ok(path) = self + .get_config(&format!("part_dir.{}", name))? + .value_string() + { + crate::platform::any::load_part(self, name, Some(path)) + } else { + crate::platform::any::load_part(self, name, None) + } } - pub fn fetch_module(&mut self, name: &str) -> MizeResult { + pub fn fetch_part(&mut self, name: &str) -> MizeResult { // platform specific way to fetch a module - crate::platform::any::fetch_module(self, name) + crate::platform::any::fetch_part(self, name) } - pub fn load_module_at(&mut self, name: &str, path: String) -> MizeResult<()> { + pub fn load_part_at(&mut self, name: &str, path: String) -> MizeResult<()> { // platform specific init code - crate::platform::any::load_module(self, name, Some(path)) - } - - pub fn get_module(&mut self, name: &str) -> MizeResult> { - let inner = self.modules.lock()?; - - let module = inner - .get(name) - .ok_or(mize_err!("Couldn't get_module('{name}')"))? - .clone_module(); - - Ok(module) + crate::platform::any::load_part(self, name, Some(path)) } pub fn namespace_from_string(&self, ns_str: String) -> MizeResult { diff --git a/packages/mize/src/core/instance/module.rs b/packages/mize/src/core/instance/module.rs deleted file mode 100644 index e90a74a..0000000 --- a/packages/mize/src/core/instance/module.rs +++ /dev/null @@ -1,60 +0,0 @@ -// https://users.rust-lang.org/t/casting-between-trait-object-types/97220/2 - -use std::ffi::OsString; - -use crate::error::MizeResult; -use crate::instance::Mize; - -pub trait Module { - fn init(&mut self, instance: &Mize) -> MizeResult<()>; - - fn exit(&mut self, instance: &Mize) -> MizeResult<()>; - - fn clone_module(&self) -> Box; - - // extra traits, that can be implemented - // return None if not implemented - - fn run_cli(&mut self, instance: &Mize, cmd_line: Vec) -> Option> { - None - } -} - -// console_log macro -// that can be copied into other files for debugging purposes -#[cfg(feature = "target-wasm ")] -use wasm_bindgen::prelude::*; - -#[cfg(feature = "target-wasm ")] -#[wasm_bindgen] -extern "C" { - #[wasm_bindgen(js_namespace = console)] - fn log(s: &str); -} - -#[cfg(feature = "wasm-target")] -macro_rules! console_log { - // Note that this is using the `log` function imported above during - // `bare_bones` - ($($t:tt)*) => (unsafe { log(&format_args!($($t)*).to_string())}) -} - -pub struct EmptyModule {} - -impl Module for EmptyModule { - fn init(&mut self, instance: &Mize) -> MizeResult<()> { - println!("empty module fn init"); - - #[cfg(feature = "wasm-target")] - console_log!("empty module fn init"); - Ok(()) - } - fn exit(&mut self, instance: &Mize) -> MizeResult<()> { - println!("empty module fn exit"); - Ok(()) - } - - fn clone_module(&self) -> Box { - Box::new(EmptyModule {}) - } -} diff --git a/packages/mize/src/core/instance/tests.rs b/packages/mize/src/core/instance/tests.rs index e1e4214..eb58952 100644 --- a/packages/mize/src/core/instance/tests.rs +++ b/packages/mize/src/core/instance/tests.rs @@ -43,7 +43,7 @@ fn test_sort_keys() -> MizeResult<()> { fn test_get_module_hash() -> MizeResult<()> { let mut instance = Mize::empty()?; - use crate::platform::os::get_module_hash; + use crate::platform::os::get_part_hash; let selector_toml = r#" mize_version = "0.0.0" system = "x86_64-unknown-linux-gnu" @@ -52,7 +52,7 @@ fn test_get_module_hash() -> MizeResult<()> { instance.set_blocking("0/config/selector", ItemData::from_toml(&selector_toml)?)?; - let (hash, selector) = get_module_hash(&mut instance, "String", ItemData::new())?; + let (hash, selector) = get_part_hash(&mut instance, "String", ItemData::new())?; test_println!("hash: {}", hash); test_println!("selector: {}", selector); diff --git a/packages/mize/src/core/item.rs b/packages/mize/src/core/item.rs index c12fbf6..86f2697 100644 --- a/packages/mize/src/core/item.rs +++ b/packages/mize/src/core/item.rs @@ -225,6 +225,12 @@ impl ItemData { _ => Err(mize_err!("this ItemData has no string value")), } } + pub fn as_bool(self) -> Option { + match self.cbor() { + CborValue::Bool(val) => Some(*val), + _ => None, + } + } pub fn from_string>(into_string: S) -> ItemData { let string = into_string.into(); @@ -594,28 +600,31 @@ pub fn get_raw_from_cbor<'a>(value: &'a CborValue, path: Vec<&String>) -> MizeRe trace!("[ {} ] path: {:?}", "ARG".yellow(), path); let mut path_iter = path.clone().into_iter(); - let path_el = match path_iter.nth(0) { - Some(val) => val, - None => { - // our base case - let ret_val = match value { - CborValue::Bytes(vec) => { - trace!("[ {} ] ret value: {:?}", "RET".yellow(), &vec[..]); - return Ok(&vec[..]); - } - CborValue::Text(string) => { - trace!("[ {} ] ret value: {:?}", "RET".yellow(), string.as_bytes()); - return Ok(string.as_bytes()); - } - other => { - return Err(mize_err!( - "path is empty and the value: '{:?}' is neither Bytes nor Text", + let path_el = + match path_iter.nth(0) { + Some(val) => val, + None => { + // our base case + let ret_val = + match value { + CborValue::Bytes(vec) => { + trace!("[ {} ] ret value: {:?}", "RET".yellow(), &vec[..]); + return Ok(&vec[..]); + } + CborValue::Text(string) => { + trace!("[ {} ] ret value: {:?}", "RET".yellow(), string.as_bytes()); + return Ok(string.as_bytes()); + } + other => { + return Err(mize_err!( + "path '{}' is empty and the value: '{:?}' is neither Bytes nor Text", + path.iter().map(|p| p.as_str()).collect::>().join("."), other )); - } - }; - } - }; + } + }; + } + }; match value { CborValue::Bytes(vec) => { diff --git a/packages/mize/src/lib.rs b/packages/mize/src/lib.rs index f26c1c6..b2f7cf0 100644 --- a/packages/mize/src/lib.rs +++ b/packages/mize/src/lib.rs @@ -45,7 +45,6 @@ mod core { pub use async_trait::async_trait; pub use core::error::MizeError; pub use core::error::MizeResult; -pub use core::instance::module::Module; pub use core::instance::Mize; pub use core::instance::{ DynMizePartGuard, MizePart, MizePartCreate, MizePartCreateGenerated, MizePartGenerated, @@ -74,33 +73,34 @@ pub mod platform { #[cfg(not(any(feature = "target-os", feature = "target-js")))] pub use super::super::instance_init; - //////////// load_module + //////////// load_part #[cfg(feature = "target-os")] - pub use super::os::load_module; + pub use super::os::load_part; #[cfg(feature = "target-js")] - pub use super::js::load_module; + pub use super::js::load_part; #[cfg(not(any(feature = "target-os", feature = "target-js")))] - pub use super::super::load_module; + pub use super::super::load_part; - //////////// fetch_module + //////////// fetch_part #[cfg(feature = "target-os")] - pub use super::os::fetch_module; + pub use super::os::fetch_part; #[cfg(feature = "target-js")] - pub use super::super::fetch_module; + pub use super::super::fetch_part; #[cfg(not(any(feature = "target-os", feature = "target-js")))] - pub use super::super::fetch_module; + pub use super::super::fetch_part; } } +// platform specific functions pub fn instance_init(instance: &mut core::instance::Mize) -> MizeResult<()> { Ok(()) } -pub fn load_module( +pub fn load_part( instance: &mut core::instance::Mize, name: &str, path: Option, @@ -108,6 +108,6 @@ pub fn load_module( Ok(()) } -pub fn fetch_module(instance: &mut core::instance::Mize, name: &str) -> MizeResult { +pub fn fetch_part(instance: &mut core::instance::Mize, name: &str) -> MizeResult { Ok("oh noooooooooooooo, something went really really wrong, if this ends up in the executable....".to_owned()) } diff --git a/packages/mize/src/platform/os/cli.rs b/packages/mize/src/platform/os/cli.rs index 66b1782..f3483cb 100644 --- a/packages/mize/src/platform/os/cli.rs +++ b/packages/mize/src/platform/os/cli.rs @@ -120,7 +120,7 @@ pub fn stop(sub_matches: &ArgMatches) -> MizeResult<()> { pub fn gui(sub_matches: &ArgMatches) -> MizeResult<()> { let mut instance = Mize::with_config(config_from_cli_args(sub_matches)?)?; - instance.load_module("mme")?; + instance.load_part("mme")?; instance.wait(); @@ -153,14 +153,15 @@ pub fn run_from_module(cmd: &str, sub_matches: &ArgMatches) -> MizeResult<()> { let mut instance = Mize::with_config(config_from_cli_args(sub_matches)?)?; debug!("loading module '{}'", cmd); - instance.load_module(cmd)?; + instance.load_part(cmd)?; - instance - .get_module(cmd)? - .run_cli(&instance, sub_cmd_line) - .ok_or(mize_err!( - "The Module '{cmd}' does not implement the run_cli() functionality" - ))??; + println!("running cli from part not implemented"); + //instance + //.get_part(cmd)? + //.run_cli(&instance, sub_cmd_line) + //.ok_or(mize_err!( + //"The Part '{cmd}' does not implement the run_cli() functionality" + //))??; Ok(()) } diff --git a/packages/mize/src/platform/os/mod.rs b/packages/mize/src/platform/os/mod.rs index 37f85c8..bfd54df 100644 --- a/packages/mize/src/platform/os/mod.rs +++ b/packages/mize/src/platform/os/mod.rs @@ -12,14 +12,15 @@ use std::time::UNIX_EPOCH; use tar::Archive; use tracing::{debug, error, info, trace, warn}; +use crate::config::ConfigOpt; use crate::error::{IntoMizeResult, MizeError, MizeResult}; use crate::id::MizeId; -use crate::instance::module::EmptyModule; use crate::instance::store::Store; +use crate::instance::EmptyPart; use crate::instance::Mize; use crate::item::{data_from_string, IntoItemData, ItemData}; use crate::memstore::MemStore; -use crate::{mize_err, Module}; +use crate::{mize_err, MizePart}; use self::fsstore::FileStore; @@ -33,40 +34,23 @@ mod unix_socket; use crate::platform::os::unix_socket::UnixListener; //mod web; -pub fn os_instance_init(instance: &mut Mize) -> MizeResult<()> { +pub fn os_instance_init(mize: &mut Mize) -> MizeResult<()> { // this is the code, that runs to initialize an Instance on a system with an os present. - ////// load MIZE_CONFIG_FILE as the instance, which is item 0 - match std::env::var("MIZE_CONFIG_FILE") { - Ok(config_file_path) => { - let config = config_from_file(config_file_path)?; - debug!("env var MIZE_CONFIG_FILE present"); - instance.set_blocking("0", config)?; - trace!( - "config after MIZE_CONFIG_FILE env var: {}", - instance.get("self/config")? - ); - } - Err(var_err) => match var_err { - VarError::NotPresent => { - debug!("env var MIZE_CONFIG_FILE NOT present"); - } - VarError::NotUnicode(_) => { - warn!("env var MIZE_CONFIG_FILE is not Unicode, so not reading it") - } - }, - }; + ////// populate values from $MIZE_CONFIG_FILES + let config_file_paths = std::env::var("MIZE_CONFIG_FILES")?; + for config_file_path in config_file_paths.split(":") { + println!("reading config file: {config_file_path}"); + let content = std::fs::read_to_string(config_file_path)?; + let mut data = ItemData::from_toml(content.as_str())?; + set_config_from_data(mize, data)?; + } ////// load config from MIZE_CONFIG env var match std::env::var("MIZE_CONFIG") { Ok(config_string) => { - let config = data_from_string(config_string)?; - debug!("env var MIZE_CONFIG present"); - instance.set_blocking("self/config", config)?; - trace!( - "config after MIZE_CONFIG env var: {}", - instance.get("self/config")? - ); + let data = data_from_string(config_string)?; + set_config_from_data(mize, data)?; } Err(var_err) => match var_err { VarError::NotPresent => { @@ -79,8 +63,8 @@ pub fn os_instance_init(instance: &mut Mize) -> MizeResult<()> { }; ////// if a config.store_path is set, upgrade to the filestore there - let mut test = instance.get("0")?.as_data_full()?; - let mut store_path = match instance.get("self/config/store_path")?.value_string() { + let mut test = mize.get("0")?.as_data_full()?; + let mut store_path = match mize.get("self/config/store_path")?.value_string() { Ok(path) => path, Err(e) => { // the default store_path: $HOME/.mize @@ -95,12 +79,12 @@ pub fn os_instance_init(instance: &mut Mize) -> MizeResult<()> { let store_path_buff = home_dir.join(".mize"); let store_path = store_path_buff.display().to_string(); - instance.set_blocking( + mize.set_blocking( "self/config/store_path", store_path.clone().into_item_data(), )?; - let store_path = instance.get("self/config/store_path")?.value_string()?; + let store_path = mize.get("self/config/store_path")?.value_string()?; println!("store_path: {}", store_path); @@ -108,7 +92,7 @@ pub fn os_instance_init(instance: &mut Mize) -> MizeResult<()> { } }; - if FileStore::store_is_opened(store_path.to_owned(), instance)? { + if FileStore::store_is_opened(store_path.to_owned(), mize)? { // if the store is already opened, connect to the instance, that opened it and join // it's namespace @@ -116,7 +100,7 @@ pub fn os_instance_init(instance: &mut Mize) -> MizeResult<()> { { info!("CONNECTING"); use crate::platform::os::unix_socket; - unix_socket::connect(instance, store_path.into())?; + unix_socket::connect(mize, store_path.into())?; return Ok(()); } @@ -127,13 +111,13 @@ pub fn os_instance_init(instance: &mut Mize) -> MizeResult<()> { } else { // else open it ourselves let file_store = FileStore::new(store_path.as_str())?; - instance.migrate_to_store(Box::new(file_store))?; + mize.migrate_to_store(Box::new(file_store))?; let path = Path::new(&store_path).to_owned(); #[cfg(target_family = "unix")] { - instance.add_listener(UnixListener::new(path)?)?; + mize.add_listener(UnixListener::new(path)?)?; } #[cfg(target_family = "windows")] @@ -144,6 +128,32 @@ pub fn os_instance_init(instance: &mut Mize) -> MizeResult<()> { Ok(()) } +fn set_config_from_data(mize: &mut Mize, mut data: ItemData) -> MizeResult<()> { + let mut config_opts = mize.config_opts.lock().unwrap(); + for path in data.get_paths_recursive()? { + let mut conf_name = path.replace("/", "."); + if conf_name.starts_with(".") { + conf_name.remove(0); + } + let val = data.get_path(path.split("/").filter(|s| s != &"").collect::>())?; + match config_opts.get_mut(&conf_name) { + Some(opt) => { + opt.val = Some(val); + } + None => { + config_opts.insert( + conf_name.clone(), + ConfigOpt { + name: conf_name, + val: Some(val), + thunk: None, + }, + ); + } + }; + } + Ok(()) +} pub fn seconds_since_modification(path: &Path) -> MizeResult { let metadata = fs::metadata(path)?; @@ -155,12 +165,12 @@ pub fn seconds_since_modification(path: &Path) -> MizeResult { Ok(duration.as_secs()) } -pub fn get_module_hash( - instance: &mut Mize, +pub fn get_part_hash( + mize: &mut Mize, name: &str, mut options: ItemData, ) -> MizeResult<(String, String)> { - let mut selector_data = instance.get("self/config/selector")?.as_data_full()?; + let mut selector_data = mize.get("self/config/selector")?.as_data_full()?; // handle the case, when we want a module for not the system we are running on... println!("get_module_hash: name: {}", name); @@ -209,28 +219,25 @@ pub fn get_module_hash( return Ok((hex, selector_str)); } -fn download_module( - instance: &mut Mize, +fn download_part( + mize: &mut Mize, store_path: &str, - module_url: &str, - module_hash: &str, - module_name: &str, - module_selector: &str, + part_url: &str, + part_hash: &str, + part_name: &str, + part_selector: &str, ) -> MizeResult<()> { - let tmp_file_path_gz = format!("{}/{}.tar.gz", store_path, module_hash); + let tmp_file_path_gz = format!("{}/{}.tar.gz", store_path, part_hash); let tmp_gz_file = if !PathBuf::from(tmp_file_path_gz.clone()).exists() { let mut tmp_gz_file = File::create(&tmp_file_path_gz)?; - debug!( - "downloading module '{}' with hash: {}", - module_name, module_hash - ); + debug!("downloading part '{}' with hash: {}", part_name, part_hash); let response = http_req::request::get( format!( "http://{}/mize/dist/{}-{}.tar.gz", - module_url, module_hash, module_name + part_url, part_hash, part_name ), &mut tmp_gz_file, )?; @@ -238,13 +245,13 @@ fn download_module( let code = response.status_code(); if code != 200.into() { return Err(mize_err!( - "failed to get module '{}' with hash '{}' and selector: {}", - module_name, - module_hash, - module_selector + "failed to get part '{}' with hash '{}' and selector: {}", + part_name, + part_hash, + part_selector ) .msg(format!( - "the http request to fetch the module returned a status code of: {}", + "the http request to fetch the part returned a status code of: {}", code ))); } @@ -259,7 +266,7 @@ fn download_module( //archive.set_mask(umask::Mode::parse("rwxrwxrwx")?.into()); - let target_dir = format!("{}/modules/{}", store_path, module_hash); + let target_dir = format!("{}/parts/{}", store_path, part_hash); std::fs::create_dir_all(target_dir.as_str())?; @@ -270,72 +277,66 @@ fn download_module( Ok(()) } -pub fn fetch_module(instance: &mut Mize, module_name: &str) -> MizeResult { - let module_name_with_slashes = module_name.replace(".", "/"); - if let Ok(module_path) = instance - .get(format!( - "self/config/module_dir/{}", - module_name_with_slashes - ))? +pub fn fetch_part(mize: &mut Mize, part_name: &str) -> MizeResult { + let part_name_with_slashes = part_name.replace(".", "/"); + if let Ok(part_path) = mize + .get(format!("self/config/part_dir/{}", part_name_with_slashes))? .value_string() { - // in case a dir is configured, which holds the modules output - return Ok(module_path); + // in case a dir is configured, which holds the parts output + return Ok(part_path); } else { // if null, load it from the url - let module_url = instance.get("self/config/module_url")?.value_string()?; + let part_url = mize.get("self/config/part_url")?.value_string()?; - let store_path = instance.get("self/config/store_path")?.value_string()?; + let store_path = mize.get("self/config/store_path")?.value_string()?; - let (module_hash, module_selector) = - get_module_hash(instance, module_name, ItemData::new())?; + let (part_hash, part_selector) = get_part_hash(mize, part_name, ItemData::new())?; - if !PathBuf::from(format!("{}/modules/{}", store_path, module_hash.as_str())).exists() { - // download module if it does not exist - download_module( - instance, + if !PathBuf::from(format!("{}/parts/{}", store_path, part_hash.as_str())).exists() { + // download part if it does not exist + download_part( + mize, store_path.as_str(), - module_url.as_str(), - module_hash.as_str(), - module_name, - module_selector.as_str(), + part_url.as_str(), + part_hash.as_str(), + part_name, + part_selector.as_str(), )?; } - return Ok(format!("{}/modules/{}", store_path, module_hash.as_str())); + return Ok(format!("{}/parts/{}", store_path, part_hash.as_str())); } } -pub fn load_module(instance: &mut Mize, module_name: &str, path: Option) -> MizeResult<()> { - let module_path = if path.is_some() { - format!("{}/lib/libmize_module_{}.so", path.unwrap(), module_name) +pub fn load_part(mize: &mut Mize, part_name: &str, path: Option) -> MizeResult<()> { + let part_path = if path.is_some() { + format!("{}/lib/lib{}_part.so", path.unwrap(), part_name) } else { format!( - "{}/lib/libmize_module_{}.so", - fetch_module(instance, module_name)?, - module_name + "{}/lib/lib{}_part.so", + fetch_part(mize, part_name)?, + part_name ) }; - let lib = unsafe { libloading::Library::new(module_path)? }; + let lib = unsafe { libloading::Library::new(part_path)? }; let func: libloading::Symbol< - unsafe extern "C" fn(&mut Box, Mize) -> (), - > = unsafe { lib.get(format!("get_mize_module_{}", module_name).as_bytes())? }; + unsafe extern "C" fn(&mut Box, Mize) -> (), + > = unsafe { lib.get(format!("make_mize_part_{}", part_name).as_bytes())? }; - let mut module: Box = Box::new(EmptyModule {}); + let mut part: Box = Box::new(EmptyPart { mize: mize.clone() }); - unsafe { func(&mut module, instance.clone()) }; + unsafe { func(&mut part, mize.clone()) }; - let mut modules_inner = instance.modules.lock()?; + part.init(mize)?; - module.init(&instance)?; - - modules_inner.insert(module_name.to_owned(), module); + mize.add_part(part)?; unsafe { // dropping the lib, would (i suspect) free all memory, of the library's code, which would - // make the module's vtable point into empty memory + // make the part's vtable point into empty memory std::mem::forget(lib); } diff --git a/packages/ppc/Cargo.toml b/packages/ppc/Cargo.toml index 0bd59d4..f3dbb8a 100644 --- a/packages/ppc/Cargo.toml +++ b/packages/ppc/Cargo.toml @@ -9,11 +9,11 @@ marts = { path = "../marts/", default-features = false } clap = { version = "4.5.59", optional = true } js-sys = { version = "0.3.85", optional = true } wasm-bindgen = { version = "0.2.108", optional = true } +generated = { path = "../../packages/generated" } # server deps axum = { version = "0.8.0", optional = true } axum-extra = { version = "0.10.3", features = ["cookie-private"], optional = true } -openidconnect = { version = "4", features = ["reqwest", "rustls-tls"], optional = true } serde = { version = "1.0", features = ["derive"], optional = true } serde_json = { version = "1.0", optional = true } reqwest = { version = "0.11", features = ["rustls-tls"], optional = true } @@ -29,11 +29,11 @@ tracing = { version = "0.1.44", optional = true } tower = { version = "0.5", optional = true } tower-sessions = { version = "0.14.0", optional = true } tower-http = { version = "0.6.8", features = ["trace"] } -webbrowser = { version = "1.2.0", optional = true } base64 = { version = "0.22.1", optional = true } dioxus-web = { version = "0.7.3", optional = true } web-sys = { version = "0.3.91", optional = true } spacetimedb-sdk = "2.1.0" +openidconnect = { version = "4", features = ["reqwest", "rustls-tls"], optional = true } flume = "0.12.0" chrono = "0.4.44" @@ -48,12 +48,12 @@ name = "ppc" [features] default = ["target-os", "server", "client" ] -target-os = [ "clap", "mize/target-os", "marts/target-os", "tracing", "webbrowser", "base64", "serde_json", "serde" ] -target-obsidian = [ "js-sys", "wasm-bindgen", "mize/target-js", "marts/target-js", "base64", "serde_json", "serde", "openidconnect", "dioxus", "dioxus-web", "web-sys", "web-sys/Document", "dioxus/web" ] -server = [ "axum", "axum-extra", "openidconnect", "serde", "serde_json", "reqwest", "rand", "url", "time", "tokio", "dioxus/ssr", "dioxus/server", "dioxus/fullstack", "dioxus/router", "dioxus-ssr", "html-escape", "axum-oidc", "tower", "tower-sessions", "marts/server", "target-os" ] -desktop = ["dioxus/desktop", "marts/desktop", "target-os"] -client = [ "tokio", "openidconnect" ] -webbrowser = ["dep:webbrowser"] +target-os = [ "marts/target-os", "clap", "mize/target-os", "marts/target-os", "tracing", "base64", "serde_json", "serde" ] +target-obsidian = [ "marts/target-obsidian", "js-sys", "wasm-bindgen", "mize/target-js", "marts/target-js", "base64", "serde_json", "serde", "dioxus", "dioxus-web", "web-sys", "web-sys/Document", "dioxus/web" ] +server = [ "marts/server", "axum", "axum-extra", "serde", "serde_json", "reqwest", "rand", "url", "time", "tokio", "dioxus/ssr", "dioxus/server", "dioxus/fullstack", "dioxus/router", "dioxus-ssr", "html-escape", "axum-oidc", "tower", "tower-sessions", "marts/server", "target-os", "openidconnect" ] +desktop = [ "marts/desktop", "dioxus/desktop", "target-os"] +client = [ "marts/client", "tokio" ] +website = [] [package.metadata.wasm-pack.profile.release] diff --git a/packages/ppc/lib.rs b/packages/ppc/lib.rs index 398ce99..ccfc63a 100644 --- a/packages/ppc/lib.rs +++ b/packages/ppc/lib.rs @@ -1,5 +1,9 @@ #![feature(oneshot_channel)] +use clap::Command; +use clap::crate_version; +use mize::{Mize, MizePart, MizeResult, mize_part}; + mod platform { #[cfg(feature = "target-obsidian")] pub mod obsidian; @@ -17,6 +21,7 @@ mod platform { #[cfg(feature = "website")] mod website; +use mize::MizePartCreate; #[cfg(feature = "target-os")] #[cfg(feature = "server")] pub use platform::os::server::server; @@ -24,14 +29,67 @@ pub use platform::os::server::server; #[cfg(feature = "desktop")] pub use platform::os::ui; -pub mod auth { - pub mod client; -} -pub use auth::client::client_auth; - -pub mod spacetime; pub mod timetrack; -// the generated source -// right now only from spacetimedb -mod generated; +#[mize_part("ppc")] +#[derive(Default)] +pub struct PPCPart { + mize: Mize, +} + +impl MizePart for PPCPart {} + +impl MizePartCreate for PPCPart { + fn create(mize: &mut mize::Mize) -> MizeResult> { + println!("ppc part loaded..."); + use marts::spacetime::spacetime; + + marts::cli(mize)?; + + #[cfg(feature = "client")] + { + use crate::timetrack::timetrack; + + marts::client_auth(mize)?; + if let Err(err) = spacetime(mize) { + println!("spacetime part failed to initialize: {:?}", err); + }; + timetrack(mize)?; + } + + // TODO move out of ppc and into it's own part + marts::c2vi(mize)?; + + #[cfg(feature = "server")] + crate::server(mize)?; + + let mut cli = mize.get_part_native::("cli")?; + + #[cfg(feature = "client")] + #[cfg(feature = "desktop")] + { + cli.subcommand(Command::new("gui"), |_, _| { + crate::ui::launch_desktop_app(); + Ok(()) + }); + } + + cli.with_cmd(|_, cmd| { + Ok(cmd + .version(crate_version!()) + .name("ppc") + .author("ppc") + .about("the ppc app")) + })?; + + cli.subcommand(Command::new("test"), |_, _| { + println!("test ppc..."); + Ok(()) + }); + + drop(cli); + Ok(Box::new(PPCPart { + mize: mize.to_owned(), + })) + } +} diff --git a/packages/ppc/platform/os/main.rs b/packages/ppc/platform/os/main.rs index f9b4854..da41270 100644 --- a/packages/ppc/platform/os/main.rs +++ b/packages/ppc/platform/os/main.rs @@ -1,5 +1,3 @@ -use std::collections::HashMap; - use clap::Command; use clap::crate_version; use mize::{Mize, MizeResult}; @@ -17,7 +15,7 @@ fn main() { #[cfg(feature = "target-os")] fn os_main(mize: &mut Mize) -> MizeResult<()> { - use ppc::spacetime::spacetime; + use marts::spacetime::spacetime; marts::cli(mize)?; //marts::js(mize)?; @@ -26,7 +24,7 @@ fn os_main(mize: &mut Mize) -> MizeResult<()> { { use ppc::timetrack::timetrack; - ppc::client_auth(mize)?; + marts::client_auth(mize)?; if let Err(err) = spacetime(mize) { println!("spacetime part failed to initialize: {:?}", err); }; @@ -48,18 +46,6 @@ fn os_main(mize: &mut Mize) -> MizeResult<()> { ppc::ui::launch_desktop_app(); Ok(()) }); - cli.subcommand(Command::new("c2vi-dash"), |_, mut mize| { - // refresh the credentials every 23h - // as this is basically running as a daemon - use ppc::auth::client::ClientAuth; - let mut auth = mize.get_part_native::("auth")?; - auth.refresh()?; - auth.start_refresh_thread()?; - drop(auth); - - ppc::ui::launch_c2vi_dashboard(&mut mize); - Ok(()) - }); } cli.with_cmd(|_, cmd| { diff --git a/packages/ppc/platform/os/server.rs b/packages/ppc/platform/os/server.rs index adf048c..c4d07a8 100644 --- a/packages/ppc/platform/os/server.rs +++ b/packages/ppc/platform/os/server.rs @@ -1,6 +1,5 @@ use axum::{Json, http::StatusCode}; use serde_json::{Value, json}; -use std::net::SocketAddr; use std::str::FromStr; use axum::{ @@ -57,7 +56,6 @@ pub fn server(mize: &mut Mize) -> MizeResult<()> { pub async fn start_server(mize: &mut Mize) -> MizeResult<()> { dioxus::logger::initialize_default(); - let issuer = mize.get_config("auth.issuer")?.value_string()?; let listen_addr = mize.get_config("server.listen_addr")?.value_string()?; let port = mize.get_config("server.port")?.value_string()?; let issuer = mize.get_config("auth.issuer")?.value_string()?; diff --git a/packages/ppc/platform/os/ui/mod.rs b/packages/ppc/platform/os/ui/mod.rs index 6e192e4..77066da 100644 --- a/packages/ppc/platform/os/ui/mod.rs +++ b/packages/ppc/platform/os/ui/mod.rs @@ -1,14 +1,12 @@ use dioxus::prelude::*; use mize::Mize; -use crate::{ - generated::{ - Action, ActivitiesTableAccess, Activity, DbConnection, TaskPart, TaskPartTableAccess, - activitiesQueryTableAccess, next_action, remove_activity, task_partQueryTableAccess, - update_activity, update_upcoming, - }, - spacetime::SpacetimePart, +use generated::spacetime::{ + Action, ActivitiesTableAccess, Activity, DbConnection, TaskPart, TaskPartTableAccess, + activitiesQueryTableAccess, next_action, remove_activity, task_partQueryTableAccess, + update_activity, update_upcoming, }; +use marts::spacetime::SpacetimePart; use spacetimedb_sdk::{ DbContext, Error, Event, Identity, Status, SubscriptionHandle, Table, TableWithPrimaryKey, credentials, @@ -25,51 +23,10 @@ pub fn hello_world() -> Element { } } -pub fn c2vi_dash_main() -> Element { - let mut current = use_signal_sync(|| "".to_string()); - use_effect(move || { - let mut mize = use_context::(); - let mut spacetime = mize.get_part_native::("spacetime").unwrap(); - let con = spacetime.con(); - con.subscription_builder() - .on_applied(move |ctx| { - let data = ctx.db.task_part().identity().find(&ctx.identity()).unwrap(); - current.set(data.current.name.clone()); - }) - .add_query(|q| q.from.task_part()) - .subscribe(); - con.db - .task_part() - .on_update(move |_, old: &TaskPart, new: &TaskPart| { - current.set(new.current.name.clone()); - }); - }); - rsx! { - div { - style: "text-align: center; padding: 2rem; font-size: 50px;", - p { - "{current}" - } - } - } -} - pub fn launch_desktop_app() { dioxus::launch(hello_world); } -#[cfg(feature = "desktop")] -pub fn launch_c2vi_dashboard(mize: &mut Mize) { - use dioxus::desktop::{Config, WindowBuilder, muda::Menu}; - let mize_clone = mize.clone(); - LaunchBuilder::new() - .with_context_provider(move || Box::new(mize_clone.clone())) - .with_cfg(desktop! { - Config::new().with_window(WindowBuilder::new().with_decorations(false).with_title("PPC")) - }) - .launch(c2vi_dash_main); -} - use dioxus::prelude::*; /* diff --git a/packages/ppc/timetrack/mod.rs b/packages/ppc/timetrack/mod.rs index 6c92ead..9221bed 100644 --- a/packages/ppc/timetrack/mod.rs +++ b/packages/ppc/timetrack/mod.rs @@ -1,27 +1,15 @@ -use std::{io::Read, sync::oneshot, thread, time::Duration}; +use std::sync::oneshot; use clap::{Arg, ArgAction, ArgMatches, Command}; -use mize::{Mize, MizeError, MizePart, MizePartGuard, MizeResult, mize_err, mize_part}; -use spacetimedb_sdk::{ - DbContext, Error, Event, Identity, Status, SubscriptionHandle, Table, TableWithPrimaryKey, - credentials, -}; +use mize::{Mize, MizeError, MizePart, MizePartCreate, MizeResult, mize_err, mize_part}; +use spacetimedb_sdk::{DbContext, Table}; -use crate::{ - generated::{ - Action, ActivitiesTableAccess, Activity, DbConnection, TaskPartTableAccess, - activitiesQueryTableAccess, next_action, remove_activity, task_partQueryTableAccess, - update_activity, update_upcoming, - }, - spacetime::SpacetimePart, -}; - -const MizeConfig = mconf!{ - hi "t" - rustBinary "hello" '' - println!("hello world"); - '' +use generated::spacetime::{ + Action, ActivitiesTableAccess, Activity, DbConnection, TaskPartTableAccess, + activitiesQueryTableAccess, next_action, remove_activity, task_partQueryTableAccess, + update_activity, update_upcoming, }; +use marts::spacetime::SpacetimePart; #[mize_part] #[derive(Default)] @@ -58,10 +46,12 @@ pub fn timetrack(mize: &mut Mize) -> MizeResult<()> { command_edit_activities, ); - mize.register_part(Box::new(TimeTrack { mize: mize.clone() })); + mize.register_part(Box::new(TimeTrack { mize: mize.clone() }))?; Ok(()) } +impl MizePartCreate for TimeTrack {} + impl MizePart for TimeTrack { fn name(&self) -> &'static str { "timetrack" @@ -87,7 +77,7 @@ fn command_current_action(_: &ArgMatches, mut mize: Mize) -> MizeResult<()> { Ok(()) } -fn get_current_action(mize: &mut Mize, con: &DbConnection) -> MizeResult { +fn get_current_action(_mize: &mut Mize, con: &DbConnection) -> MizeResult { let (wait_tx, wait_rx) = std::sync::oneshot::channel::(); con.subscription_builder() .on_applied(|ctx| { @@ -159,7 +149,7 @@ fn command_edit_action_list(matches: &ArgMatches, mut mize: Mize) -> MizeResult< let mut actions = get_actions(spacetime.con())?; // write to tmp file - let mut tmp_file_content = actions_to_string(&actions)?; + let tmp_file_content = actions_to_string(&actions)?; let tmp_file = std::env::temp_dir().join(format!( "ppc-edit-actions-{}.txt", chrono::Utc::now().timestamp() @@ -177,7 +167,7 @@ fn command_edit_action_list(matches: &ArgMatches, mut mize: Mize) -> MizeResult< let new_file_content = std::fs::read_to_string(&tmp_file) .map_err(|e| mize_err!("Failed to read temp file: {}", e))?; - actions = actions_from_string(actions, new_file_content)?; + actions = actions_from_string(new_file_content)?; set_actions(actions, spacetime.con())?; // delete tmpfile @@ -224,7 +214,7 @@ fn actions_to_string(actions: &Vec) -> MizeResult { Ok(string) } -fn actions_from_string(mut old_actions: Vec, string: String) -> MizeResult> { +fn actions_from_string(string: String) -> MizeResult> { let mut new_actions = Vec::new(); for line in string.lines() { if line.trim().is_empty() { @@ -246,7 +236,7 @@ fn actions_from_string(mut old_actions: Vec, string: String) -> MizeResu } fn parse_action(action: &mut Action) { - let parts: Vec<&str> = action.name.split_whitespace().collect(); + let _parts: Vec<&str> = action.name.split_whitespace().collect(); } fn command_edit_activities(_: &ArgMatches, mut mize: Mize) -> MizeResult<()> { @@ -311,7 +301,7 @@ fn command_edit_activities(_: &ArgMatches, mut mize: Mize) -> MizeResult<()> { Ok(()) } -fn get_activities(mize: &mut Mize, con: &mut DbConnection) -> MizeResult> { +fn get_activities(_mize: &mut Mize, con: &mut DbConnection) -> MizeResult> { let (exit_tx, exit_rx) = std::sync::oneshot::channel::>(); con.subscription_builder() .on_applied(|ctx| { @@ -360,7 +350,7 @@ fn parse_activities_from_text( parents_ids: old_activity.parents_ids.clone(), }, move |_, _| { - wait_tx.send(()); + let _ = wait_tx.send(()); }, )?; } else { @@ -372,7 +362,7 @@ fn parse_activities_from_text( parents_ids: Vec::new(), }, move |_, _| { - wait_tx.send(()); + let _ = wait_tx.send(()); }, )?; } @@ -383,7 +373,7 @@ fn parse_activities_from_text( let (wait_tx, wait_rx) = oneshot::channel::<()>(); wait_revievers.push(wait_rx); con.reducers.remove_activity_then(activity, move |_, _| { - wait_tx.send(()); + let _ = wait_tx.send(()); })?; } @@ -403,7 +393,7 @@ fn parse_activities_from_text( // split let mut parts = line.split(" "); - let id: u64 = parts.next().ok_or(mize_err!(".."))?.parse()?; + let _id: u64 = parts.next().ok_or(mize_err!(".."))?.parse()?; let name = parts.next().ok_or(mize_err!(".."))?.to_string(); // parse parents @@ -431,9 +421,9 @@ fn parse_activities_from_text( ..child_activity.to_owned() }, move |_, _| { - wait_tx.send(()); + let _ = wait_tx.send(()); }, - ); + )?; } } diff --git a/packages/ppc/spacetimedb/Cargo.toml b/packages/spacetime/Cargo.toml similarity index 90% rename from packages/ppc/spacetimedb/Cargo.toml rename to packages/spacetime/Cargo.toml index b653f8c..78fdb96 100644 --- a/packages/ppc/spacetimedb/Cargo.toml +++ b/packages/spacetime/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "ppc-spacetime" +name = "mize-spacetime" version = "0.1.0" edition = "2021" diff --git a/packages/ppc/spacetimedb/src/lib.rs b/packages/spacetime/src/lib.rs similarity index 96% rename from packages/ppc/spacetimedb/src/lib.rs rename to packages/spacetime/src/lib.rs index f8302a8..3992160 100644 --- a/packages/ppc/spacetimedb/src/lib.rs +++ b/packages/spacetime/src/lib.rs @@ -1,10 +1,5 @@ -use std::task; - use log::*; -use spacetimedb::{ - reducer, table, view, Deserialize, Identity, ReducerContext, Serialize, SpacetimeType, Table, - Timestamp, ViewContext, -}; +use spacetimedb::{reducer, table, Identity, ReducerContext, Table, Timestamp}; #[table(accessor = profiles, public)] pub struct Profile {