moved generated,spacetime into it's own package + many other things

This commit is contained in:
Sebastian Moser
2026-05-17 14:23:34 +02:00
parent 2907d7e236
commit d1ddb405c8
49 changed files with 610 additions and 499 deletions

89
Cargo.lock generated
View File

@@ -625,9 +625,9 @@ dependencies = [
[[package]] [[package]]
name = "bytestring" name = "bytestring"
version = "1.5.0" version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "113b4343b5f6617e7ad401ced8de3cc8b012e73a594347c307b90db3e9271289" checksum = "86566c496f2f47d9b8147a4c8b02ffdb69c919fe0c2b2e7195d22cbba0e635c9"
dependencies = [ dependencies = [
"bytes", "bytes",
"serde_core", "serde_core",
@@ -2829,6 +2829,13 @@ dependencies = [
"x11", "x11",
] ]
[[package]]
name = "generated"
version = "0.1.0"
dependencies = [
"spacetimedb-sdk",
]
[[package]] [[package]]
name = "generational-box" name = "generational-box"
version = "0.5.6" version = "0.5.6"
@@ -4261,12 +4268,16 @@ dependencies = [
"dioxus", "dioxus",
"flume 0.12.0", "flume 0.12.0",
"futures", "futures",
"generated",
"mize", "mize",
"openidconnect",
"reqwest 0.13.2", "reqwest 0.13.2",
"rusqlite", "rusqlite",
"serde", "serde",
"serde_json", "serde_json",
"spacetimedb-sdk",
"tokio", "tokio",
"webbrowser",
] ]
[[package]] [[package]]
@@ -4435,6 +4446,14 @@ dependencies = [
"wee_alloc", "wee_alloc",
] ]
[[package]]
name = "mize-spacetime"
version = "0.1.0"
dependencies = [
"log",
"spacetimedb",
]
[[package]] [[package]]
name = "mize_macros" name = "mize_macros"
version = "0.1.0" version = "0.1.0"
@@ -5261,6 +5280,7 @@ dependencies = [
"dioxus-ssr 0.5.6", "dioxus-ssr 0.5.6",
"dioxus-web", "dioxus-web",
"flume 0.12.0", "flume 0.12.0",
"generated",
"html-escape", "html-escape",
"js-sys", "js-sys",
"marts", "marts",
@@ -5280,15 +5300,6 @@ dependencies = [
"url", "url",
"wasm-bindgen", "wasm-bindgen",
"web-sys", "web-sys",
"webbrowser",
]
[[package]]
name = "ppc-spacetime"
version = "0.1.0"
dependencies = [
"log",
"spacetimedb",
] ]
[[package]] [[package]]
@@ -6673,9 +6684,9 @@ dependencies = [
[[package]] [[package]]
name = "spacetimedb" name = "spacetimedb"
version = "2.1.0" version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "591f9068644aab6808e7612a869dedde7eeb26df78027a19bc9dc597cc649678" checksum = "1306cc3a9ed9c89f43b263614a529357cc53a067e3d06c1cbb485e3b577b118b"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bytemuck", "bytemuck",
@@ -6696,9 +6707,9 @@ dependencies = [
[[package]] [[package]]
name = "spacetimedb-bindings-macro" name = "spacetimedb-bindings-macro"
version = "2.1.0" version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72f68bf4810d838be622c13efd4cd64e0a9ce8cd340deaa730f0c92caee845f9" checksum = "51567ec01cd323438a00c134c16f26ffcde5f9dbe6a42a52e54578285bf49d73"
dependencies = [ dependencies = [
"heck 0.4.1", "heck 0.4.1",
"humantime", "humantime",
@@ -6710,18 +6721,18 @@ dependencies = [
[[package]] [[package]]
name = "spacetimedb-bindings-sys" name = "spacetimedb-bindings-sys"
version = "2.1.0" version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c2fe9f4124a599c9deae8f8231be3ae5a49bc5b2eef5e04c04b2632cf4cc0b4" checksum = "3b40fa1bea26664085febe2b4455568c8b47dea2cb0245406b27e30963df2ba1"
dependencies = [ dependencies = [
"spacetimedb-primitives", "spacetimedb-primitives",
] ]
[[package]] [[package]]
name = "spacetimedb-client-api-messages" name = "spacetimedb-client-api-messages"
version = "2.1.0" version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02a18c2e145f61ad498f8094a2231e09f8d39a3dde09defa716075dbcb8c7e85" checksum = "dfc9eeb20a555bad07029cbee4efe3a305cb5c1e40e21a07cbbbbed16a106014"
dependencies = [ dependencies = [
"bytes", "bytes",
"bytestring", "bytestring",
@@ -6741,9 +6752,9 @@ dependencies = [
[[package]] [[package]]
name = "spacetimedb-data-structures" name = "spacetimedb-data-structures"
version = "2.1.0" version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e4035c17ddbfc8c49a659bd6fb265b0a2a11115d1b4ad1963bccfad75cdfb4b" checksum = "748fd5850a757823c5b8948065d9e4dc5092968a051aa3f34f170e91d95e493b"
dependencies = [ dependencies = [
"ahash", "ahash",
"crossbeam-queue", "crossbeam-queue",
@@ -6756,9 +6767,9 @@ dependencies = [
[[package]] [[package]]
name = "spacetimedb-lib" name = "spacetimedb-lib"
version = "2.1.0" version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "672c0dd16feced67155a0dee7bd38d30f7725321c8177cb871a21c3d8749ae97" checksum = "5612611d09d358f535438275d2a0d6a5e2fa56fa583dcfdbeddd623974df1d5e"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bitflags 2.11.0", "bitflags 2.11.0",
@@ -6780,9 +6791,9 @@ dependencies = [
[[package]] [[package]]
name = "spacetimedb-memory-usage" name = "spacetimedb-memory-usage"
version = "2.1.0" version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c00614eb981354ee6b31661ec47002d3fc274f9d4543279dd6ee8692cdd8266" checksum = "1c3a0d08fc5d8688a47e3ffcb803275519663b7ea1fba7ad25e608182de4ec6d"
dependencies = [ dependencies = [
"decorum", "decorum",
"ethnum", "ethnum",
@@ -6790,9 +6801,9 @@ dependencies = [
[[package]] [[package]]
name = "spacetimedb-metrics" name = "spacetimedb-metrics"
version = "2.1.0" version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef6f7f6b24932505a696b75b7e5e60646ab1d76eeb8d2f95f04948562c965b5e" checksum = "ca2d647201339aa17ba438a07463e96ed64ba214fb0c182588e262b055efa7f3"
dependencies = [ dependencies = [
"arrayvec", "arrayvec",
"itertools 0.12.1", "itertools 0.12.1",
@@ -6802,9 +6813,9 @@ dependencies = [
[[package]] [[package]]
name = "spacetimedb-primitives" name = "spacetimedb-primitives"
version = "2.1.0" version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dba5d7497d54aa8d4254f78a0bef12606bb05e62f8dea8b69abc9b241508e8b7" checksum = "9b668b51e7318207ae7eebcd4cae0c5d43bf713e7f229ac309ea2614a486ffde"
dependencies = [ dependencies = [
"bitflags 2.11.0", "bitflags 2.11.0",
"either", "either",
@@ -6816,18 +6827,18 @@ dependencies = [
[[package]] [[package]]
name = "spacetimedb-query-builder" name = "spacetimedb-query-builder"
version = "2.1.0" version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d04c6e41e05273f14405ac6f429477626677d46528b561a509b7b78b45128f30" checksum = "0186b1a2b3bf25bdd0f2676b61801fd754013ca6a58e1e24cc5148945388bc9d"
dependencies = [ dependencies = [
"spacetimedb-lib", "spacetimedb-lib",
] ]
[[package]] [[package]]
name = "spacetimedb-sats" name = "spacetimedb-sats"
version = "2.1.0" version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfde33ec86d80881da8b00c42096bf0382bef8e1bc35e9b6faaa42d77cbf503c" checksum = "11780ed69f178bf3784b7599da5171450e4b7ac6fd66b79e2e1861c867cef1a6"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"arrayvec", "arrayvec",
@@ -6858,9 +6869,9 @@ dependencies = [
[[package]] [[package]]
name = "spacetimedb-schema" name = "spacetimedb-schema"
version = "2.1.0" version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b03b34a38bd39f3f60a0687efafb942355bd9f6026b88a38c7c9ec904e944f1" checksum = "1e4e9f8aa596e0e7034f0c8b3649d3fa3cc7bde340761519c3a3c60f10ec8888"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"convert_case 0.6.0", "convert_case 0.6.0",
@@ -6889,9 +6900,9 @@ dependencies = [
[[package]] [[package]]
name = "spacetimedb-sdk" name = "spacetimedb-sdk"
version = "2.1.0" version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e7302851fec72929ffef976125f51971b0ec76be2730e27705a8e544f2ce159" checksum = "41e82f20034b8aaeaa081871b07895aab45be1f0fc35e114ab64ae8e7e5c1a54"
dependencies = [ dependencies = [
"anymap3", "anymap3",
"base64 0.21.7", "base64 0.21.7",
@@ -6921,9 +6932,9 @@ dependencies = [
[[package]] [[package]]
name = "spacetimedb-sql-parser" name = "spacetimedb-sql-parser"
version = "2.1.0" version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7cbb9a837ac5f1ddb0cfb745159dea276dcf456244452f5a90684e5184f1f31" checksum = "ec5c77a2d4e3f42ede59598c56cb81a0fe54fd1974e2707f7140d1d5f41d08a7"
dependencies = [ dependencies = [
"derive_more 0.99.20", "derive_more 0.99.20",
"spacetimedb-lib", "spacetimedb-lib",

View File

@@ -4,6 +4,7 @@ members = [
"packages/marts", "packages/marts",
"packages/mize", "packages/mize",
"packages/ppc", "packages/ppc",
"packages/ppc/spacetimedb", "packages/spacetime",
"packages/generated",
] ]
resolver = "2" resolver = "2"

View File

@@ -43,7 +43,7 @@ let
}; };
in rec { in {
############################## PACKAGES ############################## ############################## PACKAGES ##############################
packages = rec { packages = rec {

90
md
View File

@@ -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" 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 { function main {
if [[ "$1" == "gen" ]]; then
generate_sources
fi
if [[ "$1" == "dsp" ]]; then
deploy_spacetime
fi
if [[ "$1" == "dlu" ]]; then if [[ "$1" == "dlu" ]]; then
deploy_lush deploy_lush
fi fi
if [[ "$1" == "dma" ]]; then 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 fi
if [[ "$1" == "dmo" ]]; then if [[ "$1" == "dmo" ]]; then
@@ -18,6 +34,68 @@ function main {
fi 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 { function deploy_lush {
echo "c2vi: Deploying to lush..." echo "c2vi: Deploying to lush..."
@@ -30,19 +108,21 @@ function deploy_lush {
if ! tmux has-session -t ppc-deploy 2>/dev/null; then if ! tmux has-session -t ppc-deploy 2>/dev/null; then
echo "Created new tmux session...." echo "Created new tmux session...."
tmux new-session -d -s ppc-deploy "nix develop git+file:///home/me/here/mize#buildShell" 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 tmux send-keys -t ppc-deploy "systemctl --user restart mize" Enter
else else
echo "using existing session..." 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 tmux send-keys -t ppc-deploy "systemctl --user restart mize" Enter
fi fi
EOF EOF
} }
function deploy_main_website { function deploy_ppc_website {
echo "c2vi: Deploying website to fes" echo "c2vi: Deploying ppc website to fes"
# compile # compile
cargo build --release --no-default-features --features server --manifest-path $MIZE_SRC/packages/ppc/Cargo.toml cargo build --release --no-default-features --features server --manifest-path $MIZE_SRC/packages/ppc/Cargo.toml

View File

@@ -33,6 +33,9 @@ pub fn mize_part(attr: TokenStream, item: TokenStream) -> TokenStream {
.into(); .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! { let expanded = quote! {
#input #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<dyn MizePart + Send + Sync>, mut mize: Mize) {
#struct_name::create_this_sucks(&mut mize);
}
/* /*
impl std::ops::Deref for mize::MizePartGuard<#struct_name> { impl std::ops::Deref for mize::MizePartGuard<#struct_name> {
type Target = #struct_name; type Target = #struct_name;

View File

@@ -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"

View File

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

View File

@@ -19,13 +19,19 @@ serde = "1.0.228"
serde_json = "1.0.149" serde_json = "1.0.149"
rusqlite = { version = "0.31", features = ["bundled"], optional = true } rusqlite = { version = "0.31", features = ["bundled"], optional = true }
dioxus = { version = "0.7.1", 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] [features]
default = ["target-os", "desktop", "server"] default = ["target-os", "desktop", "server", "client", "target-js",]
target-os = [ "clap", "mize/target-os", "rusqlite", "dioxus" ] target-os = [ "clap", "mize/target-os", "rusqlite", "dioxus", "dep:webbrowser" ]
desktop = ["dioxus/desktop"]
server = []
target-js = [ "mize/target-js" ] target-js = [ "mize/target-js" ]
target-obsidian = [ "target-js" ]
desktop = ["dioxus/desktop"]
client = [ "dep:openidconnect" ]
server = []
clap = ["dep:clap"] clap = ["dep:clap"]
[lib] [lib]

View File

@@ -1,23 +1,13 @@
use base64::{ use chrono::{DateTime, TimeDelta, Utc};
Engine, use mize::{
alphabet::STANDARD, item::ItemData, mize_err, mize_part, Mize, MizeError, MizePart, MizePartCreate, MizeResult,
engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig},
}; };
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::{ use openidconnect::{
AccessToken, AuthorizationCode, ClientId, CsrfToken, DeviceAuthorizationResponse, ClientId, DeviceAuthorizationResponse, EmptyExtraDeviceAuthorizationFields, IssuerUrl,
EmptyExtraDeviceAuthorizationFields, IssuerUrl, Nonce, OAuth2TokenResponse, PkceCodeChallenge, OAuth2TokenResponse, RefreshToken, Scope, TokenResponse,
PkceCodeVerifier, RedirectUrl, RefreshToken, Scope, TokenResponse,
core::{CoreAuthenticationFlow, CoreClient, CoreProviderMetadata},
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{ use std::{path::PathBuf, thread};
io::{self, Write},
path::PathBuf,
thread,
};
// console_log macro // console_log macro
// that can be copied into other files for debugging purposes // that can be copied into other files for debugging purposes
@@ -56,6 +46,8 @@ pub struct ClientSecrets {
expiry: DateTime<Utc>, expiry: DateTime<Utc>,
} }
impl MizePartCreate for ClientAuth {}
impl MizePart for ClientAuth { impl MizePart for ClientAuth {
fn name(&self) -> &'static str { fn name(&self) -> &'static str {
"client_auth" "client_auth"
@@ -97,20 +89,17 @@ impl ClientAuth {
pub fn start_refresh_thread(&mut self) -> MizeResult<()> { pub fn start_refresh_thread(&mut self) -> MizeResult<()> {
let mut mize_clone = self.mize.clone(); let mut mize_clone = self.mize.clone();
self.mize.spawn_background("auth.refresh", move || { self.mize.spawn_background("auth.refresh", move || loop {
loop { let auth = mize_clone.get_part_native::<ClientAuth>("auth")?;
let auth = mize_clone.get_part_native::<ClientAuth>("auth")?; let to_sleep =
let to_sleep = Utc::now() Utc::now() - auth.secrets.as_ref().unwrap().expiry.clone() - TimeDelta::minutes(20);
- auth.secrets.as_ref().unwrap().expiry.clone() drop(auth);
- TimeDelta::minutes(20); println!("refresh_thread: going to sleep for: {}", to_sleep);
drop(auth); thread::sleep(to_sleep.to_std()?);
println!("refresh_thread: going to sleep for: {}", to_sleep); println!("refresh_thread: sleeping done");
thread::sleep(to_sleep.to_std()?); let mut auth = mize_clone.get_part_native::<ClientAuth>("auth")?;
println!("refresh_thread: sleeping done"); auth.refresh()?;
let mut auth = mize_clone.get_part_native::<ClientAuth>("auth")?; drop(auth);
auth.refresh()?;
drop(auth);
}
})?; })?;
Ok(()) Ok(())
} }
@@ -128,7 +117,7 @@ pub fn client_auth(mize: &mut Mize) -> MizeResult<()> {
}; };
// do a refresh if the tokens have expired // 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( secrets = Some(
mize.spawn_async_blocking("refresh_low", refresh_flow(mize.clone(), secrets.unwrap()))?, 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")] #[cfg(feature = "target-os")]
{ {
let mut cli = mize.get_part_native::<marts::CliPart>("cli")?; let mut cli = mize.get_part_native::<crate::CliPart>("cli")?;
cli.subcommand(Command::new("login"), |_, mut mize| { cli.subcommand(Command::new("login"), |_, mut mize| {
let mut auth = mize.get_part_native::<ClientAuth>("client_auth")?; let mut auth = mize.get_part_native::<ClientAuth>("client_auth")?;
println!("secrets: {:?}", auth.secrets); println!("secrets: {:?}", auth.secrets);
@@ -206,14 +195,8 @@ fn write_secrets(mize: &mut Mize, secrets: &ClientSecrets) -> MizeResult<()> {
Ok(()) Ok(())
} }
#[derive(Serialize, Deserialize)]
struct Combined<'a> {
code: &'a str,
state: &'a str,
}
use openidconnect::DeviceAuthorizationUrl;
use openidconnect::reqwest::Client as HttpClient; use openidconnect::reqwest::Client as HttpClient;
use openidconnect::DeviceAuthorizationUrl;
use std::time::Duration; use std::time::Duration;
async fn refresh_flow(mut mize: Mize, old_secrets: ClientSecrets) -> MizeResult<ClientSecrets> { async fn refresh_flow(mut mize: Mize, old_secrets: ClientSecrets) -> MizeResult<ClientSecrets> {
@@ -231,14 +214,14 @@ async fn refresh_flow(mut mize: Mize, old_secrets: ClientSecrets) -> MizeResult<
struct MyExtraProviderMetadata { struct MyExtraProviderMetadata {
device_authorization_endpoint: String, device_authorization_endpoint: String,
} }
use openidconnect::AdditionalProviderMetadata;
use openidconnect::ProviderMetadata;
use openidconnect::core::{ use openidconnect::core::{
CoreAuthDisplay, CoreClaimName, CoreClaimType, CoreClient, CoreClientAuthMethod, CoreAuthDisplay, CoreClaimName, CoreClaimType, CoreClient, CoreClientAuthMethod,
CoreDeviceAuthorizationResponse, CoreGrantType, CoreJsonWebKey, CoreJsonWebKeyType, CoreGrantType, CoreJsonWebKey, CoreJweContentEncryptionAlgorithm,
CoreJsonWebKeyUse, CoreJweContentEncryptionAlgorithm, CoreJweKeyManagementAlgorithm, CoreJweKeyManagementAlgorithm, CoreResponseMode, CoreResponseType,
CoreJwsSigningAlgorithm, CoreResponseMode, CoreResponseType, CoreSubjectIdentifierType, CoreSubjectIdentifierType,
}; };
use openidconnect::AdditionalProviderMetadata;
use openidconnect::ProviderMetadata;
impl AdditionalProviderMetadata for MyExtraProviderMetadata {} impl AdditionalProviderMetadata for MyExtraProviderMetadata {}
type MyProviderMetadata = ProviderMetadata< type MyProviderMetadata = ProviderMetadata<
MyExtraProviderMetadata, MyExtraProviderMetadata,
@@ -302,14 +285,14 @@ async fn auth_flow(mut mize: Mize) -> MizeResult<ClientSecrets> {
struct MyExtraProviderMetadata { struct MyExtraProviderMetadata {
device_authorization_endpoint: String, device_authorization_endpoint: String,
} }
use openidconnect::AdditionalProviderMetadata;
use openidconnect::ProviderMetadata;
use openidconnect::core::{ use openidconnect::core::{
CoreAuthDisplay, CoreClaimName, CoreClaimType, CoreClient, CoreClientAuthMethod, CoreAuthDisplay, CoreClaimName, CoreClaimType, CoreClient, CoreClientAuthMethod,
CoreDeviceAuthorizationResponse, CoreGrantType, CoreJsonWebKey, CoreJsonWebKeyType, CoreGrantType, CoreJsonWebKey, CoreJweContentEncryptionAlgorithm,
CoreJsonWebKeyUse, CoreJweContentEncryptionAlgorithm, CoreJweKeyManagementAlgorithm, CoreJweKeyManagementAlgorithm, CoreResponseMode, CoreResponseType,
CoreJwsSigningAlgorithm, CoreResponseMode, CoreResponseType, CoreSubjectIdentifierType, CoreSubjectIdentifierType,
}; };
use openidconnect::AdditionalProviderMetadata;
use openidconnect::ProviderMetadata;
impl AdditionalProviderMetadata for MyExtraProviderMetadata {} impl AdditionalProviderMetadata for MyExtraProviderMetadata {}
type MyProviderMetadata = ProviderMetadata< type MyProviderMetadata = ProviderMetadata<
MyExtraProviderMetadata, MyExtraProviderMetadata,
@@ -372,7 +355,7 @@ async fn auth_flow(mut mize: Mize) -> MizeResult<ClientSecrets> {
#[cfg(feature = "target-os")] #[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()); let _ = webbrowser::open(details.verification_uri_complete().unwrap().secret());
} }
} }
@@ -382,7 +365,7 @@ async fn auth_flow(mut mize: Mize) -> MizeResult<ClientSecrets> {
.request_async( .request_async(
&http_client, &http_client,
async |dur: Duration| { async |dur: Duration| {
tokio::time::sleep(dur); tokio::time::sleep(dur).await;
}, },
None, None,
) )

View File

@@ -5,10 +5,21 @@ use clap::{Arg, Command};
use rusqlite::{params, Connection}; use rusqlite::{params, Connection};
use serde_json::{json, Value}; 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::cli::CliPart;
use crate::habitica::Habitica; 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; mod dashboard;
@@ -24,6 +35,7 @@ impl MizePart for C2vi {
mize.new_opt("c2vi.local_storage_path"); mize.new_opt("c2vi.local_storage_path");
} }
} }
impl MizePartCreate for C2vi {}
impl C2vi { impl C2vi {
fn with_db<F, R>(&self, f: F) -> MizeResult<R> fn with_db<F, R>(&self, f: F) -> MizeResult<R>
@@ -42,12 +54,67 @@ impl C2vi {
} }
pub fn c2vi(mize: &mut Mize) -> MizeResult<()> { pub fn c2vi(mize: &mut Mize) -> MizeResult<()> {
#[cfg(feature = "client")] #[cfg(feature = "desktop")]
c2vi_client(mize)?; 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::<ClientAuth>("auth")?;
auth.refresh()?;
auth.start_refresh_thread()?;
drop(auth);
launch_c2vi_dashboard(mize);
}
Ok(()) 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::<Mize>();
let mut spacetime = mize.get_part_native::<SpacetimePart>("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<()> { pub fn c2vi_client(mize: &mut Mize) -> MizeResult<()> {
//let storage_path = mize.get_config("c2vi.local_storage_path")?.as_ //let storage_path = mize.get_config("c2vi.local_storage_path")?.as_
let storage_path = "/home/me/work/app-data/ppc"; 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) { fn register_subcommands(cli: &mut CliPart) {
cli.subcommand( cli.subcommand(
Command::new("c2vi-dash").about("Run the c2vi dashboard gui"), 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( cli.subcommand(
Command::new("bed").about("Command to run when c2vi goes to bed"), Command::new("bed").about("Command to run when c2vi goes to bed"),

View File

@@ -1,7 +1,7 @@
use clap::{ArgMatches, Command}; use clap::{ArgMatches, Command};
use std::collections::HashMap; use std::collections::HashMap;
use mize::{mize_part, Mize, MizePart, MizeResult}; use mize::{mize_part, Mize, MizePart, MizePartCreate, MizeResult};
#[mize_part("cli")] #[mize_part("cli")]
#[derive(Default)] #[derive(Default)]
@@ -28,6 +28,8 @@ pub fn cli(mize: &mut Mize) -> MizeResult<()> {
mize.add_part(Box::new(cli_part)) mize.add_part(Box::new(cli_part))
} }
impl MizePartCreate for CliPart {}
impl MizePart for CliPart { impl MizePart for CliPart {
fn init(&mut self, _mize: &mut Mize) -> MizeResult<()> { fn init(&mut self, _mize: &mut Mize) -> MizeResult<()> {
Ok(()) Ok(())

View File

@@ -1,5 +1,5 @@
use chrono::{DateTime, Utc}; 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 reqwest::{blocking::Client, blocking::Response, header, Method};
use serde_json::{json, Value}; use serde_json::{json, Value};
use std::thread::sleep; use std::thread::sleep;
@@ -20,6 +20,7 @@ pub fn habitica(mize: &mut Mize) -> MizeResult<()> {
})) }))
} }
impl MizePartCreate for Habitica {}
impl MizePart for Habitica { impl MizePart for Habitica {
fn opts(&self, mize: &mut Mize) { fn opts(&self, mize: &mut Mize) {
mize.new_opt("habitica.api_url"); mize.new_opt("habitica.api_url");

View File

@@ -1,6 +1,3 @@
use mize::MizeResult;
#[cfg(feature = "target-os")] #[cfg(feature = "target-os")]
mod cli; mod cli;
#[cfg(feature = "target-os")] #[cfg(feature = "target-os")]
@@ -16,6 +13,17 @@ pub mod c2vi;
#[cfg(feature = "target-os")] #[cfg(feature = "target-os")]
pub use c2vi::*; 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")] //#[cfg(feature = "target-os")]
//pub mod js; //pub mod js;
//#[cfg(feature = "target-os")] //#[cfg(feature = "target-os")]

View File

@@ -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] #[mize_part]
#[derive(Default)] #[derive(Default)]
@@ -9,6 +10,7 @@ pub struct SpacetimePart {
con: Option<DbConnection>, con: Option<DbConnection>,
} }
impl MizePartCreate for SpacetimePart {}
impl MizePart for SpacetimePart { impl MizePart for SpacetimePart {
fn name(&self) -> &'static str { fn name(&self) -> &'static str {
"spacetime" "spacetime"

View File

@@ -45,35 +45,5 @@ pub fn gather_config(mize: &mut Mize) -> MizeResult<()> {
part.as_deref().unwrap().opts(&mut mize.clone()); 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::<Vec<&str>>())?;
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(()) Ok(())
} }

View File

@@ -125,7 +125,7 @@ impl MizeError {
} }
pub fn log(self) -> MizeError { pub fn log(self) -> MizeError {
error!("MizeError envountered!"); error!("MizeError encountered!");
if let Some(ref location) = self.code_location { if let Some(ref location) = self.code_location {
error!("[ {} ] {}", "LOCATION".yellow(), location); error!("[ {} ] {}", "LOCATION".yellow(), location);

View File

@@ -25,8 +25,8 @@ use crate::instance::updater::Operation;
use crate::instance::updater::{updater_thread, updater_thread_async}; use crate::instance::updater::{updater_thread, updater_thread_async};
use crate::item::{Item, ItemData}; use crate::item::{Item, ItemData};
use crate::memstore::MemStore; use crate::memstore::MemStore;
use crate::mize_err;
use crate::proto::MizeMessage; use crate::proto::MizeMessage;
use crate::{mize_err, Module};
use self::connection::{ConnListener, Connection}; use self::connection::{ConnListener, Connection};
use self::updater::handle_operation; use self::updater::handle_operation;
@@ -40,7 +40,6 @@ use core::future::Future;
use std::thread::JoinHandle; use std::thread::JoinHandle;
pub mod connection; pub mod connection;
pub mod module;
pub mod msg_thread; pub mod msg_thread;
pub mod store; pub mod store;
pub mod subscription; pub mod subscription;
@@ -61,13 +60,12 @@ pub struct Mize {
connections: Arc<Mutex<Vec<Connection>>>, connections: Arc<Mutex<Vec<Connection>>>,
next_con_id: Arc<Mutex<u64>>, next_con_id: Arc<Mutex<u64>>,
subs: Arc<Mutex<HashMap<MizeId, Vec<Subscription>>>>, subs: Arc<Mutex<HashMap<MizeId, Vec<Subscription>>>>,
pub(crate) modules: Arc<Mutex<HashMap<String, Box<dyn Module + Sync + Send>>>>,
pub(crate) id_pool: Arc<Mutex<VecStringPool>>, pub(crate) id_pool: Arc<Mutex<VecStringPool>>,
pub(crate) namespace_pool: Arc<Mutex<StringPool>>, pub(crate) namespace_pool: Arc<Mutex<StringPool>>,
pub(crate) parts: Arc<Mutex<HashMap<&'static str, Option<Box<dyn MizePart + Sync + Send>>>>>, pub(crate) parts: Arc<Mutex<HashMap<&'static str, Option<Box<dyn MizePart + Sync + Send>>>>>,
//pub(crate) platform: Arc<Mutex<Box<dyn MizePlatform>>>, // should we do that instead of all the #cfg(faturs=targt-smth) in lib.rs
part_names: Arc<Mutex<Vec<&'static str>>>, part_names: Arc<Mutex<Vec<&'static str>>>, // exists, so that we know the ordering in which parts were loaded
pub(crate) config_opts: Arc<Mutex<HashMap<String, ConfigOpt>>>, pub(crate) config_opts: Arc<Mutex<HashMap<String, ConfigOpt>>>,
@@ -166,11 +164,40 @@ pub trait MizePartGenerated {
} }
pub trait MizePartCreate: MizePartCreateGenerated + MizePart + 'static { pub trait MizePartCreate: MizePartCreateGenerated + MizePart + 'static {
fn create(mize: &mut Mize) -> Box<dyn MizePart> { fn create(mize: &mut Mize) -> MizeResult<Box<dyn MizePart>> {
Box::new(Self::create_generated(mize.clone())) Ok(Box::new(Self::create_generated(mize.clone())))
} }
} }
pub trait MizePartCreateThisSucks: MizePartCreate + MizePart + 'static {
fn create_this_sucks(mize: &mut Mize) -> MizeResult<Box<dyn MizePart>> {
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<Self>) -> Box<dyn Any> {
self
}
}
impl MizePart for EmptyPart {}
#[async_trait] #[async_trait]
pub trait MizePart: MizePartGenerated { pub trait MizePart: MizePartGenerated {
fn name(&self) -> &'static str { fn name(&self) -> &'static str {
@@ -236,7 +263,6 @@ impl Mize {
self_namespace, self_namespace,
op_tx, op_tx,
namespace_pool: Arc::new(Mutex::new(namespace_pool_raw)), namespace_pool: Arc::new(Mutex::new(namespace_pool_raw)),
modules: Arc::new(Mutex::new(HashMap::new())),
threads: Arc::new(Mutex::new(Vec::new())), threads: Arc::new(Mutex::new(Vec::new())),
next_thread_id: Arc::new(Mutex::new(0)), next_thread_id: Arc::new(Mutex::new(0)),
next_con_id: Arc::new(Mutex::new(1)), next_con_id: Arc::new(Mutex::new(1)),
@@ -337,7 +363,7 @@ impl Mize {
} }
pub fn init(&mut self) -> MizeResult<()> { pub fn init(&mut self) -> MizeResult<()> {
// gather options // gather config options from all parts
gather_config(self)?; gather_config(self)?;
// platform specific init code // platform specific init code
@@ -345,21 +371,19 @@ impl Mize {
// end of platform specific init code // end of platform specific init code
// load the modules, ad specified in the load_modules config // load the modules, as specified in the parts config
match self.get("0/config/load_modules")?.value_string() { match self.get_config("parts")?.value_string() {
Ok(modules_to_load) => { Ok(parts_to_load) => {
for module in modules_to_load.split(" ") { for part_name in parts_to_load.split(" ") {
#[cfg(feature = "target-wasm ")] self.load_part(part_name)?;
console_log!("loading module in Instance::init() ... {}", module);
self.load_module(module)?;
} }
} }
Err(err) => { Err(err) => {
// no load_modules option is set // no parts to load
} }
} }
debug!("INSTANCE INIT DONE"); debug!("MIZE INIT DONE");
Ok(()) Ok(())
} }
@@ -515,29 +539,25 @@ impl Mize {
Ok(id) Ok(id)
} }
pub fn load_module(&mut self, name: &str) -> MizeResult<()> { pub fn load_part(&mut self, name: &str) -> MizeResult<()> {
crate::platform::any::load_module(self, name, None) 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<String> { pub fn fetch_part(&mut self, name: &str) -> MizeResult<String> {
// platform specific way to fetch a module // 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 // platform specific init code
crate::platform::any::load_module(self, name, Some(path)) crate::platform::any::load_part(self, name, Some(path))
}
pub fn get_module(&mut self, name: &str) -> MizeResult<Box<dyn Module + Send + Sync>> {
let inner = self.modules.lock()?;
let module = inner
.get(name)
.ok_or(mize_err!("Couldn't get_module('{name}')"))?
.clone_module();
Ok(module)
} }
pub fn namespace_from_string(&self, ns_str: String) -> MizeResult<Namespace> { pub fn namespace_from_string(&self, ns_str: String) -> MizeResult<Namespace> {

View File

@@ -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<dyn Module + Send + Sync>;
// extra traits, that can be implemented
// return None if not implemented
fn run_cli(&mut self, instance: &Mize, cmd_line: Vec<OsString>) -> Option<MizeResult<()>> {
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<dyn Module + Send + Sync> {
Box::new(EmptyModule {})
}
}

View File

@@ -43,7 +43,7 @@ fn test_sort_keys() -> MizeResult<()> {
fn test_get_module_hash() -> MizeResult<()> { fn test_get_module_hash() -> MizeResult<()> {
let mut instance = Mize::empty()?; let mut instance = Mize::empty()?;
use crate::platform::os::get_module_hash; use crate::platform::os::get_part_hash;
let selector_toml = r#" let selector_toml = r#"
mize_version = "0.0.0" mize_version = "0.0.0"
system = "x86_64-unknown-linux-gnu" 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)?)?; 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!("hash: {}", hash);
test_println!("selector: {}", selector); test_println!("selector: {}", selector);

View File

@@ -225,6 +225,12 @@ impl ItemData {
_ => Err(mize_err!("this ItemData has no string value")), _ => Err(mize_err!("this ItemData has no string value")),
} }
} }
pub fn as_bool(self) -> Option<bool> {
match self.cbor() {
CborValue::Bool(val) => Some(*val),
_ => None,
}
}
pub fn from_string<S: Into<String>>(into_string: S) -> ItemData { pub fn from_string<S: Into<String>>(into_string: S) -> ItemData {
let string = into_string.into(); 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); trace!("[ {} ] path: {:?}", "ARG".yellow(), path);
let mut path_iter = path.clone().into_iter(); let mut path_iter = path.clone().into_iter();
let path_el = match path_iter.nth(0) { let path_el =
Some(val) => val, match path_iter.nth(0) {
None => { Some(val) => val,
// our base case None => {
let ret_val = match value { // our base case
CborValue::Bytes(vec) => { let ret_val =
trace!("[ {} ] ret value: {:?}", "RET".yellow(), &vec[..]); match value {
return Ok(&vec[..]); CborValue::Bytes(vec) => {
} trace!("[ {} ] ret value: {:?}", "RET".yellow(), &vec[..]);
CborValue::Text(string) => { return Ok(&vec[..]);
trace!("[ {} ] ret value: {:?}", "RET".yellow(), string.as_bytes()); }
return Ok(string.as_bytes()); CborValue::Text(string) => {
} trace!("[ {} ] ret value: {:?}", "RET".yellow(), string.as_bytes());
other => { return Ok(string.as_bytes());
return Err(mize_err!( }
"path is empty and the value: '{:?}' is neither Bytes nor Text", other => {
return Err(mize_err!(
"path '{}' is empty and the value: '{:?}' is neither Bytes nor Text",
path.iter().map(|p| p.as_str()).collect::<Vec<_>>().join("."),
other other
)); ));
} }
}; };
} }
}; };
match value { match value {
CborValue::Bytes(vec) => { CborValue::Bytes(vec) => {

View File

@@ -45,7 +45,6 @@ mod core {
pub use async_trait::async_trait; pub use async_trait::async_trait;
pub use core::error::MizeError; pub use core::error::MizeError;
pub use core::error::MizeResult; pub use core::error::MizeResult;
pub use core::instance::module::Module;
pub use core::instance::Mize; pub use core::instance::Mize;
pub use core::instance::{ pub use core::instance::{
DynMizePartGuard, MizePart, MizePartCreate, MizePartCreateGenerated, MizePartGenerated, DynMizePartGuard, MizePart, MizePartCreate, MizePartCreateGenerated, MizePartGenerated,
@@ -74,33 +73,34 @@ pub mod platform {
#[cfg(not(any(feature = "target-os", feature = "target-js")))] #[cfg(not(any(feature = "target-os", feature = "target-js")))]
pub use super::super::instance_init; pub use super::super::instance_init;
//////////// load_module //////////// load_part
#[cfg(feature = "target-os")] #[cfg(feature = "target-os")]
pub use super::os::load_module; pub use super::os::load_part;
#[cfg(feature = "target-js")] #[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")))] #[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")] #[cfg(feature = "target-os")]
pub use super::os::fetch_module; pub use super::os::fetch_part;
#[cfg(feature = "target-js")] #[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")))] #[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<()> { pub fn instance_init(instance: &mut core::instance::Mize) -> MizeResult<()> {
Ok(()) Ok(())
} }
pub fn load_module( pub fn load_part(
instance: &mut core::instance::Mize, instance: &mut core::instance::Mize,
name: &str, name: &str,
path: Option<String>, path: Option<String>,
@@ -108,6 +108,6 @@ pub fn load_module(
Ok(()) Ok(())
} }
pub fn fetch_module(instance: &mut core::instance::Mize, name: &str) -> MizeResult<String> { pub fn fetch_part(instance: &mut core::instance::Mize, name: &str) -> MizeResult<String> {
Ok("oh noooooooooooooo, something went really really wrong, if this ends up in the executable....".to_owned()) Ok("oh noooooooooooooo, something went really really wrong, if this ends up in the executable....".to_owned())
} }

View File

@@ -120,7 +120,7 @@ pub fn stop(sub_matches: &ArgMatches) -> MizeResult<()> {
pub fn gui(sub_matches: &ArgMatches) -> MizeResult<()> { pub fn gui(sub_matches: &ArgMatches) -> MizeResult<()> {
let mut instance = Mize::with_config(config_from_cli_args(sub_matches)?)?; let mut instance = Mize::with_config(config_from_cli_args(sub_matches)?)?;
instance.load_module("mme")?; instance.load_part("mme")?;
instance.wait(); 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)?)?; let mut instance = Mize::with_config(config_from_cli_args(sub_matches)?)?;
debug!("loading module '{}'", cmd); debug!("loading module '{}'", cmd);
instance.load_module(cmd)?; instance.load_part(cmd)?;
instance println!("running cli from part not implemented");
.get_module(cmd)? //instance
.run_cli(&instance, sub_cmd_line) //.get_part(cmd)?
.ok_or(mize_err!( //.run_cli(&instance, sub_cmd_line)
"The Module '{cmd}' does not implement the run_cli() functionality" //.ok_or(mize_err!(
))??; //"The Part '{cmd}' does not implement the run_cli() functionality"
//))??;
Ok(()) Ok(())
} }

View File

@@ -12,14 +12,15 @@ use std::time::UNIX_EPOCH;
use tar::Archive; use tar::Archive;
use tracing::{debug, error, info, trace, warn}; use tracing::{debug, error, info, trace, warn};
use crate::config::ConfigOpt;
use crate::error::{IntoMizeResult, MizeError, MizeResult}; use crate::error::{IntoMizeResult, MizeError, MizeResult};
use crate::id::MizeId; use crate::id::MizeId;
use crate::instance::module::EmptyModule;
use crate::instance::store::Store; use crate::instance::store::Store;
use crate::instance::EmptyPart;
use crate::instance::Mize; use crate::instance::Mize;
use crate::item::{data_from_string, IntoItemData, ItemData}; use crate::item::{data_from_string, IntoItemData, ItemData};
use crate::memstore::MemStore; use crate::memstore::MemStore;
use crate::{mize_err, Module}; use crate::{mize_err, MizePart};
use self::fsstore::FileStore; use self::fsstore::FileStore;
@@ -33,40 +34,23 @@ mod unix_socket;
use crate::platform::os::unix_socket::UnixListener; use crate::platform::os::unix_socket::UnixListener;
//mod web; //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. // 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 ////// populate values from $MIZE_CONFIG_FILES
match std::env::var("MIZE_CONFIG_FILE") { let config_file_paths = std::env::var("MIZE_CONFIG_FILES")?;
Ok(config_file_path) => { for config_file_path in config_file_paths.split(":") {
let config = config_from_file(config_file_path)?; println!("reading config file: {config_file_path}");
debug!("env var MIZE_CONFIG_FILE present"); let content = std::fs::read_to_string(config_file_path)?;
instance.set_blocking("0", config)?; let mut data = ItemData::from_toml(content.as_str())?;
trace!( set_config_from_data(mize, data)?;
"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")
}
},
};
////// load config from MIZE_CONFIG env var ////// load config from MIZE_CONFIG env var
match std::env::var("MIZE_CONFIG") { match std::env::var("MIZE_CONFIG") {
Ok(config_string) => { Ok(config_string) => {
let config = data_from_string(config_string)?; let data = data_from_string(config_string)?;
debug!("env var MIZE_CONFIG present"); set_config_from_data(mize, data)?;
instance.set_blocking("self/config", config)?;
trace!(
"config after MIZE_CONFIG env var: {}",
instance.get("self/config")?
);
} }
Err(var_err) => match var_err { Err(var_err) => match var_err {
VarError::NotPresent => { 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 ////// if a config.store_path is set, upgrade to the filestore there
let mut test = instance.get("0")?.as_data_full()?; let mut test = mize.get("0")?.as_data_full()?;
let mut store_path = match instance.get("self/config/store_path")?.value_string() { let mut store_path = match mize.get("self/config/store_path")?.value_string() {
Ok(path) => path, Ok(path) => path,
Err(e) => { Err(e) => {
// the default store_path: $HOME/.mize // 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_buff = home_dir.join(".mize");
let store_path = store_path_buff.display().to_string(); let store_path = store_path_buff.display().to_string();
instance.set_blocking( mize.set_blocking(
"self/config/store_path", "self/config/store_path",
store_path.clone().into_item_data(), 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); 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 // if the store is already opened, connect to the instance, that opened it and join
// it's namespace // it's namespace
@@ -116,7 +100,7 @@ pub fn os_instance_init(instance: &mut Mize) -> MizeResult<()> {
{ {
info!("CONNECTING"); info!("CONNECTING");
use crate::platform::os::unix_socket; use crate::platform::os::unix_socket;
unix_socket::connect(instance, store_path.into())?; unix_socket::connect(mize, store_path.into())?;
return Ok(()); return Ok(());
} }
@@ -127,13 +111,13 @@ pub fn os_instance_init(instance: &mut Mize) -> MizeResult<()> {
} else { } else {
// else open it ourselves // else open it ourselves
let file_store = FileStore::new(store_path.as_str())?; 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(); let path = Path::new(&store_path).to_owned();
#[cfg(target_family = "unix")] #[cfg(target_family = "unix")]
{ {
instance.add_listener(UnixListener::new(path)?)?; mize.add_listener(UnixListener::new(path)?)?;
} }
#[cfg(target_family = "windows")] #[cfg(target_family = "windows")]
@@ -144,6 +128,32 @@ pub fn os_instance_init(instance: &mut Mize) -> MizeResult<()> {
Ok(()) 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::<Vec<&str>>())?;
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<u64> { pub fn seconds_since_modification(path: &Path) -> MizeResult<u64> {
let metadata = fs::metadata(path)?; let metadata = fs::metadata(path)?;
@@ -155,12 +165,12 @@ pub fn seconds_since_modification(path: &Path) -> MizeResult<u64> {
Ok(duration.as_secs()) Ok(duration.as_secs())
} }
pub fn get_module_hash( pub fn get_part_hash(
instance: &mut Mize, mize: &mut Mize,
name: &str, name: &str,
mut options: ItemData, mut options: ItemData,
) -> MizeResult<(String, String)> { ) -> 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... // handle the case, when we want a module for not the system we are running on...
println!("get_module_hash: name: {}", name); println!("get_module_hash: name: {}", name);
@@ -209,28 +219,25 @@ pub fn get_module_hash(
return Ok((hex, selector_str)); return Ok((hex, selector_str));
} }
fn download_module( fn download_part(
instance: &mut Mize, mize: &mut Mize,
store_path: &str, store_path: &str,
module_url: &str, part_url: &str,
module_hash: &str, part_hash: &str,
module_name: &str, part_name: &str,
module_selector: &str, part_selector: &str,
) -> MizeResult<()> { ) -> 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 tmp_gz_file = if !PathBuf::from(tmp_file_path_gz.clone()).exists() {
let mut tmp_gz_file = File::create(&tmp_file_path_gz)?; let mut tmp_gz_file = File::create(&tmp_file_path_gz)?;
debug!( debug!("downloading part '{}' with hash: {}", part_name, part_hash);
"downloading module '{}' with hash: {}",
module_name, module_hash
);
let response = http_req::request::get( let response = http_req::request::get(
format!( format!(
"http://{}/mize/dist/{}-{}.tar.gz", "http://{}/mize/dist/{}-{}.tar.gz",
module_url, module_hash, module_name part_url, part_hash, part_name
), ),
&mut tmp_gz_file, &mut tmp_gz_file,
)?; )?;
@@ -238,13 +245,13 @@ fn download_module(
let code = response.status_code(); let code = response.status_code();
if code != 200.into() { if code != 200.into() {
return Err(mize_err!( return Err(mize_err!(
"failed to get module '{}' with hash '{}' and selector: {}", "failed to get part '{}' with hash '{}' and selector: {}",
module_name, part_name,
module_hash, part_hash,
module_selector part_selector
) )
.msg(format!( .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 code
))); )));
} }
@@ -259,7 +266,7 @@ fn download_module(
//archive.set_mask(umask::Mode::parse("rwxrwxrwx")?.into()); //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())?; std::fs::create_dir_all(target_dir.as_str())?;
@@ -270,72 +277,66 @@ fn download_module(
Ok(()) Ok(())
} }
pub fn fetch_module(instance: &mut Mize, module_name: &str) -> MizeResult<String> { pub fn fetch_part(mize: &mut Mize, part_name: &str) -> MizeResult<String> {
let module_name_with_slashes = module_name.replace(".", "/"); let part_name_with_slashes = part_name.replace(".", "/");
if let Ok(module_path) = instance if let Ok(part_path) = mize
.get(format!( .get(format!("self/config/part_dir/{}", part_name_with_slashes))?
"self/config/module_dir/{}",
module_name_with_slashes
))?
.value_string() .value_string()
{ {
// in case a dir is configured, which holds the modules output // in case a dir is configured, which holds the parts output
return Ok(module_path); return Ok(part_path);
} else { } else {
// if null, load it from the url // 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) = let (part_hash, part_selector) = get_part_hash(mize, part_name, ItemData::new())?;
get_module_hash(instance, module_name, ItemData::new())?;
if !PathBuf::from(format!("{}/modules/{}", store_path, module_hash.as_str())).exists() { if !PathBuf::from(format!("{}/parts/{}", store_path, part_hash.as_str())).exists() {
// download module if it does not exist // download part if it does not exist
download_module( download_part(
instance, mize,
store_path.as_str(), store_path.as_str(),
module_url.as_str(), part_url.as_str(),
module_hash.as_str(), part_hash.as_str(),
module_name, part_name,
module_selector.as_str(), 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<String>) -> MizeResult<()> { pub fn load_part(mize: &mut Mize, part_name: &str, path: Option<String>) -> MizeResult<()> {
let module_path = if path.is_some() { let part_path = if path.is_some() {
format!("{}/lib/libmize_module_{}.so", path.unwrap(), module_name) format!("{}/lib/lib{}_part.so", path.unwrap(), part_name)
} else { } else {
format!( format!(
"{}/lib/libmize_module_{}.so", "{}/lib/lib{}_part.so",
fetch_module(instance, module_name)?, fetch_part(mize, part_name)?,
module_name part_name
) )
}; };
let lib = unsafe { libloading::Library::new(module_path)? }; let lib = unsafe { libloading::Library::new(part_path)? };
let func: libloading::Symbol< let func: libloading::Symbol<
unsafe extern "C" fn(&mut Box<dyn Module + Send + Sync>, Mize) -> (), unsafe extern "C" fn(&mut Box<dyn MizePart + Send + Sync>, Mize) -> (),
> = unsafe { lib.get(format!("get_mize_module_{}", module_name).as_bytes())? }; > = unsafe { lib.get(format!("make_mize_part_{}", part_name).as_bytes())? };
let mut module: Box<dyn Module + Send + Sync> = Box::new(EmptyModule {}); let mut part: Box<dyn MizePart + Send + Sync> = 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)?; mize.add_part(part)?;
modules_inner.insert(module_name.to_owned(), module);
unsafe { unsafe {
// dropping the lib, would (i suspect) free all memory, of the library's code, which would // 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); std::mem::forget(lib);
} }

View File

@@ -9,11 +9,11 @@ marts = { path = "../marts/", default-features = false }
clap = { version = "4.5.59", optional = true } clap = { version = "4.5.59", optional = true }
js-sys = { version = "0.3.85", optional = true } js-sys = { version = "0.3.85", optional = true }
wasm-bindgen = { version = "0.2.108", optional = true } wasm-bindgen = { version = "0.2.108", optional = true }
generated = { path = "../../packages/generated" }
# server deps # server deps
axum = { version = "0.8.0", optional = true } axum = { version = "0.8.0", optional = true }
axum-extra = { version = "0.10.3", features = ["cookie-private"], 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 = { version = "1.0", features = ["derive"], optional = true }
serde_json = { version = "1.0", optional = true } serde_json = { version = "1.0", optional = true }
reqwest = { version = "0.11", features = ["rustls-tls"], 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 = { version = "0.5", optional = true }
tower-sessions = { version = "0.14.0", optional = true } tower-sessions = { version = "0.14.0", optional = true }
tower-http = { version = "0.6.8", features = ["trace"] } tower-http = { version = "0.6.8", features = ["trace"] }
webbrowser = { version = "1.2.0", optional = true }
base64 = { version = "0.22.1", optional = true } base64 = { version = "0.22.1", optional = true }
dioxus-web = { version = "0.7.3", optional = true } dioxus-web = { version = "0.7.3", optional = true }
web-sys = { version = "0.3.91", optional = true } web-sys = { version = "0.3.91", optional = true }
spacetimedb-sdk = "2.1.0" spacetimedb-sdk = "2.1.0"
openidconnect = { version = "4", features = ["reqwest", "rustls-tls"], optional = true }
flume = "0.12.0" flume = "0.12.0"
chrono = "0.4.44" chrono = "0.4.44"
@@ -48,12 +48,12 @@ name = "ppc"
[features] [features]
default = ["target-os", "server", "client" ] default = ["target-os", "server", "client" ]
target-os = [ "clap", "mize/target-os", "marts/target-os", "tracing", "webbrowser", "base64", "serde_json", "serde" ] target-os = [ "marts/target-os", "clap", "mize/target-os", "marts/target-os", "tracing", "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" ] 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 = [ "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" ] 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 = ["dioxus/desktop", "marts/desktop", "target-os"] desktop = [ "marts/desktop", "dioxus/desktop", "target-os"]
client = [ "tokio", "openidconnect" ] client = [ "marts/client", "tokio" ]
webbrowser = ["dep:webbrowser"] website = []
[package.metadata.wasm-pack.profile.release] [package.metadata.wasm-pack.profile.release]

View File

@@ -1,5 +1,9 @@
#![feature(oneshot_channel)] #![feature(oneshot_channel)]
use clap::Command;
use clap::crate_version;
use mize::{Mize, MizePart, MizeResult, mize_part};
mod platform { mod platform {
#[cfg(feature = "target-obsidian")] #[cfg(feature = "target-obsidian")]
pub mod obsidian; pub mod obsidian;
@@ -17,6 +21,7 @@ mod platform {
#[cfg(feature = "website")] #[cfg(feature = "website")]
mod website; mod website;
use mize::MizePartCreate;
#[cfg(feature = "target-os")] #[cfg(feature = "target-os")]
#[cfg(feature = "server")] #[cfg(feature = "server")]
pub use platform::os::server::server; pub use platform::os::server::server;
@@ -24,14 +29,67 @@ pub use platform::os::server::server;
#[cfg(feature = "desktop")] #[cfg(feature = "desktop")]
pub use platform::os::ui; pub use platform::os::ui;
pub mod auth {
pub mod client;
}
pub use auth::client::client_auth;
pub mod spacetime;
pub mod timetrack; pub mod timetrack;
// the generated source #[mize_part("ppc")]
// right now only from spacetimedb #[derive(Default)]
mod generated; pub struct PPCPart {
mize: Mize,
}
impl MizePart for PPCPart {}
impl MizePartCreate for PPCPart {
fn create(mize: &mut mize::Mize) -> MizeResult<Box<dyn mize::MizePart>> {
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::<marts::CliPart>("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(),
}))
}
}

View File

@@ -1,5 +1,3 @@
use std::collections::HashMap;
use clap::Command; use clap::Command;
use clap::crate_version; use clap::crate_version;
use mize::{Mize, MizeResult}; use mize::{Mize, MizeResult};
@@ -17,7 +15,7 @@ fn main() {
#[cfg(feature = "target-os")] #[cfg(feature = "target-os")]
fn os_main(mize: &mut Mize) -> MizeResult<()> { fn os_main(mize: &mut Mize) -> MizeResult<()> {
use ppc::spacetime::spacetime; use marts::spacetime::spacetime;
marts::cli(mize)?; marts::cli(mize)?;
//marts::js(mize)?; //marts::js(mize)?;
@@ -26,7 +24,7 @@ fn os_main(mize: &mut Mize) -> MizeResult<()> {
{ {
use ppc::timetrack::timetrack; use ppc::timetrack::timetrack;
ppc::client_auth(mize)?; marts::client_auth(mize)?;
if let Err(err) = spacetime(mize) { if let Err(err) = spacetime(mize) {
println!("spacetime part failed to initialize: {:?}", err); println!("spacetime part failed to initialize: {:?}", err);
}; };
@@ -48,18 +46,6 @@ fn os_main(mize: &mut Mize) -> MizeResult<()> {
ppc::ui::launch_desktop_app(); ppc::ui::launch_desktop_app();
Ok(()) 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::<ClientAuth>("auth")?;
auth.refresh()?;
auth.start_refresh_thread()?;
drop(auth);
ppc::ui::launch_c2vi_dashboard(&mut mize);
Ok(())
});
} }
cli.with_cmd(|_, cmd| { cli.with_cmd(|_, cmd| {

View File

@@ -1,6 +1,5 @@
use axum::{Json, http::StatusCode}; use axum::{Json, http::StatusCode};
use serde_json::{Value, json}; use serde_json::{Value, json};
use std::net::SocketAddr;
use std::str::FromStr; use std::str::FromStr;
use axum::{ use axum::{
@@ -57,7 +56,6 @@ pub fn server(mize: &mut Mize) -> MizeResult<()> {
pub async fn start_server(mize: &mut Mize) -> MizeResult<()> { pub async fn start_server(mize: &mut Mize) -> MizeResult<()> {
dioxus::logger::initialize_default(); 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 listen_addr = mize.get_config("server.listen_addr")?.value_string()?;
let port = mize.get_config("server.port")?.value_string()?; let port = mize.get_config("server.port")?.value_string()?;
let issuer = mize.get_config("auth.issuer")?.value_string()?; let issuer = mize.get_config("auth.issuer")?.value_string()?;

View File

@@ -1,14 +1,12 @@
use dioxus::prelude::*; use dioxus::prelude::*;
use mize::Mize; use mize::Mize;
use crate::{ use generated::spacetime::{
generated::{ Action, ActivitiesTableAccess, Activity, DbConnection, TaskPart, TaskPartTableAccess,
Action, ActivitiesTableAccess, Activity, DbConnection, TaskPart, TaskPartTableAccess, activitiesQueryTableAccess, next_action, remove_activity, task_partQueryTableAccess,
activitiesQueryTableAccess, next_action, remove_activity, task_partQueryTableAccess, update_activity, update_upcoming,
update_activity, update_upcoming,
},
spacetime::SpacetimePart,
}; };
use marts::spacetime::SpacetimePart;
use spacetimedb_sdk::{ use spacetimedb_sdk::{
DbContext, Error, Event, Identity, Status, SubscriptionHandle, Table, TableWithPrimaryKey, DbContext, Error, Event, Identity, Status, SubscriptionHandle, Table, TableWithPrimaryKey,
credentials, 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::<Mize>();
let mut spacetime = mize.get_part_native::<SpacetimePart>("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() { pub fn launch_desktop_app() {
dioxus::launch(hello_world); 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::*; use dioxus::prelude::*;
/* /*

View File

@@ -1,27 +1,15 @@
use std::{io::Read, sync::oneshot, thread, time::Duration}; use std::sync::oneshot;
use clap::{Arg, ArgAction, ArgMatches, Command}; use clap::{Arg, ArgAction, ArgMatches, Command};
use mize::{Mize, MizeError, MizePart, MizePartGuard, MizeResult, mize_err, mize_part}; use mize::{Mize, MizeError, MizePart, MizePartCreate, MizeResult, mize_err, mize_part};
use spacetimedb_sdk::{ use spacetimedb_sdk::{DbContext, Table};
DbContext, Error, Event, Identity, Status, SubscriptionHandle, Table, TableWithPrimaryKey,
credentials,
};
use crate::{ use generated::spacetime::{
generated::{ Action, ActivitiesTableAccess, Activity, DbConnection, TaskPartTableAccess,
Action, ActivitiesTableAccess, Activity, DbConnection, TaskPartTableAccess, activitiesQueryTableAccess, next_action, remove_activity, task_partQueryTableAccess,
activitiesQueryTableAccess, next_action, remove_activity, task_partQueryTableAccess, update_activity, update_upcoming,
update_activity, update_upcoming,
},
spacetime::SpacetimePart,
};
const MizeConfig = mconf!{
hi "t"
rustBinary "hello" ''
println!("hello world");
''
}; };
use marts::spacetime::SpacetimePart;
#[mize_part] #[mize_part]
#[derive(Default)] #[derive(Default)]
@@ -58,10 +46,12 @@ pub fn timetrack(mize: &mut Mize) -> MizeResult<()> {
command_edit_activities, command_edit_activities,
); );
mize.register_part(Box::new(TimeTrack { mize: mize.clone() })); mize.register_part(Box::new(TimeTrack { mize: mize.clone() }))?;
Ok(()) Ok(())
} }
impl MizePartCreate for TimeTrack {}
impl MizePart for TimeTrack { impl MizePart for TimeTrack {
fn name(&self) -> &'static str { fn name(&self) -> &'static str {
"timetrack" "timetrack"
@@ -87,7 +77,7 @@ fn command_current_action(_: &ArgMatches, mut mize: Mize) -> MizeResult<()> {
Ok(()) Ok(())
} }
fn get_current_action(mize: &mut Mize, con: &DbConnection) -> MizeResult<Action> { fn get_current_action(_mize: &mut Mize, con: &DbConnection) -> MizeResult<Action> {
let (wait_tx, wait_rx) = std::sync::oneshot::channel::<Action>(); let (wait_tx, wait_rx) = std::sync::oneshot::channel::<Action>();
con.subscription_builder() con.subscription_builder()
.on_applied(|ctx| { .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())?; let mut actions = get_actions(spacetime.con())?;
// write to tmp file // 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!( let tmp_file = std::env::temp_dir().join(format!(
"ppc-edit-actions-{}.txt", "ppc-edit-actions-{}.txt",
chrono::Utc::now().timestamp() 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) let new_file_content = std::fs::read_to_string(&tmp_file)
.map_err(|e| mize_err!("Failed to read temp file: {}", e))?; .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())?; set_actions(actions, spacetime.con())?;
// delete tmpfile // delete tmpfile
@@ -224,7 +214,7 @@ fn actions_to_string(actions: &Vec<Action>) -> MizeResult<String> {
Ok(string) Ok(string)
} }
fn actions_from_string(mut old_actions: Vec<Action>, string: String) -> MizeResult<Vec<Action>> { fn actions_from_string(string: String) -> MizeResult<Vec<Action>> {
let mut new_actions = Vec::new(); let mut new_actions = Vec::new();
for line in string.lines() { for line in string.lines() {
if line.trim().is_empty() { if line.trim().is_empty() {
@@ -246,7 +236,7 @@ fn actions_from_string(mut old_actions: Vec<Action>, string: String) -> MizeResu
} }
fn parse_action(action: &mut Action) { 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<()> { fn command_edit_activities(_: &ArgMatches, mut mize: Mize) -> MizeResult<()> {
@@ -311,7 +301,7 @@ fn command_edit_activities(_: &ArgMatches, mut mize: Mize) -> MizeResult<()> {
Ok(()) Ok(())
} }
fn get_activities(mize: &mut Mize, con: &mut DbConnection) -> MizeResult<Vec<Activity>> { fn get_activities(_mize: &mut Mize, con: &mut DbConnection) -> MizeResult<Vec<Activity>> {
let (exit_tx, exit_rx) = std::sync::oneshot::channel::<Vec<Activity>>(); let (exit_tx, exit_rx) = std::sync::oneshot::channel::<Vec<Activity>>();
con.subscription_builder() con.subscription_builder()
.on_applied(|ctx| { .on_applied(|ctx| {
@@ -360,7 +350,7 @@ fn parse_activities_from_text(
parents_ids: old_activity.parents_ids.clone(), parents_ids: old_activity.parents_ids.clone(),
}, },
move |_, _| { move |_, _| {
wait_tx.send(()); let _ = wait_tx.send(());
}, },
)?; )?;
} else { } else {
@@ -372,7 +362,7 @@ fn parse_activities_from_text(
parents_ids: Vec::new(), parents_ids: Vec::new(),
}, },
move |_, _| { move |_, _| {
wait_tx.send(()); let _ = wait_tx.send(());
}, },
)?; )?;
} }
@@ -383,7 +373,7 @@ fn parse_activities_from_text(
let (wait_tx, wait_rx) = oneshot::channel::<()>(); let (wait_tx, wait_rx) = oneshot::channel::<()>();
wait_revievers.push(wait_rx); wait_revievers.push(wait_rx);
con.reducers.remove_activity_then(activity, move |_, _| { con.reducers.remove_activity_then(activity, move |_, _| {
wait_tx.send(()); let _ = wait_tx.send(());
})?; })?;
} }
@@ -403,7 +393,7 @@ fn parse_activities_from_text(
// split // split
let mut parts = line.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(); let name = parts.next().ok_or(mize_err!(".."))?.to_string();
// parse parents // parse parents
@@ -431,9 +421,9 @@ fn parse_activities_from_text(
..child_activity.to_owned() ..child_activity.to_owned()
}, },
move |_, _| { move |_, _| {
wait_tx.send(()); let _ = wait_tx.send(());
}, },
); )?;
} }
} }

View File

@@ -1,5 +1,5 @@
[package] [package]
name = "ppc-spacetime" name = "mize-spacetime"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"

View File

@@ -1,10 +1,5 @@
use std::task;
use log::*; use log::*;
use spacetimedb::{ use spacetimedb::{reducer, table, Identity, ReducerContext, Table, Timestamp};
reducer, table, view, Deserialize, Identity, ReducerContext, Serialize, SpacetimeType, Table,
Timestamp, ViewContext,
};
#[table(accessor = profiles, public)] #[table(accessor = profiles, public)]
pub struct Profile { pub struct Profile {