omega restructuring + a bunch of changes i have made over the last weeks
This commit is contained in:
@@ -1,11 +0,0 @@
|
||||
[package]
|
||||
name = "mize_macros"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
quote = "1.0.44"
|
||||
syn = "2.0.114"
|
||||
@@ -1,98 +0,0 @@
|
||||
use proc_macro::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::{Data, DeriveInput, Fields, parse_macro_input};
|
||||
|
||||
#[proc_macro_attribute]
|
||||
pub fn mize_part(attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(item as DeriveInput);
|
||||
let struct_name = &input.ident;
|
||||
|
||||
// Parse name from attribute
|
||||
let part_name = if !attr.is_empty() {
|
||||
let lit: syn::LitStr = parse_macro_input!(attr);
|
||||
lit.value()
|
||||
} else {
|
||||
struct_name.to_string().to_lowercase()
|
||||
};
|
||||
|
||||
// Verify mize field exists
|
||||
let has_mize = match &input.data {
|
||||
Data::Struct(s) => match &s.fields {
|
||||
Fields::Named(f) => f
|
||||
.named
|
||||
.iter()
|
||||
.any(|field| field.ident.as_ref().map(|i| i == "mize").unwrap_or(false)),
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
};
|
||||
|
||||
if !has_mize {
|
||||
return syn::Error::new_spanned(struct_name, "Struct must have a 'mize: Mize' field")
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
|
||||
let part_getter_fn_name_str = format!("make_mize_part_{}", part_name);
|
||||
let part_getter_fn_name = syn::Ident::new(&part_getter_fn_name_str, struct_name.span());
|
||||
|
||||
let expanded = quote! {
|
||||
#input
|
||||
|
||||
// impl the default new impl
|
||||
impl mize::MizePartGenerated for #struct_name {
|
||||
fn name_generated(&self) -> &'static str {
|
||||
#part_name
|
||||
}
|
||||
fn get_mize_generated(&mut self) -> &mut Mize {
|
||||
&mut self.mize
|
||||
}
|
||||
fn as_any_generated(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
fn as_any_mut_generated(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
fn into_any_generated(self: Box<Self>) -> Box<dyn std::any::Any> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl mize::MizePartCreateGenerated for #struct_name {
|
||||
fn create_generated(mize: Mize) -> Self {
|
||||
Self {
|
||||
mize,
|
||||
.. Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use mize::instance::MizePartCreateThisSucks;
|
||||
|
||||
impl MizePartCreateThisSucks for #struct_name {}
|
||||
|
||||
// the function to get the part from a .so file
|
||||
#[unsafe(no_mangle)]
|
||||
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> {
|
||||
type Target = #struct_name;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&*self.part.as_ref().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::DerefMut for mize::MizePartGuard<#struct_name> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut *self.part.as_mut().unwrap()
|
||||
}
|
||||
}
|
||||
*/
|
||||
};
|
||||
|
||||
TokenStream::from(expanded)
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
[package]
|
||||
name = "generated"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
name = "generated"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
spacetimedb-sdk = "2.1.0"
|
||||
@@ -1,2 +0,0 @@
|
||||
pub mod spacetime;
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
|
||||
#[sats(crate = __lib)]
|
||||
pub struct Action {
|
||||
pub name: String,
|
||||
pub activity: Option<u64>,
|
||||
pub task: Option<u64>,
|
||||
pub start: Option<__sdk::Timestamp>,
|
||||
pub end: Option<__sdk::Timestamp>,
|
||||
pub duration: Option<u64>,
|
||||
}
|
||||
|
||||
impl __sdk::InModule for Action {
|
||||
type Module = super::RemoteModule;
|
||||
}
|
||||
|
||||
/// Column accessor struct for the table `Action`.
|
||||
///
|
||||
/// Provides typed access to columns for query building.
|
||||
pub struct ActionCols {
|
||||
pub name: __sdk::__query_builder::Col<Action, String>,
|
||||
pub activity: __sdk::__query_builder::Col<Action, Option<u64>>,
|
||||
pub task: __sdk::__query_builder::Col<Action, Option<u64>>,
|
||||
pub start: __sdk::__query_builder::Col<Action, Option<__sdk::Timestamp>>,
|
||||
pub end: __sdk::__query_builder::Col<Action, Option<__sdk::Timestamp>>,
|
||||
pub duration: __sdk::__query_builder::Col<Action, Option<u64>>,
|
||||
}
|
||||
|
||||
impl __sdk::__query_builder::HasCols for Action {
|
||||
type Cols = ActionCols;
|
||||
fn cols(table_name: &'static str) -> Self::Cols {
|
||||
ActionCols {
|
||||
name: __sdk::__query_builder::Col::new(table_name, "name"),
|
||||
activity: __sdk::__query_builder::Col::new(table_name, "activity"),
|
||||
task: __sdk::__query_builder::Col::new(table_name, "task"),
|
||||
start: __sdk::__query_builder::Col::new(table_name, "start"),
|
||||
end: __sdk::__query_builder::Col::new(table_name, "end"),
|
||||
duration: __sdk::__query_builder::Col::new(table_name, "duration"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Indexed column accessor struct for the table `Action`.
|
||||
///
|
||||
/// Provides typed access to indexed columns for query building.
|
||||
pub struct ActionIxCols {}
|
||||
|
||||
impl __sdk::__query_builder::HasIxCols for Action {
|
||||
type IxCols = ActionIxCols;
|
||||
fn ix_cols(table_name: &'static str) -> Self::IxCols {
|
||||
ActionIxCols {}
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::__query_builder::CanBeLookupTable for Action {}
|
||||
@@ -1,159 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use super::activity_type::Activity;
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
/// Table handle for the table `activities`.
|
||||
///
|
||||
/// Obtain a handle from the [`ActivitiesTableAccess::activities`] method on [`super::RemoteTables`],
|
||||
/// like `ctx.db.activities()`.
|
||||
///
|
||||
/// Users are encouraged not to explicitly reference this type,
|
||||
/// but to directly chain method calls,
|
||||
/// like `ctx.db.activities().on_insert(...)`.
|
||||
pub struct ActivitiesTableHandle<'ctx> {
|
||||
imp: __sdk::TableHandle<Activity>,
|
||||
ctx: std::marker::PhantomData<&'ctx super::RemoteTables>,
|
||||
}
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
/// Extension trait for access to the table `activities`.
|
||||
///
|
||||
/// Implemented for [`super::RemoteTables`].
|
||||
pub trait ActivitiesTableAccess {
|
||||
#[allow(non_snake_case)]
|
||||
/// Obtain a [`ActivitiesTableHandle`], which mediates access to the table `activities`.
|
||||
fn activities(&self) -> ActivitiesTableHandle<'_>;
|
||||
}
|
||||
|
||||
impl ActivitiesTableAccess for super::RemoteTables {
|
||||
fn activities(&self) -> ActivitiesTableHandle<'_> {
|
||||
ActivitiesTableHandle {
|
||||
imp: self.imp.get_table::<Activity>("activities"),
|
||||
ctx: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ActivitiesInsertCallbackId(__sdk::CallbackId);
|
||||
pub struct ActivitiesDeleteCallbackId(__sdk::CallbackId);
|
||||
|
||||
impl<'ctx> __sdk::Table for ActivitiesTableHandle<'ctx> {
|
||||
type Row = Activity;
|
||||
type EventContext = super::EventContext;
|
||||
|
||||
fn count(&self) -> u64 {
|
||||
self.imp.count()
|
||||
}
|
||||
fn iter(&self) -> impl Iterator<Item = Activity> + '_ {
|
||||
self.imp.iter()
|
||||
}
|
||||
|
||||
type InsertCallbackId = ActivitiesInsertCallbackId;
|
||||
|
||||
fn on_insert(
|
||||
&self,
|
||||
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
|
||||
) -> ActivitiesInsertCallbackId {
|
||||
ActivitiesInsertCallbackId(self.imp.on_insert(Box::new(callback)))
|
||||
}
|
||||
|
||||
fn remove_on_insert(&self, callback: ActivitiesInsertCallbackId) {
|
||||
self.imp.remove_on_insert(callback.0)
|
||||
}
|
||||
|
||||
type DeleteCallbackId = ActivitiesDeleteCallbackId;
|
||||
|
||||
fn on_delete(
|
||||
&self,
|
||||
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
|
||||
) -> ActivitiesDeleteCallbackId {
|
||||
ActivitiesDeleteCallbackId(self.imp.on_delete(Box::new(callback)))
|
||||
}
|
||||
|
||||
fn remove_on_delete(&self, callback: ActivitiesDeleteCallbackId) {
|
||||
self.imp.remove_on_delete(callback.0)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ActivitiesUpdateCallbackId(__sdk::CallbackId);
|
||||
|
||||
impl<'ctx> __sdk::TableWithPrimaryKey for ActivitiesTableHandle<'ctx> {
|
||||
type UpdateCallbackId = ActivitiesUpdateCallbackId;
|
||||
|
||||
fn on_update(
|
||||
&self,
|
||||
callback: impl FnMut(&Self::EventContext, &Self::Row, &Self::Row) + Send + 'static,
|
||||
) -> ActivitiesUpdateCallbackId {
|
||||
ActivitiesUpdateCallbackId(self.imp.on_update(Box::new(callback)))
|
||||
}
|
||||
|
||||
fn remove_on_update(&self, callback: ActivitiesUpdateCallbackId) {
|
||||
self.imp.remove_on_update(callback.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Access to the `id` unique index on the table `activities`,
|
||||
/// which allows point queries on the field of the same name
|
||||
/// via the [`ActivitiesIdUnique::find`] method.
|
||||
///
|
||||
/// Users are encouraged not to explicitly reference this type,
|
||||
/// but to directly chain method calls,
|
||||
/// like `ctx.db.activities().id().find(...)`.
|
||||
pub struct ActivitiesIdUnique<'ctx> {
|
||||
imp: __sdk::UniqueConstraintHandle<Activity, u64>,
|
||||
phantom: std::marker::PhantomData<&'ctx super::RemoteTables>,
|
||||
}
|
||||
|
||||
impl<'ctx> ActivitiesTableHandle<'ctx> {
|
||||
/// Get a handle on the `id` unique index on the table `activities`.
|
||||
pub fn id(&self) -> ActivitiesIdUnique<'ctx> {
|
||||
ActivitiesIdUnique {
|
||||
imp: self.imp.get_unique_constraint::<u64>("id"),
|
||||
phantom: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ctx> ActivitiesIdUnique<'ctx> {
|
||||
/// Find the subscribed row whose `id` column value is equal to `col_val`,
|
||||
/// if such a row is present in the client cache.
|
||||
pub fn find(&self, col_val: &u64) -> Option<Activity> {
|
||||
self.imp.find(col_val)
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub(super) fn register_table(client_cache: &mut __sdk::ClientCache<super::RemoteModule>) {
|
||||
let _table = client_cache.get_or_make_table::<Activity>("activities");
|
||||
_table.add_unique_constraint::<u64>("id", |row| &row.id);
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub(super) fn parse_table_update(
|
||||
raw_updates: __ws::v2::TableUpdate,
|
||||
) -> __sdk::Result<__sdk::TableUpdate<Activity>> {
|
||||
__sdk::TableUpdate::parse_table_update(raw_updates).map_err(|e| {
|
||||
__sdk::InternalError::failed_parse("TableUpdate<Activity>", "TableUpdate")
|
||||
.with_cause(e)
|
||||
.into()
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
/// Extension trait for query builder access to the table `Activity`.
|
||||
///
|
||||
/// Implemented for [`__sdk::QueryTableAccessor`].
|
||||
pub trait activitiesQueryTableAccess {
|
||||
#[allow(non_snake_case)]
|
||||
/// Get a query builder for the table `Activity`.
|
||||
fn activities(&self) -> __sdk::__query_builder::Table<Activity>;
|
||||
}
|
||||
|
||||
impl activitiesQueryTableAccess for __sdk::QueryTableAccessor {
|
||||
fn activities(&self) -> __sdk::__query_builder::Table<Activity> {
|
||||
__sdk::__query_builder::Table::new("activities")
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
|
||||
#[sats(crate = __lib)]
|
||||
pub struct Activity {
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
pub task: Option<u64>,
|
||||
pub parents_ids: Vec<u64>,
|
||||
}
|
||||
|
||||
impl __sdk::InModule for Activity {
|
||||
type Module = super::RemoteModule;
|
||||
}
|
||||
|
||||
/// Column accessor struct for the table `Activity`.
|
||||
///
|
||||
/// Provides typed access to columns for query building.
|
||||
pub struct ActivityCols {
|
||||
pub id: __sdk::__query_builder::Col<Activity, u64>,
|
||||
pub name: __sdk::__query_builder::Col<Activity, String>,
|
||||
pub task: __sdk::__query_builder::Col<Activity, Option<u64>>,
|
||||
pub parents_ids: __sdk::__query_builder::Col<Activity, Vec<u64>>,
|
||||
}
|
||||
|
||||
impl __sdk::__query_builder::HasCols for Activity {
|
||||
type Cols = ActivityCols;
|
||||
fn cols(table_name: &'static str) -> Self::Cols {
|
||||
ActivityCols {
|
||||
id: __sdk::__query_builder::Col::new(table_name, "id"),
|
||||
name: __sdk::__query_builder::Col::new(table_name, "name"),
|
||||
task: __sdk::__query_builder::Col::new(table_name, "task"),
|
||||
parents_ids: __sdk::__query_builder::Col::new(table_name, "parents_ids"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Indexed column accessor struct for the table `Activity`.
|
||||
///
|
||||
/// Provides typed access to indexed columns for query building.
|
||||
pub struct ActivityIxCols {
|
||||
pub id: __sdk::__query_builder::IxCol<Activity, u64>,
|
||||
}
|
||||
|
||||
impl __sdk::__query_builder::HasIxCols for Activity {
|
||||
type IxCols = ActivityIxCols;
|
||||
fn ix_cols(table_name: &'static str) -> Self::IxCols {
|
||||
ActivityIxCols {
|
||||
id: __sdk::__query_builder::IxCol::new(table_name, "id"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::__query_builder::CanBeLookupTable for Activity {}
|
||||
@@ -1,66 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
|
||||
#[sats(crate = __lib)]
|
||||
pub(super) struct AddActivityArgs {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl From<AddActivityArgs> for super::Reducer {
|
||||
fn from(args: AddActivityArgs) -> Self {
|
||||
Self::AddActivity { name: args.name }
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::InModule for AddActivityArgs {
|
||||
type Module = super::RemoteModule;
|
||||
}
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
/// Extension trait for access to the reducer `add_activity`.
|
||||
///
|
||||
/// Implemented for [`super::RemoteReducers`].
|
||||
pub trait add_activity {
|
||||
/// Request that the remote module invoke the reducer `add_activity` to run as soon as possible.
|
||||
///
|
||||
/// This method returns immediately, and errors only if we are unable to send the request.
|
||||
/// The reducer will run asynchronously in the future,
|
||||
/// and this method provides no way to listen for its completion status.
|
||||
/// /// Use [`add_activity:add_activity_then`] to run a callback after the reducer completes.
|
||||
fn add_activity(&self, name: String) -> __sdk::Result<()> {
|
||||
self.add_activity_then(name, |_, _| {})
|
||||
}
|
||||
|
||||
/// Request that the remote module invoke the reducer `add_activity` to run as soon as possible,
|
||||
/// registering `callback` to run when we are notified that the reducer completed.
|
||||
///
|
||||
/// This method returns immediately, and errors only if we are unable to send the request.
|
||||
/// The reducer will run asynchronously in the future,
|
||||
/// and its status can be observed with the `callback`.
|
||||
fn add_activity_then(
|
||||
&self,
|
||||
name: String,
|
||||
|
||||
callback: impl FnOnce(&super::ReducerEventContext, Result<Result<(), String>, __sdk::InternalError>)
|
||||
+ Send
|
||||
+ 'static,
|
||||
) -> __sdk::Result<()>;
|
||||
}
|
||||
|
||||
impl add_activity for super::RemoteReducers {
|
||||
fn add_activity_then(
|
||||
&self,
|
||||
name: String,
|
||||
|
||||
callback: impl FnOnce(&super::ReducerEventContext, Result<Result<(), String>, __sdk::InternalError>)
|
||||
+ Send
|
||||
+ 'static,
|
||||
) -> __sdk::Result<()> {
|
||||
self.imp
|
||||
.invoke_reducer_with_callback(AddActivityArgs { name }, callback)
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
use super::action_type::Action;
|
||||
|
||||
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
|
||||
#[sats(crate = __lib)]
|
||||
pub struct LogEvent {
|
||||
pub id: u64,
|
||||
pub start: __sdk::Timestamp,
|
||||
pub end: __sdk::Timestamp,
|
||||
pub action: Action,
|
||||
}
|
||||
|
||||
impl __sdk::InModule for LogEvent {
|
||||
type Module = super::RemoteModule;
|
||||
}
|
||||
|
||||
/// Column accessor struct for the table `LogEvent`.
|
||||
///
|
||||
/// Provides typed access to columns for query building.
|
||||
pub struct LogEventCols {
|
||||
pub id: __sdk::__query_builder::Col<LogEvent, u64>,
|
||||
pub start: __sdk::__query_builder::Col<LogEvent, __sdk::Timestamp>,
|
||||
pub end: __sdk::__query_builder::Col<LogEvent, __sdk::Timestamp>,
|
||||
pub action: __sdk::__query_builder::Col<LogEvent, Action>,
|
||||
}
|
||||
|
||||
impl __sdk::__query_builder::HasCols for LogEvent {
|
||||
type Cols = LogEventCols;
|
||||
fn cols(table_name: &'static str) -> Self::Cols {
|
||||
LogEventCols {
|
||||
id: __sdk::__query_builder::Col::new(table_name, "id"),
|
||||
start: __sdk::__query_builder::Col::new(table_name, "start"),
|
||||
end: __sdk::__query_builder::Col::new(table_name, "end"),
|
||||
action: __sdk::__query_builder::Col::new(table_name, "action"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Indexed column accessor struct for the table `LogEvent`.
|
||||
///
|
||||
/// Provides typed access to indexed columns for query building.
|
||||
pub struct LogEventIxCols {
|
||||
pub id: __sdk::__query_builder::IxCol<LogEvent, u64>,
|
||||
}
|
||||
|
||||
impl __sdk::__query_builder::HasIxCols for LogEvent {
|
||||
type IxCols = LogEventIxCols;
|
||||
fn ix_cols(table_name: &'static str) -> Self::IxCols {
|
||||
LogEventIxCols {
|
||||
id: __sdk::__query_builder::IxCol::new(table_name, "id"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::__query_builder::CanBeLookupTable for LogEvent {}
|
||||
@@ -1,160 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use super::action_type::Action;
|
||||
use super::log_event_type::LogEvent;
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
/// Table handle for the table `log_events`.
|
||||
///
|
||||
/// Obtain a handle from the [`LogEventsTableAccess::log_events`] method on [`super::RemoteTables`],
|
||||
/// like `ctx.db.log_events()`.
|
||||
///
|
||||
/// Users are encouraged not to explicitly reference this type,
|
||||
/// but to directly chain method calls,
|
||||
/// like `ctx.db.log_events().on_insert(...)`.
|
||||
pub struct LogEventsTableHandle<'ctx> {
|
||||
imp: __sdk::TableHandle<LogEvent>,
|
||||
ctx: std::marker::PhantomData<&'ctx super::RemoteTables>,
|
||||
}
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
/// Extension trait for access to the table `log_events`.
|
||||
///
|
||||
/// Implemented for [`super::RemoteTables`].
|
||||
pub trait LogEventsTableAccess {
|
||||
#[allow(non_snake_case)]
|
||||
/// Obtain a [`LogEventsTableHandle`], which mediates access to the table `log_events`.
|
||||
fn log_events(&self) -> LogEventsTableHandle<'_>;
|
||||
}
|
||||
|
||||
impl LogEventsTableAccess for super::RemoteTables {
|
||||
fn log_events(&self) -> LogEventsTableHandle<'_> {
|
||||
LogEventsTableHandle {
|
||||
imp: self.imp.get_table::<LogEvent>("log_events"),
|
||||
ctx: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct LogEventsInsertCallbackId(__sdk::CallbackId);
|
||||
pub struct LogEventsDeleteCallbackId(__sdk::CallbackId);
|
||||
|
||||
impl<'ctx> __sdk::Table for LogEventsTableHandle<'ctx> {
|
||||
type Row = LogEvent;
|
||||
type EventContext = super::EventContext;
|
||||
|
||||
fn count(&self) -> u64 {
|
||||
self.imp.count()
|
||||
}
|
||||
fn iter(&self) -> impl Iterator<Item = LogEvent> + '_ {
|
||||
self.imp.iter()
|
||||
}
|
||||
|
||||
type InsertCallbackId = LogEventsInsertCallbackId;
|
||||
|
||||
fn on_insert(
|
||||
&self,
|
||||
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
|
||||
) -> LogEventsInsertCallbackId {
|
||||
LogEventsInsertCallbackId(self.imp.on_insert(Box::new(callback)))
|
||||
}
|
||||
|
||||
fn remove_on_insert(&self, callback: LogEventsInsertCallbackId) {
|
||||
self.imp.remove_on_insert(callback.0)
|
||||
}
|
||||
|
||||
type DeleteCallbackId = LogEventsDeleteCallbackId;
|
||||
|
||||
fn on_delete(
|
||||
&self,
|
||||
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
|
||||
) -> LogEventsDeleteCallbackId {
|
||||
LogEventsDeleteCallbackId(self.imp.on_delete(Box::new(callback)))
|
||||
}
|
||||
|
||||
fn remove_on_delete(&self, callback: LogEventsDeleteCallbackId) {
|
||||
self.imp.remove_on_delete(callback.0)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct LogEventsUpdateCallbackId(__sdk::CallbackId);
|
||||
|
||||
impl<'ctx> __sdk::TableWithPrimaryKey for LogEventsTableHandle<'ctx> {
|
||||
type UpdateCallbackId = LogEventsUpdateCallbackId;
|
||||
|
||||
fn on_update(
|
||||
&self,
|
||||
callback: impl FnMut(&Self::EventContext, &Self::Row, &Self::Row) + Send + 'static,
|
||||
) -> LogEventsUpdateCallbackId {
|
||||
LogEventsUpdateCallbackId(self.imp.on_update(Box::new(callback)))
|
||||
}
|
||||
|
||||
fn remove_on_update(&self, callback: LogEventsUpdateCallbackId) {
|
||||
self.imp.remove_on_update(callback.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Access to the `id` unique index on the table `log_events`,
|
||||
/// which allows point queries on the field of the same name
|
||||
/// via the [`LogEventsIdUnique::find`] method.
|
||||
///
|
||||
/// Users are encouraged not to explicitly reference this type,
|
||||
/// but to directly chain method calls,
|
||||
/// like `ctx.db.log_events().id().find(...)`.
|
||||
pub struct LogEventsIdUnique<'ctx> {
|
||||
imp: __sdk::UniqueConstraintHandle<LogEvent, u64>,
|
||||
phantom: std::marker::PhantomData<&'ctx super::RemoteTables>,
|
||||
}
|
||||
|
||||
impl<'ctx> LogEventsTableHandle<'ctx> {
|
||||
/// Get a handle on the `id` unique index on the table `log_events`.
|
||||
pub fn id(&self) -> LogEventsIdUnique<'ctx> {
|
||||
LogEventsIdUnique {
|
||||
imp: self.imp.get_unique_constraint::<u64>("id"),
|
||||
phantom: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ctx> LogEventsIdUnique<'ctx> {
|
||||
/// Find the subscribed row whose `id` column value is equal to `col_val`,
|
||||
/// if such a row is present in the client cache.
|
||||
pub fn find(&self, col_val: &u64) -> Option<LogEvent> {
|
||||
self.imp.find(col_val)
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub(super) fn register_table(client_cache: &mut __sdk::ClientCache<super::RemoteModule>) {
|
||||
let _table = client_cache.get_or_make_table::<LogEvent>("log_events");
|
||||
_table.add_unique_constraint::<u64>("id", |row| &row.id);
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub(super) fn parse_table_update(
|
||||
raw_updates: __ws::v2::TableUpdate,
|
||||
) -> __sdk::Result<__sdk::TableUpdate<LogEvent>> {
|
||||
__sdk::TableUpdate::parse_table_update(raw_updates).map_err(|e| {
|
||||
__sdk::InternalError::failed_parse("TableUpdate<LogEvent>", "TableUpdate")
|
||||
.with_cause(e)
|
||||
.into()
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
/// Extension trait for query builder access to the table `LogEvent`.
|
||||
///
|
||||
/// Implemented for [`__sdk::QueryTableAccessor`].
|
||||
pub trait log_eventsQueryTableAccess {
|
||||
#[allow(non_snake_case)]
|
||||
/// Get a query builder for the table `LogEvent`.
|
||||
fn log_events(&self) -> __sdk::__query_builder::Table<LogEvent>;
|
||||
}
|
||||
|
||||
impl log_eventsQueryTableAccess for __sdk::QueryTableAccessor {
|
||||
fn log_events(&self) -> __sdk::__query_builder::Table<LogEvent> {
|
||||
__sdk::__query_builder::Table::new("log_events")
|
||||
}
|
||||
}
|
||||
@@ -1,939 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
// This was generated using spacetimedb cli version 2.1.0 (commit refs/tags/v2.1.0).
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
pub mod action_type;
|
||||
pub mod activities_table;
|
||||
pub mod activity_type;
|
||||
pub mod add_activity_reducer;
|
||||
pub mod log_event_type;
|
||||
pub mod log_events_table;
|
||||
pub mod next_action_reducer;
|
||||
pub mod profile_type;
|
||||
pub mod profiles_table;
|
||||
pub mod remove_activity_reducer;
|
||||
pub mod set_activity_name_reducer;
|
||||
pub mod task_part_table;
|
||||
pub mod task_part_type;
|
||||
pub mod task_type;
|
||||
pub mod tasks_table;
|
||||
pub mod update_activity_reducer;
|
||||
pub mod update_upcoming_reducer;
|
||||
|
||||
pub use action_type::Action;
|
||||
pub use activities_table::*;
|
||||
pub use activity_type::Activity;
|
||||
pub use add_activity_reducer::add_activity;
|
||||
pub use log_event_type::LogEvent;
|
||||
pub use log_events_table::*;
|
||||
pub use next_action_reducer::next_action;
|
||||
pub use profile_type::Profile;
|
||||
pub use profiles_table::*;
|
||||
pub use remove_activity_reducer::remove_activity;
|
||||
pub use set_activity_name_reducer::set_activity_name;
|
||||
pub use task_part_table::*;
|
||||
pub use task_part_type::TaskPart;
|
||||
pub use task_type::Task;
|
||||
pub use tasks_table::*;
|
||||
pub use update_activity_reducer::update_activity;
|
||||
pub use update_upcoming_reducer::update_upcoming;
|
||||
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
|
||||
/// One of the reducers defined by this module.
|
||||
///
|
||||
/// Contained within a [`__sdk::ReducerEvent`] in [`EventContext`]s for reducer events
|
||||
/// to indicate which reducer caused the event.
|
||||
|
||||
pub enum Reducer {
|
||||
AddActivity { name: String },
|
||||
NextAction,
|
||||
RemoveActivity { activity: Activity },
|
||||
SetActivityName { id: u64, name: String },
|
||||
UpdateActivity { activity: Activity },
|
||||
UpdateUpcoming { upcoming: Vec<Action> },
|
||||
}
|
||||
|
||||
impl __sdk::InModule for Reducer {
|
||||
type Module = RemoteModule;
|
||||
}
|
||||
|
||||
impl __sdk::Reducer for Reducer {
|
||||
fn reducer_name(&self) -> &'static str {
|
||||
match self {
|
||||
Reducer::AddActivity { .. } => "add_activity",
|
||||
Reducer::NextAction => "next_action",
|
||||
Reducer::RemoveActivity { .. } => "remove_activity",
|
||||
Reducer::SetActivityName { .. } => "set_activity_name",
|
||||
Reducer::UpdateActivity { .. } => "update_activity",
|
||||
Reducer::UpdateUpcoming { .. } => "update_upcoming",
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
#[allow(clippy::clone_on_copy)]
|
||||
fn args_bsatn(&self) -> Result<Vec<u8>, __sats::bsatn::EncodeError> {
|
||||
match self {
|
||||
Reducer::AddActivity { name } => {
|
||||
__sats::bsatn::to_vec(&add_activity_reducer::AddActivityArgs { name: name.clone() })
|
||||
}
|
||||
Reducer::NextAction => __sats::bsatn::to_vec(&next_action_reducer::NextActionArgs {}),
|
||||
Reducer::RemoveActivity { activity } => {
|
||||
__sats::bsatn::to_vec(&remove_activity_reducer::RemoveActivityArgs {
|
||||
activity: activity.clone(),
|
||||
})
|
||||
}
|
||||
Reducer::SetActivityName { id, name } => {
|
||||
__sats::bsatn::to_vec(&set_activity_name_reducer::SetActivityNameArgs {
|
||||
id: id.clone(),
|
||||
name: name.clone(),
|
||||
})
|
||||
}
|
||||
Reducer::UpdateActivity { activity } => {
|
||||
__sats::bsatn::to_vec(&update_activity_reducer::UpdateActivityArgs {
|
||||
activity: activity.clone(),
|
||||
})
|
||||
}
|
||||
Reducer::UpdateUpcoming { upcoming } => {
|
||||
__sats::bsatn::to_vec(&update_upcoming_reducer::UpdateUpcomingArgs {
|
||||
upcoming: upcoming.clone(),
|
||||
})
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
#[allow(non_snake_case)]
|
||||
#[doc(hidden)]
|
||||
pub struct DbUpdate {
|
||||
activities: __sdk::TableUpdate<Activity>,
|
||||
log_events: __sdk::TableUpdate<LogEvent>,
|
||||
profiles: __sdk::TableUpdate<Profile>,
|
||||
task_part: __sdk::TableUpdate<TaskPart>,
|
||||
tasks: __sdk::TableUpdate<Task>,
|
||||
}
|
||||
|
||||
impl TryFrom<__ws::v2::TransactionUpdate> for DbUpdate {
|
||||
type Error = __sdk::Error;
|
||||
fn try_from(raw: __ws::v2::TransactionUpdate) -> Result<Self, Self::Error> {
|
||||
let mut db_update = DbUpdate::default();
|
||||
for table_update in __sdk::transaction_update_iter_table_updates(raw) {
|
||||
match &table_update.table_name[..] {
|
||||
"activities" => db_update
|
||||
.activities
|
||||
.append(activities_table::parse_table_update(table_update)?),
|
||||
"log_events" => db_update
|
||||
.log_events
|
||||
.append(log_events_table::parse_table_update(table_update)?),
|
||||
"profiles" => db_update
|
||||
.profiles
|
||||
.append(profiles_table::parse_table_update(table_update)?),
|
||||
"task_part" => db_update
|
||||
.task_part
|
||||
.append(task_part_table::parse_table_update(table_update)?),
|
||||
"tasks" => db_update
|
||||
.tasks
|
||||
.append(tasks_table::parse_table_update(table_update)?),
|
||||
|
||||
unknown => {
|
||||
return Err(__sdk::InternalError::unknown_name(
|
||||
"table",
|
||||
unknown,
|
||||
"DatabaseUpdate",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(db_update)
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::InModule for DbUpdate {
|
||||
type Module = RemoteModule;
|
||||
}
|
||||
|
||||
impl __sdk::DbUpdate for DbUpdate {
|
||||
fn apply_to_client_cache(
|
||||
&self,
|
||||
cache: &mut __sdk::ClientCache<RemoteModule>,
|
||||
) -> AppliedDiff<'_> {
|
||||
let mut diff = AppliedDiff::default();
|
||||
|
||||
diff.activities = cache
|
||||
.apply_diff_to_table::<Activity>("activities", &self.activities)
|
||||
.with_updates_by_pk(|row| &row.id);
|
||||
diff.log_events = cache
|
||||
.apply_diff_to_table::<LogEvent>("log_events", &self.log_events)
|
||||
.with_updates_by_pk(|row| &row.id);
|
||||
diff.profiles = cache
|
||||
.apply_diff_to_table::<Profile>("profiles", &self.profiles)
|
||||
.with_updates_by_pk(|row| &row.identity);
|
||||
diff.task_part = cache
|
||||
.apply_diff_to_table::<TaskPart>("task_part", &self.task_part)
|
||||
.with_updates_by_pk(|row| &row.identity);
|
||||
diff.tasks = cache
|
||||
.apply_diff_to_table::<Task>("tasks", &self.tasks)
|
||||
.with_updates_by_pk(|row| &row.id);
|
||||
|
||||
diff
|
||||
}
|
||||
fn parse_initial_rows(raw: __ws::v2::QueryRows) -> __sdk::Result<Self> {
|
||||
let mut db_update = DbUpdate::default();
|
||||
for table_rows in raw.tables {
|
||||
match &table_rows.table[..] {
|
||||
"activities" => db_update
|
||||
.activities
|
||||
.append(__sdk::parse_row_list_as_inserts(table_rows.rows)?),
|
||||
"log_events" => db_update
|
||||
.log_events
|
||||
.append(__sdk::parse_row_list_as_inserts(table_rows.rows)?),
|
||||
"profiles" => db_update
|
||||
.profiles
|
||||
.append(__sdk::parse_row_list_as_inserts(table_rows.rows)?),
|
||||
"task_part" => db_update
|
||||
.task_part
|
||||
.append(__sdk::parse_row_list_as_inserts(table_rows.rows)?),
|
||||
"tasks" => db_update
|
||||
.tasks
|
||||
.append(__sdk::parse_row_list_as_inserts(table_rows.rows)?),
|
||||
unknown => {
|
||||
return Err(
|
||||
__sdk::InternalError::unknown_name("table", unknown, "QueryRows").into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(db_update)
|
||||
}
|
||||
fn parse_unsubscribe_rows(raw: __ws::v2::QueryRows) -> __sdk::Result<Self> {
|
||||
let mut db_update = DbUpdate::default();
|
||||
for table_rows in raw.tables {
|
||||
match &table_rows.table[..] {
|
||||
"activities" => db_update
|
||||
.activities
|
||||
.append(__sdk::parse_row_list_as_deletes(table_rows.rows)?),
|
||||
"log_events" => db_update
|
||||
.log_events
|
||||
.append(__sdk::parse_row_list_as_deletes(table_rows.rows)?),
|
||||
"profiles" => db_update
|
||||
.profiles
|
||||
.append(__sdk::parse_row_list_as_deletes(table_rows.rows)?),
|
||||
"task_part" => db_update
|
||||
.task_part
|
||||
.append(__sdk::parse_row_list_as_deletes(table_rows.rows)?),
|
||||
"tasks" => db_update
|
||||
.tasks
|
||||
.append(__sdk::parse_row_list_as_deletes(table_rows.rows)?),
|
||||
unknown => {
|
||||
return Err(
|
||||
__sdk::InternalError::unknown_name("table", unknown, "QueryRows").into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(db_update)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
#[allow(non_snake_case)]
|
||||
#[doc(hidden)]
|
||||
pub struct AppliedDiff<'r> {
|
||||
activities: __sdk::TableAppliedDiff<'r, Activity>,
|
||||
log_events: __sdk::TableAppliedDiff<'r, LogEvent>,
|
||||
profiles: __sdk::TableAppliedDiff<'r, Profile>,
|
||||
task_part: __sdk::TableAppliedDiff<'r, TaskPart>,
|
||||
tasks: __sdk::TableAppliedDiff<'r, Task>,
|
||||
__unused: std::marker::PhantomData<&'r ()>,
|
||||
}
|
||||
|
||||
impl __sdk::InModule for AppliedDiff<'_> {
|
||||
type Module = RemoteModule;
|
||||
}
|
||||
|
||||
impl<'r> __sdk::AppliedDiff<'r> for AppliedDiff<'r> {
|
||||
fn invoke_row_callbacks(
|
||||
&self,
|
||||
event: &EventContext,
|
||||
callbacks: &mut __sdk::DbCallbacks<RemoteModule>,
|
||||
) {
|
||||
callbacks.invoke_table_row_callbacks::<Activity>("activities", &self.activities, event);
|
||||
callbacks.invoke_table_row_callbacks::<LogEvent>("log_events", &self.log_events, event);
|
||||
callbacks.invoke_table_row_callbacks::<Profile>("profiles", &self.profiles, event);
|
||||
callbacks.invoke_table_row_callbacks::<TaskPart>("task_part", &self.task_part, event);
|
||||
callbacks.invoke_table_row_callbacks::<Task>("tasks", &self.tasks, event);
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
#[derive(Debug)]
|
||||
pub struct RemoteModule;
|
||||
|
||||
impl __sdk::InModule for RemoteModule {
|
||||
type Module = Self;
|
||||
}
|
||||
|
||||
/// The `reducers` field of [`EventContext`] and [`DbConnection`],
|
||||
/// with methods provided by extension traits for each reducer defined by the module.
|
||||
pub struct RemoteReducers {
|
||||
imp: __sdk::DbContextImpl<RemoteModule>,
|
||||
}
|
||||
|
||||
impl __sdk::InModule for RemoteReducers {
|
||||
type Module = RemoteModule;
|
||||
}
|
||||
|
||||
/// The `procedures` field of [`DbConnection`] and other [`DbContext`] types,
|
||||
/// with methods provided by extension traits for each procedure defined by the module.
|
||||
pub struct RemoteProcedures {
|
||||
imp: __sdk::DbContextImpl<RemoteModule>,
|
||||
}
|
||||
|
||||
impl __sdk::InModule for RemoteProcedures {
|
||||
type Module = RemoteModule;
|
||||
}
|
||||
|
||||
/// The `db` field of [`EventContext`] and [`DbConnection`],
|
||||
/// with methods provided by extension traits for each table defined by the module.
|
||||
pub struct RemoteTables {
|
||||
imp: __sdk::DbContextImpl<RemoteModule>,
|
||||
}
|
||||
|
||||
impl __sdk::InModule for RemoteTables {
|
||||
type Module = RemoteModule;
|
||||
}
|
||||
|
||||
/// A connection to a remote module, including a materialized view of a subset of the database.
|
||||
///
|
||||
/// Connect to a remote module by calling [`DbConnection::builder`]
|
||||
/// and using the [`__sdk::DbConnectionBuilder`] builder-pattern constructor.
|
||||
///
|
||||
/// You must explicitly advance the connection by calling any one of:
|
||||
///
|
||||
/// - [`DbConnection::frame_tick`].
|
||||
#[cfg_attr(not(target_arch = "wasm32"), doc = "- [`DbConnection::run_threaded`].")]
|
||||
#[cfg_attr(
|
||||
target_arch = "wasm32",
|
||||
doc = "- [`DbConnection::run_background_task`]."
|
||||
)]
|
||||
/// - [`DbConnection::run_async`].
|
||||
/// - [`DbConnection::advance_one_message`].
|
||||
#[cfg_attr(
|
||||
not(target_arch = "wasm32"),
|
||||
doc = "- [`DbConnection::advance_one_message_blocking`]."
|
||||
)]
|
||||
/// - [`DbConnection::advance_one_message_async`].
|
||||
///
|
||||
/// Which of these methods you should call depends on the specific needs of your application,
|
||||
/// but you must call one of them, or else the connection will never progress.
|
||||
pub struct DbConnection {
|
||||
/// Access to tables defined by the module via extension traits implemented for [`RemoteTables`].
|
||||
pub db: RemoteTables,
|
||||
/// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`].
|
||||
pub reducers: RemoteReducers,
|
||||
#[doc(hidden)]
|
||||
|
||||
/// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`].
|
||||
pub procedures: RemoteProcedures,
|
||||
|
||||
imp: __sdk::DbContextImpl<RemoteModule>,
|
||||
}
|
||||
|
||||
impl __sdk::InModule for DbConnection {
|
||||
type Module = RemoteModule;
|
||||
}
|
||||
|
||||
impl __sdk::DbContext for DbConnection {
|
||||
type DbView = RemoteTables;
|
||||
type Reducers = RemoteReducers;
|
||||
type Procedures = RemoteProcedures;
|
||||
|
||||
fn db(&self) -> &Self::DbView {
|
||||
&self.db
|
||||
}
|
||||
fn reducers(&self) -> &Self::Reducers {
|
||||
&self.reducers
|
||||
}
|
||||
fn procedures(&self) -> &Self::Procedures {
|
||||
&self.procedures
|
||||
}
|
||||
|
||||
fn is_active(&self) -> bool {
|
||||
self.imp.is_active()
|
||||
}
|
||||
|
||||
fn disconnect(&self) -> __sdk::Result<()> {
|
||||
self.imp.disconnect()
|
||||
}
|
||||
|
||||
type SubscriptionBuilder = __sdk::SubscriptionBuilder<RemoteModule>;
|
||||
|
||||
fn subscription_builder(&self) -> Self::SubscriptionBuilder {
|
||||
__sdk::SubscriptionBuilder::new(&self.imp)
|
||||
}
|
||||
|
||||
fn try_identity(&self) -> Option<__sdk::Identity> {
|
||||
self.imp.try_identity()
|
||||
}
|
||||
fn connection_id(&self) -> __sdk::ConnectionId {
|
||||
self.imp.connection_id()
|
||||
}
|
||||
fn try_connection_id(&self) -> Option<__sdk::ConnectionId> {
|
||||
self.imp.try_connection_id()
|
||||
}
|
||||
}
|
||||
|
||||
impl DbConnection {
|
||||
/// Builder-pattern constructor for a connection to a remote module.
|
||||
///
|
||||
/// See [`__sdk::DbConnectionBuilder`] for required and optional configuration for the new connection.
|
||||
pub fn builder() -> __sdk::DbConnectionBuilder<RemoteModule> {
|
||||
__sdk::DbConnectionBuilder::new()
|
||||
}
|
||||
|
||||
/// If any WebSocket messages are waiting, process one of them.
|
||||
///
|
||||
/// Returns `true` if a message was processed, or `false` if the queue is empty.
|
||||
/// Callers should invoke this message in a loop until it returns `false`
|
||||
/// or for as much time is available to process messages.
|
||||
///
|
||||
/// Returns an error if the connection is disconnected.
|
||||
/// If the disconnection in question was normal,
|
||||
/// i.e. the result of a call to [`__sdk::DbContext::disconnect`],
|
||||
/// the returned error will be downcastable to [`__sdk::DisconnectedError`].
|
||||
///
|
||||
/// This is a low-level primitive exposed for power users who need significant control over scheduling.
|
||||
/// Most applications should call [`Self::frame_tick`] each frame
|
||||
/// to fully exhaust the queue whenever time is available.
|
||||
pub fn advance_one_message(&self) -> __sdk::Result<bool> {
|
||||
self.imp.advance_one_message()
|
||||
}
|
||||
|
||||
/// Process one WebSocket message, potentially blocking the current thread until one is received.
|
||||
///
|
||||
/// Returns an error if the connection is disconnected.
|
||||
/// If the disconnection in question was normal,
|
||||
/// i.e. the result of a call to [`__sdk::DbContext::disconnect`],
|
||||
/// the returned error will be downcastable to [`__sdk::DisconnectedError`].
|
||||
///
|
||||
/// This is a low-level primitive exposed for power users who need significant control over scheduling.
|
||||
/// Most applications should call [`Self::run_threaded`] to spawn a thread
|
||||
/// which advances the connection automatically.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn advance_one_message_blocking(&self) -> __sdk::Result<()> {
|
||||
self.imp.advance_one_message_blocking()
|
||||
}
|
||||
|
||||
/// Process one WebSocket message, `await`ing until one is received.
|
||||
///
|
||||
/// Returns an error if the connection is disconnected.
|
||||
/// If the disconnection in question was normal,
|
||||
/// i.e. the result of a call to [`__sdk::DbContext::disconnect`],
|
||||
/// the returned error will be downcastable to [`__sdk::DisconnectedError`].
|
||||
///
|
||||
/// This is a low-level primitive exposed for power users who need significant control over scheduling.
|
||||
/// Most applications should call [`Self::run_async`] to run an `async` loop
|
||||
/// which advances the connection when polled.
|
||||
pub async fn advance_one_message_async(&self) -> __sdk::Result<()> {
|
||||
self.imp.advance_one_message_async().await
|
||||
}
|
||||
|
||||
/// Process all WebSocket messages waiting in the queue,
|
||||
/// then return without `await`ing or blocking the current thread.
|
||||
pub fn frame_tick(&self) -> __sdk::Result<()> {
|
||||
self.imp.frame_tick()
|
||||
}
|
||||
|
||||
/// Spawn a thread which processes WebSocket messages as they are received.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn run_threaded(&self) -> std::thread::JoinHandle<()> {
|
||||
self.imp.run_threaded()
|
||||
}
|
||||
|
||||
/// Spawn a background task which processes WebSocket messages as they are received.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn run_background_task(&self) {
|
||||
self.imp.run_background_task()
|
||||
}
|
||||
|
||||
/// Run an `async` loop which processes WebSocket messages when polled.
|
||||
pub async fn run_async(&self) -> __sdk::Result<()> {
|
||||
self.imp.run_async().await
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::DbConnection for DbConnection {
|
||||
fn new(imp: __sdk::DbContextImpl<RemoteModule>) -> Self {
|
||||
Self {
|
||||
db: RemoteTables { imp: imp.clone() },
|
||||
reducers: RemoteReducers { imp: imp.clone() },
|
||||
procedures: RemoteProcedures { imp: imp.clone() },
|
||||
imp,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A handle on a subscribed query.
|
||||
// TODO: Document this better after implementing the new subscription API.
|
||||
#[derive(Clone)]
|
||||
pub struct SubscriptionHandle {
|
||||
imp: __sdk::SubscriptionHandleImpl<RemoteModule>,
|
||||
}
|
||||
|
||||
impl __sdk::InModule for SubscriptionHandle {
|
||||
type Module = RemoteModule;
|
||||
}
|
||||
|
||||
impl __sdk::SubscriptionHandle for SubscriptionHandle {
|
||||
fn new(imp: __sdk::SubscriptionHandleImpl<RemoteModule>) -> Self {
|
||||
Self { imp }
|
||||
}
|
||||
|
||||
/// Returns true if this subscription has been terminated due to an unsubscribe call or an error.
|
||||
fn is_ended(&self) -> bool {
|
||||
self.imp.is_ended()
|
||||
}
|
||||
|
||||
/// Returns true if this subscription has been applied and has not yet been unsubscribed.
|
||||
fn is_active(&self) -> bool {
|
||||
self.imp.is_active()
|
||||
}
|
||||
|
||||
/// Unsubscribe from the query controlled by this `SubscriptionHandle`,
|
||||
/// then run `on_end` when its rows are removed from the client cache.
|
||||
fn unsubscribe_then(self, on_end: __sdk::OnEndedCallback<RemoteModule>) -> __sdk::Result<()> {
|
||||
self.imp.unsubscribe_then(Some(on_end))
|
||||
}
|
||||
|
||||
fn unsubscribe(self) -> __sdk::Result<()> {
|
||||
self.imp.unsubscribe_then(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Alias trait for a [`__sdk::DbContext`] connected to this module,
|
||||
/// with that trait's associated types bounded to this module's concrete types.
|
||||
///
|
||||
/// Users can use this trait as a boundary on definitions which should accept
|
||||
/// either a [`DbConnection`] or an [`EventContext`] and operate on either.
|
||||
pub trait RemoteDbContext:
|
||||
__sdk::DbContext<
|
||||
DbView = RemoteTables,
|
||||
Reducers = RemoteReducers,
|
||||
SubscriptionBuilder = __sdk::SubscriptionBuilder<RemoteModule>,
|
||||
>
|
||||
{
|
||||
}
|
||||
impl<
|
||||
Ctx: __sdk::DbContext<
|
||||
DbView = RemoteTables,
|
||||
Reducers = RemoteReducers,
|
||||
SubscriptionBuilder = __sdk::SubscriptionBuilder<RemoteModule>,
|
||||
>,
|
||||
> RemoteDbContext for Ctx
|
||||
{
|
||||
}
|
||||
|
||||
/// An [`__sdk::DbContext`] augmented with a [`__sdk::Event`],
|
||||
/// passed to [`__sdk::Table::on_insert`], [`__sdk::Table::on_delete`] and [`__sdk::TableWithPrimaryKey::on_update`] callbacks.
|
||||
pub struct EventContext {
|
||||
/// Access to tables defined by the module via extension traits implemented for [`RemoteTables`].
|
||||
pub db: RemoteTables,
|
||||
/// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`].
|
||||
pub reducers: RemoteReducers,
|
||||
/// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`].
|
||||
pub procedures: RemoteProcedures,
|
||||
/// The event which caused these callbacks to run.
|
||||
pub event: __sdk::Event<Reducer>,
|
||||
imp: __sdk::DbContextImpl<RemoteModule>,
|
||||
}
|
||||
|
||||
impl __sdk::AbstractEventContext for EventContext {
|
||||
type Event = __sdk::Event<Reducer>;
|
||||
fn event(&self) -> &Self::Event {
|
||||
&self.event
|
||||
}
|
||||
fn new(imp: __sdk::DbContextImpl<RemoteModule>, event: Self::Event) -> Self {
|
||||
Self {
|
||||
db: RemoteTables { imp: imp.clone() },
|
||||
reducers: RemoteReducers { imp: imp.clone() },
|
||||
procedures: RemoteProcedures { imp: imp.clone() },
|
||||
event,
|
||||
imp,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::InModule for EventContext {
|
||||
type Module = RemoteModule;
|
||||
}
|
||||
|
||||
impl __sdk::DbContext for EventContext {
|
||||
type DbView = RemoteTables;
|
||||
type Reducers = RemoteReducers;
|
||||
type Procedures = RemoteProcedures;
|
||||
|
||||
fn db(&self) -> &Self::DbView {
|
||||
&self.db
|
||||
}
|
||||
fn reducers(&self) -> &Self::Reducers {
|
||||
&self.reducers
|
||||
}
|
||||
fn procedures(&self) -> &Self::Procedures {
|
||||
&self.procedures
|
||||
}
|
||||
|
||||
fn is_active(&self) -> bool {
|
||||
self.imp.is_active()
|
||||
}
|
||||
|
||||
fn disconnect(&self) -> __sdk::Result<()> {
|
||||
self.imp.disconnect()
|
||||
}
|
||||
|
||||
type SubscriptionBuilder = __sdk::SubscriptionBuilder<RemoteModule>;
|
||||
|
||||
fn subscription_builder(&self) -> Self::SubscriptionBuilder {
|
||||
__sdk::SubscriptionBuilder::new(&self.imp)
|
||||
}
|
||||
|
||||
fn try_identity(&self) -> Option<__sdk::Identity> {
|
||||
self.imp.try_identity()
|
||||
}
|
||||
fn connection_id(&self) -> __sdk::ConnectionId {
|
||||
self.imp.connection_id()
|
||||
}
|
||||
fn try_connection_id(&self) -> Option<__sdk::ConnectionId> {
|
||||
self.imp.try_connection_id()
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::EventContext for EventContext {}
|
||||
|
||||
/// An [`__sdk::DbContext`] augmented with a [`__sdk::ReducerEvent`],
|
||||
/// passed to on-reducer callbacks.
|
||||
pub struct ReducerEventContext {
|
||||
/// Access to tables defined by the module via extension traits implemented for [`RemoteTables`].
|
||||
pub db: RemoteTables,
|
||||
/// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`].
|
||||
pub reducers: RemoteReducers,
|
||||
/// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`].
|
||||
pub procedures: RemoteProcedures,
|
||||
/// The event which caused these callbacks to run.
|
||||
pub event: __sdk::ReducerEvent<Reducer>,
|
||||
imp: __sdk::DbContextImpl<RemoteModule>,
|
||||
}
|
||||
|
||||
impl __sdk::AbstractEventContext for ReducerEventContext {
|
||||
type Event = __sdk::ReducerEvent<Reducer>;
|
||||
fn event(&self) -> &Self::Event {
|
||||
&self.event
|
||||
}
|
||||
fn new(imp: __sdk::DbContextImpl<RemoteModule>, event: Self::Event) -> Self {
|
||||
Self {
|
||||
db: RemoteTables { imp: imp.clone() },
|
||||
reducers: RemoteReducers { imp: imp.clone() },
|
||||
procedures: RemoteProcedures { imp: imp.clone() },
|
||||
event,
|
||||
imp,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::InModule for ReducerEventContext {
|
||||
type Module = RemoteModule;
|
||||
}
|
||||
|
||||
impl __sdk::DbContext for ReducerEventContext {
|
||||
type DbView = RemoteTables;
|
||||
type Reducers = RemoteReducers;
|
||||
type Procedures = RemoteProcedures;
|
||||
|
||||
fn db(&self) -> &Self::DbView {
|
||||
&self.db
|
||||
}
|
||||
fn reducers(&self) -> &Self::Reducers {
|
||||
&self.reducers
|
||||
}
|
||||
fn procedures(&self) -> &Self::Procedures {
|
||||
&self.procedures
|
||||
}
|
||||
|
||||
fn is_active(&self) -> bool {
|
||||
self.imp.is_active()
|
||||
}
|
||||
|
||||
fn disconnect(&self) -> __sdk::Result<()> {
|
||||
self.imp.disconnect()
|
||||
}
|
||||
|
||||
type SubscriptionBuilder = __sdk::SubscriptionBuilder<RemoteModule>;
|
||||
|
||||
fn subscription_builder(&self) -> Self::SubscriptionBuilder {
|
||||
__sdk::SubscriptionBuilder::new(&self.imp)
|
||||
}
|
||||
|
||||
fn try_identity(&self) -> Option<__sdk::Identity> {
|
||||
self.imp.try_identity()
|
||||
}
|
||||
fn connection_id(&self) -> __sdk::ConnectionId {
|
||||
self.imp.connection_id()
|
||||
}
|
||||
fn try_connection_id(&self) -> Option<__sdk::ConnectionId> {
|
||||
self.imp.try_connection_id()
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::ReducerEventContext for ReducerEventContext {}
|
||||
|
||||
/// An [`__sdk::DbContext`] passed to procedure callbacks.
|
||||
pub struct ProcedureEventContext {
|
||||
/// Access to tables defined by the module via extension traits implemented for [`RemoteTables`].
|
||||
pub db: RemoteTables,
|
||||
/// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`].
|
||||
pub reducers: RemoteReducers,
|
||||
/// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`].
|
||||
pub procedures: RemoteProcedures,
|
||||
imp: __sdk::DbContextImpl<RemoteModule>,
|
||||
}
|
||||
|
||||
impl __sdk::AbstractEventContext for ProcedureEventContext {
|
||||
type Event = ();
|
||||
fn event(&self) -> &Self::Event {
|
||||
&()
|
||||
}
|
||||
fn new(imp: __sdk::DbContextImpl<RemoteModule>, _event: Self::Event) -> Self {
|
||||
Self {
|
||||
db: RemoteTables { imp: imp.clone() },
|
||||
reducers: RemoteReducers { imp: imp.clone() },
|
||||
procedures: RemoteProcedures { imp: imp.clone() },
|
||||
imp,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::InModule for ProcedureEventContext {
|
||||
type Module = RemoteModule;
|
||||
}
|
||||
|
||||
impl __sdk::DbContext for ProcedureEventContext {
|
||||
type DbView = RemoteTables;
|
||||
type Reducers = RemoteReducers;
|
||||
type Procedures = RemoteProcedures;
|
||||
|
||||
fn db(&self) -> &Self::DbView {
|
||||
&self.db
|
||||
}
|
||||
fn reducers(&self) -> &Self::Reducers {
|
||||
&self.reducers
|
||||
}
|
||||
fn procedures(&self) -> &Self::Procedures {
|
||||
&self.procedures
|
||||
}
|
||||
|
||||
fn is_active(&self) -> bool {
|
||||
self.imp.is_active()
|
||||
}
|
||||
|
||||
fn disconnect(&self) -> __sdk::Result<()> {
|
||||
self.imp.disconnect()
|
||||
}
|
||||
|
||||
type SubscriptionBuilder = __sdk::SubscriptionBuilder<RemoteModule>;
|
||||
|
||||
fn subscription_builder(&self) -> Self::SubscriptionBuilder {
|
||||
__sdk::SubscriptionBuilder::new(&self.imp)
|
||||
}
|
||||
|
||||
fn try_identity(&self) -> Option<__sdk::Identity> {
|
||||
self.imp.try_identity()
|
||||
}
|
||||
fn connection_id(&self) -> __sdk::ConnectionId {
|
||||
self.imp.connection_id()
|
||||
}
|
||||
fn try_connection_id(&self) -> Option<__sdk::ConnectionId> {
|
||||
self.imp.try_connection_id()
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::ProcedureEventContext for ProcedureEventContext {}
|
||||
|
||||
/// An [`__sdk::DbContext`] passed to [`__sdk::SubscriptionBuilder::on_applied`] and [`SubscriptionHandle::unsubscribe_then`] callbacks.
|
||||
pub struct SubscriptionEventContext {
|
||||
/// Access to tables defined by the module via extension traits implemented for [`RemoteTables`].
|
||||
pub db: RemoteTables,
|
||||
/// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`].
|
||||
pub reducers: RemoteReducers,
|
||||
/// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`].
|
||||
pub procedures: RemoteProcedures,
|
||||
imp: __sdk::DbContextImpl<RemoteModule>,
|
||||
}
|
||||
|
||||
impl __sdk::AbstractEventContext for SubscriptionEventContext {
|
||||
type Event = ();
|
||||
fn event(&self) -> &Self::Event {
|
||||
&()
|
||||
}
|
||||
fn new(imp: __sdk::DbContextImpl<RemoteModule>, _event: Self::Event) -> Self {
|
||||
Self {
|
||||
db: RemoteTables { imp: imp.clone() },
|
||||
reducers: RemoteReducers { imp: imp.clone() },
|
||||
procedures: RemoteProcedures { imp: imp.clone() },
|
||||
imp,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::InModule for SubscriptionEventContext {
|
||||
type Module = RemoteModule;
|
||||
}
|
||||
|
||||
impl __sdk::DbContext for SubscriptionEventContext {
|
||||
type DbView = RemoteTables;
|
||||
type Reducers = RemoteReducers;
|
||||
type Procedures = RemoteProcedures;
|
||||
|
||||
fn db(&self) -> &Self::DbView {
|
||||
&self.db
|
||||
}
|
||||
fn reducers(&self) -> &Self::Reducers {
|
||||
&self.reducers
|
||||
}
|
||||
fn procedures(&self) -> &Self::Procedures {
|
||||
&self.procedures
|
||||
}
|
||||
|
||||
fn is_active(&self) -> bool {
|
||||
self.imp.is_active()
|
||||
}
|
||||
|
||||
fn disconnect(&self) -> __sdk::Result<()> {
|
||||
self.imp.disconnect()
|
||||
}
|
||||
|
||||
type SubscriptionBuilder = __sdk::SubscriptionBuilder<RemoteModule>;
|
||||
|
||||
fn subscription_builder(&self) -> Self::SubscriptionBuilder {
|
||||
__sdk::SubscriptionBuilder::new(&self.imp)
|
||||
}
|
||||
|
||||
fn try_identity(&self) -> Option<__sdk::Identity> {
|
||||
self.imp.try_identity()
|
||||
}
|
||||
fn connection_id(&self) -> __sdk::ConnectionId {
|
||||
self.imp.connection_id()
|
||||
}
|
||||
fn try_connection_id(&self) -> Option<__sdk::ConnectionId> {
|
||||
self.imp.try_connection_id()
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::SubscriptionEventContext for SubscriptionEventContext {}
|
||||
|
||||
/// An [`__sdk::DbContext`] augmented with a [`__sdk::Error`],
|
||||
/// passed to [`__sdk::DbConnectionBuilder::on_disconnect`], [`__sdk::DbConnectionBuilder::on_connect_error`] and [`__sdk::SubscriptionBuilder::on_error`] callbacks.
|
||||
pub struct ErrorContext {
|
||||
/// Access to tables defined by the module via extension traits implemented for [`RemoteTables`].
|
||||
pub db: RemoteTables,
|
||||
/// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`].
|
||||
pub reducers: RemoteReducers,
|
||||
/// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`].
|
||||
pub procedures: RemoteProcedures,
|
||||
/// The event which caused these callbacks to run.
|
||||
pub event: Option<__sdk::Error>,
|
||||
imp: __sdk::DbContextImpl<RemoteModule>,
|
||||
}
|
||||
|
||||
impl __sdk::AbstractEventContext for ErrorContext {
|
||||
type Event = Option<__sdk::Error>;
|
||||
fn event(&self) -> &Self::Event {
|
||||
&self.event
|
||||
}
|
||||
fn new(imp: __sdk::DbContextImpl<RemoteModule>, event: Self::Event) -> Self {
|
||||
Self {
|
||||
db: RemoteTables { imp: imp.clone() },
|
||||
reducers: RemoteReducers { imp: imp.clone() },
|
||||
procedures: RemoteProcedures { imp: imp.clone() },
|
||||
event,
|
||||
imp,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::InModule for ErrorContext {
|
||||
type Module = RemoteModule;
|
||||
}
|
||||
|
||||
impl __sdk::DbContext for ErrorContext {
|
||||
type DbView = RemoteTables;
|
||||
type Reducers = RemoteReducers;
|
||||
type Procedures = RemoteProcedures;
|
||||
|
||||
fn db(&self) -> &Self::DbView {
|
||||
&self.db
|
||||
}
|
||||
fn reducers(&self) -> &Self::Reducers {
|
||||
&self.reducers
|
||||
}
|
||||
fn procedures(&self) -> &Self::Procedures {
|
||||
&self.procedures
|
||||
}
|
||||
|
||||
fn is_active(&self) -> bool {
|
||||
self.imp.is_active()
|
||||
}
|
||||
|
||||
fn disconnect(&self) -> __sdk::Result<()> {
|
||||
self.imp.disconnect()
|
||||
}
|
||||
|
||||
type SubscriptionBuilder = __sdk::SubscriptionBuilder<RemoteModule>;
|
||||
|
||||
fn subscription_builder(&self) -> Self::SubscriptionBuilder {
|
||||
__sdk::SubscriptionBuilder::new(&self.imp)
|
||||
}
|
||||
|
||||
fn try_identity(&self) -> Option<__sdk::Identity> {
|
||||
self.imp.try_identity()
|
||||
}
|
||||
fn connection_id(&self) -> __sdk::ConnectionId {
|
||||
self.imp.connection_id()
|
||||
}
|
||||
fn try_connection_id(&self) -> Option<__sdk::ConnectionId> {
|
||||
self.imp.try_connection_id()
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::ErrorContext for ErrorContext {}
|
||||
|
||||
impl __sdk::SpacetimeModule for RemoteModule {
|
||||
type DbConnection = DbConnection;
|
||||
type EventContext = EventContext;
|
||||
type ReducerEventContext = ReducerEventContext;
|
||||
type ProcedureEventContext = ProcedureEventContext;
|
||||
type SubscriptionEventContext = SubscriptionEventContext;
|
||||
type ErrorContext = ErrorContext;
|
||||
type Reducer = Reducer;
|
||||
type DbView = RemoteTables;
|
||||
type Reducers = RemoteReducers;
|
||||
type Procedures = RemoteProcedures;
|
||||
type DbUpdate = DbUpdate;
|
||||
type AppliedDiff<'r> = AppliedDiff<'r>;
|
||||
type SubscriptionHandle = SubscriptionHandle;
|
||||
type QueryBuilder = __sdk::QueryBuilder;
|
||||
|
||||
fn register_tables(client_cache: &mut __sdk::ClientCache<Self>) {
|
||||
activities_table::register_table(client_cache);
|
||||
log_events_table::register_table(client_cache);
|
||||
profiles_table::register_table(client_cache);
|
||||
task_part_table::register_table(client_cache);
|
||||
tasks_table::register_table(client_cache);
|
||||
}
|
||||
const ALL_TABLE_NAMES: &'static [&'static str] =
|
||||
&["activities", "log_events", "profiles", "task_part", "tasks"];
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
|
||||
#[sats(crate = __lib)]
|
||||
pub(super) struct NextActionArgs {}
|
||||
|
||||
impl From<NextActionArgs> for super::Reducer {
|
||||
fn from(args: NextActionArgs) -> Self {
|
||||
Self::NextAction
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::InModule for NextActionArgs {
|
||||
type Module = super::RemoteModule;
|
||||
}
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
/// Extension trait for access to the reducer `next_action`.
|
||||
///
|
||||
/// Implemented for [`super::RemoteReducers`].
|
||||
pub trait next_action {
|
||||
/// Request that the remote module invoke the reducer `next_action` to run as soon as possible.
|
||||
///
|
||||
/// This method returns immediately, and errors only if we are unable to send the request.
|
||||
/// The reducer will run asynchronously in the future,
|
||||
/// and this method provides no way to listen for its completion status.
|
||||
/// /// Use [`next_action:next_action_then`] to run a callback after the reducer completes.
|
||||
fn next_action(&self) -> __sdk::Result<()> {
|
||||
self.next_action_then(|_, _| {})
|
||||
}
|
||||
|
||||
/// Request that the remote module invoke the reducer `next_action` to run as soon as possible,
|
||||
/// registering `callback` to run when we are notified that the reducer completed.
|
||||
///
|
||||
/// This method returns immediately, and errors only if we are unable to send the request.
|
||||
/// The reducer will run asynchronously in the future,
|
||||
/// and its status can be observed with the `callback`.
|
||||
fn next_action_then(
|
||||
&self,
|
||||
|
||||
callback: impl FnOnce(&super::ReducerEventContext, Result<Result<(), String>, __sdk::InternalError>)
|
||||
+ Send
|
||||
+ 'static,
|
||||
) -> __sdk::Result<()>;
|
||||
}
|
||||
|
||||
impl next_action for super::RemoteReducers {
|
||||
fn next_action_then(
|
||||
&self,
|
||||
|
||||
callback: impl FnOnce(&super::ReducerEventContext, Result<Result<(), String>, __sdk::InternalError>)
|
||||
+ Send
|
||||
+ 'static,
|
||||
) -> __sdk::Result<()> {
|
||||
self.imp
|
||||
.invoke_reducer_with_callback(NextActionArgs {}, callback)
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
|
||||
#[sats(crate = __lib)]
|
||||
pub struct Profile {
|
||||
pub identity: __sdk::Identity,
|
||||
pub username: String,
|
||||
}
|
||||
|
||||
impl __sdk::InModule for Profile {
|
||||
type Module = super::RemoteModule;
|
||||
}
|
||||
|
||||
/// Column accessor struct for the table `Profile`.
|
||||
///
|
||||
/// Provides typed access to columns for query building.
|
||||
pub struct ProfileCols {
|
||||
pub identity: __sdk::__query_builder::Col<Profile, __sdk::Identity>,
|
||||
pub username: __sdk::__query_builder::Col<Profile, String>,
|
||||
}
|
||||
|
||||
impl __sdk::__query_builder::HasCols for Profile {
|
||||
type Cols = ProfileCols;
|
||||
fn cols(table_name: &'static str) -> Self::Cols {
|
||||
ProfileCols {
|
||||
identity: __sdk::__query_builder::Col::new(table_name, "identity"),
|
||||
username: __sdk::__query_builder::Col::new(table_name, "username"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Indexed column accessor struct for the table `Profile`.
|
||||
///
|
||||
/// Provides typed access to indexed columns for query building.
|
||||
pub struct ProfileIxCols {
|
||||
pub identity: __sdk::__query_builder::IxCol<Profile, __sdk::Identity>,
|
||||
pub username: __sdk::__query_builder::IxCol<Profile, String>,
|
||||
}
|
||||
|
||||
impl __sdk::__query_builder::HasIxCols for Profile {
|
||||
type IxCols = ProfileIxCols;
|
||||
fn ix_cols(table_name: &'static str) -> Self::IxCols {
|
||||
ProfileIxCols {
|
||||
identity: __sdk::__query_builder::IxCol::new(table_name, "identity"),
|
||||
username: __sdk::__query_builder::IxCol::new(table_name, "username"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::__query_builder::CanBeLookupTable for Profile {}
|
||||
@@ -1,192 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use super::profile_type::Profile;
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
/// Table handle for the table `profiles`.
|
||||
///
|
||||
/// Obtain a handle from the [`ProfilesTableAccess::profiles`] method on [`super::RemoteTables`],
|
||||
/// like `ctx.db.profiles()`.
|
||||
///
|
||||
/// Users are encouraged not to explicitly reference this type,
|
||||
/// but to directly chain method calls,
|
||||
/// like `ctx.db.profiles().on_insert(...)`.
|
||||
pub struct ProfilesTableHandle<'ctx> {
|
||||
imp: __sdk::TableHandle<Profile>,
|
||||
ctx: std::marker::PhantomData<&'ctx super::RemoteTables>,
|
||||
}
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
/// Extension trait for access to the table `profiles`.
|
||||
///
|
||||
/// Implemented for [`super::RemoteTables`].
|
||||
pub trait ProfilesTableAccess {
|
||||
#[allow(non_snake_case)]
|
||||
/// Obtain a [`ProfilesTableHandle`], which mediates access to the table `profiles`.
|
||||
fn profiles(&self) -> ProfilesTableHandle<'_>;
|
||||
}
|
||||
|
||||
impl ProfilesTableAccess for super::RemoteTables {
|
||||
fn profiles(&self) -> ProfilesTableHandle<'_> {
|
||||
ProfilesTableHandle {
|
||||
imp: self.imp.get_table::<Profile>("profiles"),
|
||||
ctx: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ProfilesInsertCallbackId(__sdk::CallbackId);
|
||||
pub struct ProfilesDeleteCallbackId(__sdk::CallbackId);
|
||||
|
||||
impl<'ctx> __sdk::Table for ProfilesTableHandle<'ctx> {
|
||||
type Row = Profile;
|
||||
type EventContext = super::EventContext;
|
||||
|
||||
fn count(&self) -> u64 {
|
||||
self.imp.count()
|
||||
}
|
||||
fn iter(&self) -> impl Iterator<Item = Profile> + '_ {
|
||||
self.imp.iter()
|
||||
}
|
||||
|
||||
type InsertCallbackId = ProfilesInsertCallbackId;
|
||||
|
||||
fn on_insert(
|
||||
&self,
|
||||
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
|
||||
) -> ProfilesInsertCallbackId {
|
||||
ProfilesInsertCallbackId(self.imp.on_insert(Box::new(callback)))
|
||||
}
|
||||
|
||||
fn remove_on_insert(&self, callback: ProfilesInsertCallbackId) {
|
||||
self.imp.remove_on_insert(callback.0)
|
||||
}
|
||||
|
||||
type DeleteCallbackId = ProfilesDeleteCallbackId;
|
||||
|
||||
fn on_delete(
|
||||
&self,
|
||||
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
|
||||
) -> ProfilesDeleteCallbackId {
|
||||
ProfilesDeleteCallbackId(self.imp.on_delete(Box::new(callback)))
|
||||
}
|
||||
|
||||
fn remove_on_delete(&self, callback: ProfilesDeleteCallbackId) {
|
||||
self.imp.remove_on_delete(callback.0)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ProfilesUpdateCallbackId(__sdk::CallbackId);
|
||||
|
||||
impl<'ctx> __sdk::TableWithPrimaryKey for ProfilesTableHandle<'ctx> {
|
||||
type UpdateCallbackId = ProfilesUpdateCallbackId;
|
||||
|
||||
fn on_update(
|
||||
&self,
|
||||
callback: impl FnMut(&Self::EventContext, &Self::Row, &Self::Row) + Send + 'static,
|
||||
) -> ProfilesUpdateCallbackId {
|
||||
ProfilesUpdateCallbackId(self.imp.on_update(Box::new(callback)))
|
||||
}
|
||||
|
||||
fn remove_on_update(&self, callback: ProfilesUpdateCallbackId) {
|
||||
self.imp.remove_on_update(callback.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Access to the `identity` unique index on the table `profiles`,
|
||||
/// which allows point queries on the field of the same name
|
||||
/// via the [`ProfilesIdentityUnique::find`] method.
|
||||
///
|
||||
/// Users are encouraged not to explicitly reference this type,
|
||||
/// but to directly chain method calls,
|
||||
/// like `ctx.db.profiles().identity().find(...)`.
|
||||
pub struct ProfilesIdentityUnique<'ctx> {
|
||||
imp: __sdk::UniqueConstraintHandle<Profile, __sdk::Identity>,
|
||||
phantom: std::marker::PhantomData<&'ctx super::RemoteTables>,
|
||||
}
|
||||
|
||||
impl<'ctx> ProfilesTableHandle<'ctx> {
|
||||
/// Get a handle on the `identity` unique index on the table `profiles`.
|
||||
pub fn identity(&self) -> ProfilesIdentityUnique<'ctx> {
|
||||
ProfilesIdentityUnique {
|
||||
imp: self
|
||||
.imp
|
||||
.get_unique_constraint::<__sdk::Identity>("identity"),
|
||||
phantom: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ctx> ProfilesIdentityUnique<'ctx> {
|
||||
/// Find the subscribed row whose `identity` column value is equal to `col_val`,
|
||||
/// if such a row is present in the client cache.
|
||||
pub fn find(&self, col_val: &__sdk::Identity) -> Option<Profile> {
|
||||
self.imp.find(col_val)
|
||||
}
|
||||
}
|
||||
|
||||
/// Access to the `username` unique index on the table `profiles`,
|
||||
/// which allows point queries on the field of the same name
|
||||
/// via the [`ProfilesUsernameUnique::find`] method.
|
||||
///
|
||||
/// Users are encouraged not to explicitly reference this type,
|
||||
/// but to directly chain method calls,
|
||||
/// like `ctx.db.profiles().username().find(...)`.
|
||||
pub struct ProfilesUsernameUnique<'ctx> {
|
||||
imp: __sdk::UniqueConstraintHandle<Profile, String>,
|
||||
phantom: std::marker::PhantomData<&'ctx super::RemoteTables>,
|
||||
}
|
||||
|
||||
impl<'ctx> ProfilesTableHandle<'ctx> {
|
||||
/// Get a handle on the `username` unique index on the table `profiles`.
|
||||
pub fn username(&self) -> ProfilesUsernameUnique<'ctx> {
|
||||
ProfilesUsernameUnique {
|
||||
imp: self.imp.get_unique_constraint::<String>("username"),
|
||||
phantom: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ctx> ProfilesUsernameUnique<'ctx> {
|
||||
/// Find the subscribed row whose `username` column value is equal to `col_val`,
|
||||
/// if such a row is present in the client cache.
|
||||
pub fn find(&self, col_val: &String) -> Option<Profile> {
|
||||
self.imp.find(col_val)
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub(super) fn register_table(client_cache: &mut __sdk::ClientCache<super::RemoteModule>) {
|
||||
let _table = client_cache.get_or_make_table::<Profile>("profiles");
|
||||
_table.add_unique_constraint::<__sdk::Identity>("identity", |row| &row.identity);
|
||||
_table.add_unique_constraint::<String>("username", |row| &row.username);
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub(super) fn parse_table_update(
|
||||
raw_updates: __ws::v2::TableUpdate,
|
||||
) -> __sdk::Result<__sdk::TableUpdate<Profile>> {
|
||||
__sdk::TableUpdate::parse_table_update(raw_updates).map_err(|e| {
|
||||
__sdk::InternalError::failed_parse("TableUpdate<Profile>", "TableUpdate")
|
||||
.with_cause(e)
|
||||
.into()
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
/// Extension trait for query builder access to the table `Profile`.
|
||||
///
|
||||
/// Implemented for [`__sdk::QueryTableAccessor`].
|
||||
pub trait profilesQueryTableAccess {
|
||||
#[allow(non_snake_case)]
|
||||
/// Get a query builder for the table `Profile`.
|
||||
fn profiles(&self) -> __sdk::__query_builder::Table<Profile>;
|
||||
}
|
||||
|
||||
impl profilesQueryTableAccess for __sdk::QueryTableAccessor {
|
||||
fn profiles(&self) -> __sdk::__query_builder::Table<Profile> {
|
||||
__sdk::__query_builder::Table::new("profiles")
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
use super::activity_type::Activity;
|
||||
|
||||
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
|
||||
#[sats(crate = __lib)]
|
||||
pub(super) struct RemoveActivityArgs {
|
||||
pub activity: Activity,
|
||||
}
|
||||
|
||||
impl From<RemoveActivityArgs> for super::Reducer {
|
||||
fn from(args: RemoveActivityArgs) -> Self {
|
||||
Self::RemoveActivity {
|
||||
activity: args.activity,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::InModule for RemoveActivityArgs {
|
||||
type Module = super::RemoteModule;
|
||||
}
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
/// Extension trait for access to the reducer `remove_activity`.
|
||||
///
|
||||
/// Implemented for [`super::RemoteReducers`].
|
||||
pub trait remove_activity {
|
||||
/// Request that the remote module invoke the reducer `remove_activity` to run as soon as possible.
|
||||
///
|
||||
/// This method returns immediately, and errors only if we are unable to send the request.
|
||||
/// The reducer will run asynchronously in the future,
|
||||
/// and this method provides no way to listen for its completion status.
|
||||
/// /// Use [`remove_activity:remove_activity_then`] to run a callback after the reducer completes.
|
||||
fn remove_activity(&self, activity: Activity) -> __sdk::Result<()> {
|
||||
self.remove_activity_then(activity, |_, _| {})
|
||||
}
|
||||
|
||||
/// Request that the remote module invoke the reducer `remove_activity` to run as soon as possible,
|
||||
/// registering `callback` to run when we are notified that the reducer completed.
|
||||
///
|
||||
/// This method returns immediately, and errors only if we are unable to send the request.
|
||||
/// The reducer will run asynchronously in the future,
|
||||
/// and its status can be observed with the `callback`.
|
||||
fn remove_activity_then(
|
||||
&self,
|
||||
activity: Activity,
|
||||
|
||||
callback: impl FnOnce(&super::ReducerEventContext, Result<Result<(), String>, __sdk::InternalError>)
|
||||
+ Send
|
||||
+ 'static,
|
||||
) -> __sdk::Result<()>;
|
||||
}
|
||||
|
||||
impl remove_activity for super::RemoteReducers {
|
||||
fn remove_activity_then(
|
||||
&self,
|
||||
activity: Activity,
|
||||
|
||||
callback: impl FnOnce(&super::ReducerEventContext, Result<Result<(), String>, __sdk::InternalError>)
|
||||
+ Send
|
||||
+ 'static,
|
||||
) -> __sdk::Result<()> {
|
||||
self.imp
|
||||
.invoke_reducer_with_callback(RemoveActivityArgs { activity }, callback)
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
|
||||
#[sats(crate = __lib)]
|
||||
pub(super) struct SetActivityNameArgs {
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl From<SetActivityNameArgs> for super::Reducer {
|
||||
fn from(args: SetActivityNameArgs) -> Self {
|
||||
Self::SetActivityName {
|
||||
id: args.id,
|
||||
name: args.name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::InModule for SetActivityNameArgs {
|
||||
type Module = super::RemoteModule;
|
||||
}
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
/// Extension trait for access to the reducer `set_activity_name`.
|
||||
///
|
||||
/// Implemented for [`super::RemoteReducers`].
|
||||
pub trait set_activity_name {
|
||||
/// Request that the remote module invoke the reducer `set_activity_name` to run as soon as possible.
|
||||
///
|
||||
/// This method returns immediately, and errors only if we are unable to send the request.
|
||||
/// The reducer will run asynchronously in the future,
|
||||
/// and this method provides no way to listen for its completion status.
|
||||
/// /// Use [`set_activity_name:set_activity_name_then`] to run a callback after the reducer completes.
|
||||
fn set_activity_name(&self, id: u64, name: String) -> __sdk::Result<()> {
|
||||
self.set_activity_name_then(id, name, |_, _| {})
|
||||
}
|
||||
|
||||
/// Request that the remote module invoke the reducer `set_activity_name` to run as soon as possible,
|
||||
/// registering `callback` to run when we are notified that the reducer completed.
|
||||
///
|
||||
/// This method returns immediately, and errors only if we are unable to send the request.
|
||||
/// The reducer will run asynchronously in the future,
|
||||
/// and its status can be observed with the `callback`.
|
||||
fn set_activity_name_then(
|
||||
&self,
|
||||
id: u64,
|
||||
name: String,
|
||||
|
||||
callback: impl FnOnce(&super::ReducerEventContext, Result<Result<(), String>, __sdk::InternalError>)
|
||||
+ Send
|
||||
+ 'static,
|
||||
) -> __sdk::Result<()>;
|
||||
}
|
||||
|
||||
impl set_activity_name for super::RemoteReducers {
|
||||
fn set_activity_name_then(
|
||||
&self,
|
||||
id: u64,
|
||||
name: String,
|
||||
|
||||
callback: impl FnOnce(&super::ReducerEventContext, Result<Result<(), String>, __sdk::InternalError>)
|
||||
+ Send
|
||||
+ 'static,
|
||||
) -> __sdk::Result<()> {
|
||||
self.imp
|
||||
.invoke_reducer_with_callback(SetActivityNameArgs { id, name }, callback)
|
||||
}
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use super::action_type::Action;
|
||||
use super::task_part_type::TaskPart;
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
/// Table handle for the table `task_part`.
|
||||
///
|
||||
/// Obtain a handle from the [`TaskPartTableAccess::task_part`] method on [`super::RemoteTables`],
|
||||
/// like `ctx.db.task_part()`.
|
||||
///
|
||||
/// Users are encouraged not to explicitly reference this type,
|
||||
/// but to directly chain method calls,
|
||||
/// like `ctx.db.task_part().on_insert(...)`.
|
||||
pub struct TaskPartTableHandle<'ctx> {
|
||||
imp: __sdk::TableHandle<TaskPart>,
|
||||
ctx: std::marker::PhantomData<&'ctx super::RemoteTables>,
|
||||
}
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
/// Extension trait for access to the table `task_part`.
|
||||
///
|
||||
/// Implemented for [`super::RemoteTables`].
|
||||
pub trait TaskPartTableAccess {
|
||||
#[allow(non_snake_case)]
|
||||
/// Obtain a [`TaskPartTableHandle`], which mediates access to the table `task_part`.
|
||||
fn task_part(&self) -> TaskPartTableHandle<'_>;
|
||||
}
|
||||
|
||||
impl TaskPartTableAccess for super::RemoteTables {
|
||||
fn task_part(&self) -> TaskPartTableHandle<'_> {
|
||||
TaskPartTableHandle {
|
||||
imp: self.imp.get_table::<TaskPart>("task_part"),
|
||||
ctx: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TaskPartInsertCallbackId(__sdk::CallbackId);
|
||||
pub struct TaskPartDeleteCallbackId(__sdk::CallbackId);
|
||||
|
||||
impl<'ctx> __sdk::Table for TaskPartTableHandle<'ctx> {
|
||||
type Row = TaskPart;
|
||||
type EventContext = super::EventContext;
|
||||
|
||||
fn count(&self) -> u64 {
|
||||
self.imp.count()
|
||||
}
|
||||
fn iter(&self) -> impl Iterator<Item = TaskPart> + '_ {
|
||||
self.imp.iter()
|
||||
}
|
||||
|
||||
type InsertCallbackId = TaskPartInsertCallbackId;
|
||||
|
||||
fn on_insert(
|
||||
&self,
|
||||
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
|
||||
) -> TaskPartInsertCallbackId {
|
||||
TaskPartInsertCallbackId(self.imp.on_insert(Box::new(callback)))
|
||||
}
|
||||
|
||||
fn remove_on_insert(&self, callback: TaskPartInsertCallbackId) {
|
||||
self.imp.remove_on_insert(callback.0)
|
||||
}
|
||||
|
||||
type DeleteCallbackId = TaskPartDeleteCallbackId;
|
||||
|
||||
fn on_delete(
|
||||
&self,
|
||||
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
|
||||
) -> TaskPartDeleteCallbackId {
|
||||
TaskPartDeleteCallbackId(self.imp.on_delete(Box::new(callback)))
|
||||
}
|
||||
|
||||
fn remove_on_delete(&self, callback: TaskPartDeleteCallbackId) {
|
||||
self.imp.remove_on_delete(callback.0)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TaskPartUpdateCallbackId(__sdk::CallbackId);
|
||||
|
||||
impl<'ctx> __sdk::TableWithPrimaryKey for TaskPartTableHandle<'ctx> {
|
||||
type UpdateCallbackId = TaskPartUpdateCallbackId;
|
||||
|
||||
fn on_update(
|
||||
&self,
|
||||
callback: impl FnMut(&Self::EventContext, &Self::Row, &Self::Row) + Send + 'static,
|
||||
) -> TaskPartUpdateCallbackId {
|
||||
TaskPartUpdateCallbackId(self.imp.on_update(Box::new(callback)))
|
||||
}
|
||||
|
||||
fn remove_on_update(&self, callback: TaskPartUpdateCallbackId) {
|
||||
self.imp.remove_on_update(callback.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Access to the `identity` unique index on the table `task_part`,
|
||||
/// which allows point queries on the field of the same name
|
||||
/// via the [`TaskPartIdentityUnique::find`] method.
|
||||
///
|
||||
/// Users are encouraged not to explicitly reference this type,
|
||||
/// but to directly chain method calls,
|
||||
/// like `ctx.db.task_part().identity().find(...)`.
|
||||
pub struct TaskPartIdentityUnique<'ctx> {
|
||||
imp: __sdk::UniqueConstraintHandle<TaskPart, __sdk::Identity>,
|
||||
phantom: std::marker::PhantomData<&'ctx super::RemoteTables>,
|
||||
}
|
||||
|
||||
impl<'ctx> TaskPartTableHandle<'ctx> {
|
||||
/// Get a handle on the `identity` unique index on the table `task_part`.
|
||||
pub fn identity(&self) -> TaskPartIdentityUnique<'ctx> {
|
||||
TaskPartIdentityUnique {
|
||||
imp: self
|
||||
.imp
|
||||
.get_unique_constraint::<__sdk::Identity>("identity"),
|
||||
phantom: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ctx> TaskPartIdentityUnique<'ctx> {
|
||||
/// Find the subscribed row whose `identity` column value is equal to `col_val`,
|
||||
/// if such a row is present in the client cache.
|
||||
pub fn find(&self, col_val: &__sdk::Identity) -> Option<TaskPart> {
|
||||
self.imp.find(col_val)
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub(super) fn register_table(client_cache: &mut __sdk::ClientCache<super::RemoteModule>) {
|
||||
let _table = client_cache.get_or_make_table::<TaskPart>("task_part");
|
||||
_table.add_unique_constraint::<__sdk::Identity>("identity", |row| &row.identity);
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub(super) fn parse_table_update(
|
||||
raw_updates: __ws::v2::TableUpdate,
|
||||
) -> __sdk::Result<__sdk::TableUpdate<TaskPart>> {
|
||||
__sdk::TableUpdate::parse_table_update(raw_updates).map_err(|e| {
|
||||
__sdk::InternalError::failed_parse("TableUpdate<TaskPart>", "TableUpdate")
|
||||
.with_cause(e)
|
||||
.into()
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
/// Extension trait for query builder access to the table `TaskPart`.
|
||||
///
|
||||
/// Implemented for [`__sdk::QueryTableAccessor`].
|
||||
pub trait task_partQueryTableAccess {
|
||||
#[allow(non_snake_case)]
|
||||
/// Get a query builder for the table `TaskPart`.
|
||||
fn task_part(&self) -> __sdk::__query_builder::Table<TaskPart>;
|
||||
}
|
||||
|
||||
impl task_partQueryTableAccess for __sdk::QueryTableAccessor {
|
||||
fn task_part(&self) -> __sdk::__query_builder::Table<TaskPart> {
|
||||
__sdk::__query_builder::Table::new("task_part")
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
use super::action_type::Action;
|
||||
|
||||
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
|
||||
#[sats(crate = __lib)]
|
||||
pub struct TaskPart {
|
||||
pub identity: __sdk::Identity,
|
||||
pub start_of_current: __sdk::Timestamp,
|
||||
pub current: Action,
|
||||
pub upcoming: Vec<Action>,
|
||||
}
|
||||
|
||||
impl __sdk::InModule for TaskPart {
|
||||
type Module = super::RemoteModule;
|
||||
}
|
||||
|
||||
/// Column accessor struct for the table `TaskPart`.
|
||||
///
|
||||
/// Provides typed access to columns for query building.
|
||||
pub struct TaskPartCols {
|
||||
pub identity: __sdk::__query_builder::Col<TaskPart, __sdk::Identity>,
|
||||
pub start_of_current: __sdk::__query_builder::Col<TaskPart, __sdk::Timestamp>,
|
||||
pub current: __sdk::__query_builder::Col<TaskPart, Action>,
|
||||
pub upcoming: __sdk::__query_builder::Col<TaskPart, Vec<Action>>,
|
||||
}
|
||||
|
||||
impl __sdk::__query_builder::HasCols for TaskPart {
|
||||
type Cols = TaskPartCols;
|
||||
fn cols(table_name: &'static str) -> Self::Cols {
|
||||
TaskPartCols {
|
||||
identity: __sdk::__query_builder::Col::new(table_name, "identity"),
|
||||
start_of_current: __sdk::__query_builder::Col::new(table_name, "start_of_current"),
|
||||
current: __sdk::__query_builder::Col::new(table_name, "current"),
|
||||
upcoming: __sdk::__query_builder::Col::new(table_name, "upcoming"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Indexed column accessor struct for the table `TaskPart`.
|
||||
///
|
||||
/// Provides typed access to indexed columns for query building.
|
||||
pub struct TaskPartIxCols {
|
||||
pub identity: __sdk::__query_builder::IxCol<TaskPart, __sdk::Identity>,
|
||||
}
|
||||
|
||||
impl __sdk::__query_builder::HasIxCols for TaskPart {
|
||||
type IxCols = TaskPartIxCols;
|
||||
fn ix_cols(table_name: &'static str) -> Self::IxCols {
|
||||
TaskPartIxCols {
|
||||
identity: __sdk::__query_builder::IxCol::new(table_name, "identity"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::__query_builder::CanBeLookupTable for TaskPart {}
|
||||
@@ -1,58 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
|
||||
#[sats(crate = __lib)]
|
||||
pub struct Task {
|
||||
pub id: u64,
|
||||
pub done: bool,
|
||||
pub name: String,
|
||||
pub parent: Option<u64>,
|
||||
}
|
||||
|
||||
impl __sdk::InModule for Task {
|
||||
type Module = super::RemoteModule;
|
||||
}
|
||||
|
||||
/// Column accessor struct for the table `Task`.
|
||||
///
|
||||
/// Provides typed access to columns for query building.
|
||||
pub struct TaskCols {
|
||||
pub id: __sdk::__query_builder::Col<Task, u64>,
|
||||
pub done: __sdk::__query_builder::Col<Task, bool>,
|
||||
pub name: __sdk::__query_builder::Col<Task, String>,
|
||||
pub parent: __sdk::__query_builder::Col<Task, Option<u64>>,
|
||||
}
|
||||
|
||||
impl __sdk::__query_builder::HasCols for Task {
|
||||
type Cols = TaskCols;
|
||||
fn cols(table_name: &'static str) -> Self::Cols {
|
||||
TaskCols {
|
||||
id: __sdk::__query_builder::Col::new(table_name, "id"),
|
||||
done: __sdk::__query_builder::Col::new(table_name, "done"),
|
||||
name: __sdk::__query_builder::Col::new(table_name, "name"),
|
||||
parent: __sdk::__query_builder::Col::new(table_name, "parent"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Indexed column accessor struct for the table `Task`.
|
||||
///
|
||||
/// Provides typed access to indexed columns for query building.
|
||||
pub struct TaskIxCols {
|
||||
pub id: __sdk::__query_builder::IxCol<Task, u64>,
|
||||
}
|
||||
|
||||
impl __sdk::__query_builder::HasIxCols for Task {
|
||||
type IxCols = TaskIxCols;
|
||||
fn ix_cols(table_name: &'static str) -> Self::IxCols {
|
||||
TaskIxCols {
|
||||
id: __sdk::__query_builder::IxCol::new(table_name, "id"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::__query_builder::CanBeLookupTable for Task {}
|
||||
@@ -1,159 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use super::task_type::Task;
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
/// Table handle for the table `tasks`.
|
||||
///
|
||||
/// Obtain a handle from the [`TasksTableAccess::tasks`] method on [`super::RemoteTables`],
|
||||
/// like `ctx.db.tasks()`.
|
||||
///
|
||||
/// Users are encouraged not to explicitly reference this type,
|
||||
/// but to directly chain method calls,
|
||||
/// like `ctx.db.tasks().on_insert(...)`.
|
||||
pub struct TasksTableHandle<'ctx> {
|
||||
imp: __sdk::TableHandle<Task>,
|
||||
ctx: std::marker::PhantomData<&'ctx super::RemoteTables>,
|
||||
}
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
/// Extension trait for access to the table `tasks`.
|
||||
///
|
||||
/// Implemented for [`super::RemoteTables`].
|
||||
pub trait TasksTableAccess {
|
||||
#[allow(non_snake_case)]
|
||||
/// Obtain a [`TasksTableHandle`], which mediates access to the table `tasks`.
|
||||
fn tasks(&self) -> TasksTableHandle<'_>;
|
||||
}
|
||||
|
||||
impl TasksTableAccess for super::RemoteTables {
|
||||
fn tasks(&self) -> TasksTableHandle<'_> {
|
||||
TasksTableHandle {
|
||||
imp: self.imp.get_table::<Task>("tasks"),
|
||||
ctx: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TasksInsertCallbackId(__sdk::CallbackId);
|
||||
pub struct TasksDeleteCallbackId(__sdk::CallbackId);
|
||||
|
||||
impl<'ctx> __sdk::Table for TasksTableHandle<'ctx> {
|
||||
type Row = Task;
|
||||
type EventContext = super::EventContext;
|
||||
|
||||
fn count(&self) -> u64 {
|
||||
self.imp.count()
|
||||
}
|
||||
fn iter(&self) -> impl Iterator<Item = Task> + '_ {
|
||||
self.imp.iter()
|
||||
}
|
||||
|
||||
type InsertCallbackId = TasksInsertCallbackId;
|
||||
|
||||
fn on_insert(
|
||||
&self,
|
||||
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
|
||||
) -> TasksInsertCallbackId {
|
||||
TasksInsertCallbackId(self.imp.on_insert(Box::new(callback)))
|
||||
}
|
||||
|
||||
fn remove_on_insert(&self, callback: TasksInsertCallbackId) {
|
||||
self.imp.remove_on_insert(callback.0)
|
||||
}
|
||||
|
||||
type DeleteCallbackId = TasksDeleteCallbackId;
|
||||
|
||||
fn on_delete(
|
||||
&self,
|
||||
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
|
||||
) -> TasksDeleteCallbackId {
|
||||
TasksDeleteCallbackId(self.imp.on_delete(Box::new(callback)))
|
||||
}
|
||||
|
||||
fn remove_on_delete(&self, callback: TasksDeleteCallbackId) {
|
||||
self.imp.remove_on_delete(callback.0)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TasksUpdateCallbackId(__sdk::CallbackId);
|
||||
|
||||
impl<'ctx> __sdk::TableWithPrimaryKey for TasksTableHandle<'ctx> {
|
||||
type UpdateCallbackId = TasksUpdateCallbackId;
|
||||
|
||||
fn on_update(
|
||||
&self,
|
||||
callback: impl FnMut(&Self::EventContext, &Self::Row, &Self::Row) + Send + 'static,
|
||||
) -> TasksUpdateCallbackId {
|
||||
TasksUpdateCallbackId(self.imp.on_update(Box::new(callback)))
|
||||
}
|
||||
|
||||
fn remove_on_update(&self, callback: TasksUpdateCallbackId) {
|
||||
self.imp.remove_on_update(callback.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Access to the `id` unique index on the table `tasks`,
|
||||
/// which allows point queries on the field of the same name
|
||||
/// via the [`TasksIdUnique::find`] method.
|
||||
///
|
||||
/// Users are encouraged not to explicitly reference this type,
|
||||
/// but to directly chain method calls,
|
||||
/// like `ctx.db.tasks().id().find(...)`.
|
||||
pub struct TasksIdUnique<'ctx> {
|
||||
imp: __sdk::UniqueConstraintHandle<Task, u64>,
|
||||
phantom: std::marker::PhantomData<&'ctx super::RemoteTables>,
|
||||
}
|
||||
|
||||
impl<'ctx> TasksTableHandle<'ctx> {
|
||||
/// Get a handle on the `id` unique index on the table `tasks`.
|
||||
pub fn id(&self) -> TasksIdUnique<'ctx> {
|
||||
TasksIdUnique {
|
||||
imp: self.imp.get_unique_constraint::<u64>("id"),
|
||||
phantom: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ctx> TasksIdUnique<'ctx> {
|
||||
/// Find the subscribed row whose `id` column value is equal to `col_val`,
|
||||
/// if such a row is present in the client cache.
|
||||
pub fn find(&self, col_val: &u64) -> Option<Task> {
|
||||
self.imp.find(col_val)
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub(super) fn register_table(client_cache: &mut __sdk::ClientCache<super::RemoteModule>) {
|
||||
let _table = client_cache.get_or_make_table::<Task>("tasks");
|
||||
_table.add_unique_constraint::<u64>("id", |row| &row.id);
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub(super) fn parse_table_update(
|
||||
raw_updates: __ws::v2::TableUpdate,
|
||||
) -> __sdk::Result<__sdk::TableUpdate<Task>> {
|
||||
__sdk::TableUpdate::parse_table_update(raw_updates).map_err(|e| {
|
||||
__sdk::InternalError::failed_parse("TableUpdate<Task>", "TableUpdate")
|
||||
.with_cause(e)
|
||||
.into()
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
/// Extension trait for query builder access to the table `Task`.
|
||||
///
|
||||
/// Implemented for [`__sdk::QueryTableAccessor`].
|
||||
pub trait tasksQueryTableAccess {
|
||||
#[allow(non_snake_case)]
|
||||
/// Get a query builder for the table `Task`.
|
||||
fn tasks(&self) -> __sdk::__query_builder::Table<Task>;
|
||||
}
|
||||
|
||||
impl tasksQueryTableAccess for __sdk::QueryTableAccessor {
|
||||
fn tasks(&self) -> __sdk::__query_builder::Table<Task> {
|
||||
__sdk::__query_builder::Table::new("tasks")
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
use super::activity_type::Activity;
|
||||
|
||||
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
|
||||
#[sats(crate = __lib)]
|
||||
pub(super) struct UpdateActivityArgs {
|
||||
pub activity: Activity,
|
||||
}
|
||||
|
||||
impl From<UpdateActivityArgs> for super::Reducer {
|
||||
fn from(args: UpdateActivityArgs) -> Self {
|
||||
Self::UpdateActivity {
|
||||
activity: args.activity,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::InModule for UpdateActivityArgs {
|
||||
type Module = super::RemoteModule;
|
||||
}
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
/// Extension trait for access to the reducer `update_activity`.
|
||||
///
|
||||
/// Implemented for [`super::RemoteReducers`].
|
||||
pub trait update_activity {
|
||||
/// Request that the remote module invoke the reducer `update_activity` to run as soon as possible.
|
||||
///
|
||||
/// This method returns immediately, and errors only if we are unable to send the request.
|
||||
/// The reducer will run asynchronously in the future,
|
||||
/// and this method provides no way to listen for its completion status.
|
||||
/// /// Use [`update_activity:update_activity_then`] to run a callback after the reducer completes.
|
||||
fn update_activity(&self, activity: Activity) -> __sdk::Result<()> {
|
||||
self.update_activity_then(activity, |_, _| {})
|
||||
}
|
||||
|
||||
/// Request that the remote module invoke the reducer `update_activity` to run as soon as possible,
|
||||
/// registering `callback` to run when we are notified that the reducer completed.
|
||||
///
|
||||
/// This method returns immediately, and errors only if we are unable to send the request.
|
||||
/// The reducer will run asynchronously in the future,
|
||||
/// and its status can be observed with the `callback`.
|
||||
fn update_activity_then(
|
||||
&self,
|
||||
activity: Activity,
|
||||
|
||||
callback: impl FnOnce(&super::ReducerEventContext, Result<Result<(), String>, __sdk::InternalError>)
|
||||
+ Send
|
||||
+ 'static,
|
||||
) -> __sdk::Result<()>;
|
||||
}
|
||||
|
||||
impl update_activity for super::RemoteReducers {
|
||||
fn update_activity_then(
|
||||
&self,
|
||||
activity: Activity,
|
||||
|
||||
callback: impl FnOnce(&super::ReducerEventContext, Result<Result<(), String>, __sdk::InternalError>)
|
||||
+ Send
|
||||
+ 'static,
|
||||
) -> __sdk::Result<()> {
|
||||
self.imp
|
||||
.invoke_reducer_with_callback(UpdateActivityArgs { activity }, callback)
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
|
||||
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
|
||||
|
||||
#![allow(unused, clippy::all)]
|
||||
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
|
||||
|
||||
use super::action_type::Action;
|
||||
|
||||
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
|
||||
#[sats(crate = __lib)]
|
||||
pub(super) struct UpdateUpcomingArgs {
|
||||
pub upcoming: Vec<Action>,
|
||||
}
|
||||
|
||||
impl From<UpdateUpcomingArgs> for super::Reducer {
|
||||
fn from(args: UpdateUpcomingArgs) -> Self {
|
||||
Self::UpdateUpcoming {
|
||||
upcoming: args.upcoming,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl __sdk::InModule for UpdateUpcomingArgs {
|
||||
type Module = super::RemoteModule;
|
||||
}
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
/// Extension trait for access to the reducer `update_upcoming`.
|
||||
///
|
||||
/// Implemented for [`super::RemoteReducers`].
|
||||
pub trait update_upcoming {
|
||||
/// Request that the remote module invoke the reducer `update_upcoming` to run as soon as possible.
|
||||
///
|
||||
/// This method returns immediately, and errors only if we are unable to send the request.
|
||||
/// The reducer will run asynchronously in the future,
|
||||
/// and this method provides no way to listen for its completion status.
|
||||
/// /// Use [`update_upcoming:update_upcoming_then`] to run a callback after the reducer completes.
|
||||
fn update_upcoming(&self, upcoming: Vec<Action>) -> __sdk::Result<()> {
|
||||
self.update_upcoming_then(upcoming, |_, _| {})
|
||||
}
|
||||
|
||||
/// Request that the remote module invoke the reducer `update_upcoming` to run as soon as possible,
|
||||
/// registering `callback` to run when we are notified that the reducer completed.
|
||||
///
|
||||
/// This method returns immediately, and errors only if we are unable to send the request.
|
||||
/// The reducer will run asynchronously in the future,
|
||||
/// and its status can be observed with the `callback`.
|
||||
fn update_upcoming_then(
|
||||
&self,
|
||||
upcoming: Vec<Action>,
|
||||
|
||||
callback: impl FnOnce(&super::ReducerEventContext, Result<Result<(), String>, __sdk::InternalError>)
|
||||
+ Send
|
||||
+ 'static,
|
||||
) -> __sdk::Result<()>;
|
||||
}
|
||||
|
||||
impl update_upcoming for super::RemoteReducers {
|
||||
fn update_upcoming_then(
|
||||
&self,
|
||||
upcoming: Vec<Action>,
|
||||
|
||||
callback: impl FnOnce(&super::ReducerEventContext, Result<Result<(), String>, __sdk::InternalError>)
|
||||
+ Send
|
||||
+ 'static,
|
||||
) -> __sdk::Result<()> {
|
||||
self.imp
|
||||
.invoke_reducer_with_callback(UpdateUpcomingArgs { upcoming }, callback)
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
[package]
|
||||
name = "marts"
|
||||
description = "marts = mize_parts - parts collection of the Mize framework"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "4.5.59", optional = true, features = ["string"] }
|
||||
flume = "0.12.0"
|
||||
futures = "0.3.32"
|
||||
mize = { path = "../mize/", default-features = false }
|
||||
tokio = "1.49.0"
|
||||
# https://github.com/rscarson/rustyscript/pull/415
|
||||
#rustyscript = { git = 'https://github.com/rscarson/rustyscript', rev = 'e39529eac2c5d37cfcbb7d7d63da7264d7a5afdb', optional = true }
|
||||
#deno_core = { version = "0.380.1", optional = true }
|
||||
chrono = "0.4.44"
|
||||
reqwest = { version = "0.13.2", features = ["blocking", "json"] }
|
||||
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", "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]
|
||||
path = "lib.rs"
|
||||
@@ -1,421 +0,0 @@
|
||||
use chrono::{DateTime, TimeDelta, Utc};
|
||||
use mize::{
|
||||
item::ItemData, mize_err, mize_part, Mize, MizeError, MizePart, MizePartCreate, MizeResult,
|
||||
};
|
||||
use openidconnect::{
|
||||
ClientId, DeviceAuthorizationResponse, EmptyExtraDeviceAuthorizationFields, IssuerUrl,
|
||||
OAuth2TokenResponse, RefreshToken, Scope, TokenResponse,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{path::PathBuf, thread};
|
||||
|
||||
// console_log macro
|
||||
// that can be copied into other files for debugging purposes
|
||||
#[cfg(feature = "target-obsidian")]
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
#[cfg(feature = "target-obsidian")]
|
||||
#[wasm_bindgen]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(js_namespace = console)]
|
||||
fn log(s: &str);
|
||||
}
|
||||
|
||||
#[cfg(feature = "target-obsidian")]
|
||||
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())})
|
||||
}
|
||||
|
||||
#[cfg(feature = "target-os")]
|
||||
use clap::Command;
|
||||
|
||||
#[derive(Default)]
|
||||
#[mize_part]
|
||||
pub struct ClientAuth {
|
||||
mize: Mize,
|
||||
secrets: Option<ClientSecrets>,
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct ClientSecrets {
|
||||
id_token: String,
|
||||
access_token: String,
|
||||
refresh_token: String,
|
||||
expiry: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl MizePartCreate for ClientAuth {}
|
||||
|
||||
impl MizePart for ClientAuth {
|
||||
fn name(&self) -> &'static str {
|
||||
"client_auth"
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientAuth {
|
||||
pub fn id_token(&self) -> MizeResult<&str> {
|
||||
if self.secrets.is_none() {
|
||||
return Err(mize_err!("Client not logged in"));
|
||||
}
|
||||
Ok(&self.secrets.as_ref().unwrap().id_token)
|
||||
}
|
||||
|
||||
pub fn access_token(&self) -> MizeResult<&str> {
|
||||
if self.secrets.is_none() {
|
||||
return Err(mize_err!("Client not logged in"));
|
||||
}
|
||||
Ok(&self.secrets.as_ref().unwrap().access_token)
|
||||
}
|
||||
|
||||
pub fn refresh_token(&self) -> MizeResult<&str> {
|
||||
if self.secrets.is_none() {
|
||||
return Err(mize_err!("Client not logged in"));
|
||||
}
|
||||
Ok(&self.secrets.as_ref().unwrap().refresh_token)
|
||||
}
|
||||
|
||||
pub fn refresh(&mut self) -> MizeResult<()> {
|
||||
let secrets = self.secrets.clone().ok_or(mize_err!(
|
||||
"no client secrets, meaning the refresh thread can't use the refresh token"
|
||||
))?;
|
||||
self.mize.spawn_async_blocking(
|
||||
"auth.refresh_flow",
|
||||
refresh_flow(self.mize.clone(), secrets),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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::<ClientAuth>("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::<ClientAuth>("auth")?;
|
||||
auth.refresh()?;
|
||||
drop(auth);
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn client_auth(mize: &mut Mize) -> MizeResult<()> {
|
||||
let mize_clone = mize.clone();
|
||||
|
||||
let mut secrets = match read_secrets(mize) {
|
||||
Ok(secrets) => Some(secrets),
|
||||
Err(err) => {
|
||||
println!("err reading secrets: {:?}", err);
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
// do a refresh if the tokens have expired
|
||||
if secrets.is_some() && secrets.clone().unwrap().expiry < Utc::now() {
|
||||
secrets = Some(
|
||||
mize.spawn_async_blocking("refresh_low", refresh_flow(mize.clone(), secrets.unwrap()))?,
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "target-os")]
|
||||
{
|
||||
let mut cli = mize.get_part_native::<crate::CliPart>("cli")?;
|
||||
cli.subcommand(Command::new("login"), |_, mut mize| {
|
||||
let mut auth = mize.get_part_native::<ClientAuth>("client_auth")?;
|
||||
println!("secrets: {:?}", auth.secrets);
|
||||
let secrets = if auth.secrets.is_some() {
|
||||
match mize.spawn_async_blocking(
|
||||
"client_auth",
|
||||
refresh_flow(mize.clone(), auth.secrets.clone().unwrap()),
|
||||
) {
|
||||
Ok(secrets) => secrets,
|
||||
Err(err) => {
|
||||
println!("err refreshing secrets: {:?}", err);
|
||||
mize.spawn_async_blocking("client_auth", auth_flow(mize_clone))?
|
||||
}
|
||||
}
|
||||
} else {
|
||||
mize.spawn_async_blocking("client_auth", auth_flow(mize_clone))?
|
||||
};
|
||||
write_secrets(&mut mize, &secrets)?;
|
||||
auth.secrets = Some(secrets);
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(feature = "target-obsidian")]
|
||||
{}
|
||||
|
||||
// check if login token is stil valid refresh if not
|
||||
/*
|
||||
if secrets.is_some() {
|
||||
secrets = Some(mize.spawn_async_blocking(
|
||||
"client_auth",
|
||||
refresh_flow(mize.clone(), secrets.clone().unwrap()),
|
||||
)?);
|
||||
}
|
||||
*/
|
||||
|
||||
mize.register_part(Box::new(ClientAuth {
|
||||
secrets,
|
||||
mize: mize.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn read_secrets(mize: &mut Mize) -> MizeResult<ClientSecrets> {
|
||||
let mize_dir = mize.get_config("data_dir")?.value_string()?;
|
||||
let secrets_file_path = PathBuf::from(mize_dir).join("client_secrets.json");
|
||||
|
||||
let secrets_string = std::fs::read_to_string(secrets_file_path)?;
|
||||
let secrets: ClientSecrets = serde_json::from_str(&secrets_string)?;
|
||||
Ok(secrets)
|
||||
}
|
||||
|
||||
fn write_secrets(mize: &mut Mize, secrets: &ClientSecrets) -> MizeResult<()> {
|
||||
let mize_dir = mize.get_config("data_dir")?.value_string()?;
|
||||
let secrets_file_path = PathBuf::from(mize_dir).join("client_secrets.json");
|
||||
|
||||
let secrets_string = serde_json::to_string(secrets)?;
|
||||
std::fs::write(secrets_file_path, secrets_string)?;
|
||||
|
||||
// update the spacetimedb_token in XDG_CONFIG_HOME/spacetime/cli.toml config file if configured to do so
|
||||
if mize
|
||||
.get_config("auth.client.update_spacetime_token")
|
||||
.unwrap_or(ItemData::empty())
|
||||
.as_bool()
|
||||
.unwrap_or(false)
|
||||
{
|
||||
update_spacetimedb_token(&secrets.id_token.as_str())?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
use openidconnect::reqwest::Client as HttpClient;
|
||||
use openidconnect::DeviceAuthorizationUrl;
|
||||
use std::time::Duration;
|
||||
|
||||
async fn refresh_flow(mut mize: Mize, old_secrets: ClientSecrets) -> MizeResult<ClientSecrets> {
|
||||
println!("Refresh flow...");
|
||||
let issuer = mize.get_config("auth.client.issuer")?.value_string()?;
|
||||
let client_id = mize.get_config("auth.client.client_id")?.value_string()?;
|
||||
|
||||
let issuer = IssuerUrl::new(issuer)?;
|
||||
let client_id = ClientId::new(client_id);
|
||||
|
||||
let http_client = HttpClient::new();
|
||||
|
||||
// Teach openidconnect-rs about the device authorization url.
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
struct MyExtraProviderMetadata {
|
||||
device_authorization_endpoint: String,
|
||||
}
|
||||
use openidconnect::core::{
|
||||
CoreAuthDisplay, CoreClaimName, CoreClaimType, CoreClient, CoreClientAuthMethod,
|
||||
CoreGrantType, CoreJsonWebKey, CoreJweContentEncryptionAlgorithm,
|
||||
CoreJweKeyManagementAlgorithm, CoreResponseMode, CoreResponseType,
|
||||
CoreSubjectIdentifierType,
|
||||
};
|
||||
use openidconnect::AdditionalProviderMetadata;
|
||||
use openidconnect::ProviderMetadata;
|
||||
impl AdditionalProviderMetadata for MyExtraProviderMetadata {}
|
||||
type MyProviderMetadata = ProviderMetadata<
|
||||
MyExtraProviderMetadata,
|
||||
CoreAuthDisplay,
|
||||
CoreClientAuthMethod,
|
||||
CoreClaimName,
|
||||
CoreClaimType,
|
||||
CoreGrantType,
|
||||
CoreJweContentEncryptionAlgorithm,
|
||||
CoreJweKeyManagementAlgorithm,
|
||||
CoreJsonWebKey,
|
||||
CoreResponseMode,
|
||||
CoreResponseType,
|
||||
CoreSubjectIdentifierType,
|
||||
>;
|
||||
|
||||
// Discover provider metadata
|
||||
let provider_metadata: MyProviderMetadata =
|
||||
MyProviderMetadata::discover_async(issuer, &http_client).await?;
|
||||
|
||||
let device_auth_url = provider_metadata
|
||||
.additional_metadata()
|
||||
.device_authorization_endpoint
|
||||
.clone();
|
||||
|
||||
let client = CoreClient::from_provider_metadata(
|
||||
provider_metadata,
|
||||
client_id,
|
||||
None, // public client
|
||||
)
|
||||
.set_device_authorization_url(DeviceAuthorizationUrl::new(device_auth_url)?);
|
||||
|
||||
let refresh_token = RefreshToken::new(old_secrets.refresh_token);
|
||||
let res = client
|
||||
.exchange_refresh_token(&refresh_token)?
|
||||
.request_async(&http_client)
|
||||
.await?;
|
||||
let expires_in = res.expires_in().ok_or(mize_err!(
|
||||
"no expiry information was in token response of the refresh flow"
|
||||
))?;
|
||||
|
||||
return Ok(ClientSecrets {
|
||||
id_token: res.id_token().unwrap().to_string(),
|
||||
access_token: res.access_token().secret().to_owned(),
|
||||
refresh_token: res.refresh_token().unwrap().secret().to_owned(),
|
||||
expiry: Utc::now() + expires_in,
|
||||
});
|
||||
}
|
||||
|
||||
async fn auth_flow(mut mize: Mize) -> MizeResult<ClientSecrets> {
|
||||
let issuer = mize.get_config("auth.client.issuer")?.value_string()?;
|
||||
let client_id = mize.get_config("auth.client.client_id")?.value_string()?;
|
||||
|
||||
let issuer = IssuerUrl::new(issuer)?;
|
||||
let client_id = ClientId::new(client_id);
|
||||
|
||||
let http_client = HttpClient::new();
|
||||
|
||||
// Teach openidconnect-rs about the device authorization url.
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
struct MyExtraProviderMetadata {
|
||||
device_authorization_endpoint: String,
|
||||
}
|
||||
use openidconnect::core::{
|
||||
CoreAuthDisplay, CoreClaimName, CoreClaimType, CoreClient, CoreClientAuthMethod,
|
||||
CoreGrantType, CoreJsonWebKey, CoreJweContentEncryptionAlgorithm,
|
||||
CoreJweKeyManagementAlgorithm, CoreResponseMode, CoreResponseType,
|
||||
CoreSubjectIdentifierType,
|
||||
};
|
||||
use openidconnect::AdditionalProviderMetadata;
|
||||
use openidconnect::ProviderMetadata;
|
||||
impl AdditionalProviderMetadata for MyExtraProviderMetadata {}
|
||||
type MyProviderMetadata = ProviderMetadata<
|
||||
MyExtraProviderMetadata,
|
||||
CoreAuthDisplay,
|
||||
CoreClientAuthMethod,
|
||||
CoreClaimName,
|
||||
CoreClaimType,
|
||||
CoreGrantType,
|
||||
CoreJweContentEncryptionAlgorithm,
|
||||
CoreJweKeyManagementAlgorithm,
|
||||
CoreJsonWebKey,
|
||||
CoreResponseMode,
|
||||
CoreResponseType,
|
||||
CoreSubjectIdentifierType,
|
||||
>;
|
||||
|
||||
// Discover provider metadata
|
||||
let provider_metadata: MyProviderMetadata =
|
||||
MyProviderMetadata::discover_async(issuer, &http_client).await?;
|
||||
|
||||
let device_auth_url = provider_metadata
|
||||
.additional_metadata()
|
||||
.device_authorization_endpoint
|
||||
.clone();
|
||||
|
||||
let client = CoreClient::from_provider_metadata(
|
||||
provider_metadata,
|
||||
client_id,
|
||||
None, // public client
|
||||
)
|
||||
.set_device_authorization_url(DeviceAuthorizationUrl::new(device_auth_url)?);
|
||||
|
||||
// ===== DEVICE AUTH REQUEST =====
|
||||
let details: Result<DeviceAuthorizationResponse<EmptyExtraDeviceAuthorizationFields>, _> =
|
||||
client
|
||||
.exchange_device_code()
|
||||
.add_scope(Scope::new("openid".into()))
|
||||
.add_scope(Scope::new("profile".into()))
|
||||
.add_scope(Scope::new("offline_access".into()))
|
||||
.request_async(&http_client)
|
||||
.await;
|
||||
|
||||
let details = match details {
|
||||
Ok(val) => val,
|
||||
Err(err) => {
|
||||
println!("err: {:?}", err);
|
||||
println!("err: {}", err);
|
||||
panic!();
|
||||
}
|
||||
};
|
||||
|
||||
println!(
|
||||
"If your browser does not open automatically, open this URL in it:\n{}\n",
|
||||
details.verification_uri_complete().unwrap().secret()
|
||||
);
|
||||
println!(
|
||||
"Or enter this PPC login code:\n{}\n",
|
||||
details.user_code().secret()
|
||||
);
|
||||
|
||||
#[cfg(feature = "target-os")]
|
||||
{
|
||||
if let Some(_) = details.verification_uri_complete() {
|
||||
let _ = webbrowser::open(details.verification_uri_complete().unwrap().secret());
|
||||
}
|
||||
}
|
||||
|
||||
let token_response = client
|
||||
.exchange_device_access_token(&details)?
|
||||
.request_async(
|
||||
&http_client,
|
||||
async |dur: Duration| {
|
||||
tokio::time::sleep(dur).await;
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
|
||||
// ===== TOKENS =====
|
||||
let id_token = token_response
|
||||
.extra_fields()
|
||||
.id_token()
|
||||
.ok_or(mize_err!("no id_token"))?;
|
||||
|
||||
let refresh = token_response
|
||||
.refresh_token()
|
||||
.ok_or(mize_err!("no refresh token present"))?;
|
||||
|
||||
let expires_in = token_response.expires_in().ok_or(mize_err!(
|
||||
"no expiry information was in token response of the refresh flow"
|
||||
))?;
|
||||
|
||||
Ok(ClientSecrets {
|
||||
id_token: id_token.to_string(),
|
||||
access_token: token_response.access_token().secret().to_string(),
|
||||
refresh_token: refresh.secret().to_owned(),
|
||||
expiry: Utc::now() + expires_in,
|
||||
})
|
||||
}
|
||||
|
||||
fn update_spacetimedb_token(new_token: &str) -> MizeResult<()> {
|
||||
// Resolve config directory
|
||||
let config_dir = match std::env::var("XDG_CONFIG_HOME") {
|
||||
Ok(val) => PathBuf::from(val),
|
||||
Err(_) => {
|
||||
let home = std::env::var("HOME")?;
|
||||
std::path::PathBuf::from(home).join(".config")
|
||||
}
|
||||
};
|
||||
|
||||
let file_path = config_dir.join("spacetime").join("cli.toml");
|
||||
|
||||
// Read existing file (or create empty document if it doesn't exist)
|
||||
let content = std::fs::read_to_string(&file_path).unwrap_or_default();
|
||||
let mut data = ItemData::from_toml(content.as_str())?;
|
||||
|
||||
// Update the field
|
||||
data.set_path("spacetimedb_token", new_token)?;
|
||||
|
||||
// Write back
|
||||
std::fs::write(&file_path, data.to_toml()?)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
use dioxus::prelude::*;
|
||||
|
||||
pub fn main() -> Element {
|
||||
rsx! {
|
||||
div {
|
||||
h1 { "my dashbaord" }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,431 +0,0 @@
|
||||
import { createClient } from "@libsql/client";
|
||||
import { drizzle } from "drizzle-orm/libsql";
|
||||
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
|
||||
import { eq } from "drizzle-orm";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
export async function init(ppc: PPC) {
|
||||
ppc.c2vi = new C2vi(ppc);
|
||||
|
||||
ppc.cli
|
||||
.command("bed", "command to run when c2vi goes to bed")
|
||||
.action(async () => {
|
||||
await save_habitica_dailies(ppc);
|
||||
await save_habitica_logs(ppc);
|
||||
});
|
||||
|
||||
ppc.cli
|
||||
.command("clearTodos", "command to run when c2vi goes to bed")
|
||||
.alias("clt")
|
||||
.action(async () => {
|
||||
const todos = await ppc.habitica.get_tasks();
|
||||
for (const todo of todos) {
|
||||
await ppc.habitica.delete_task(todo.id);
|
||||
}
|
||||
});
|
||||
|
||||
ppc.cli
|
||||
.command("listTodos", "command to run when c2vi goes to bed")
|
||||
.alias("dut")
|
||||
.action(async () => {
|
||||
const todos = await ppc.habitica.get_tasks();
|
||||
for (const todo of todos) {
|
||||
console.log(todo.text);
|
||||
}
|
||||
});
|
||||
|
||||
ppc.cli
|
||||
.command("buyHealthPotion", "command to run when c2vi goes to bed")
|
||||
.alias("buyh")
|
||||
.action(async () => {
|
||||
await ppc.habitica.api_request("POST", "/user/buy-health-potion");
|
||||
});
|
||||
|
||||
ppc.cli
|
||||
.command("addActionItems", "command to run when c2vi goes to bed")
|
||||
.alias("aal")
|
||||
.action(async () => {
|
||||
await add_action_items(ppc);
|
||||
});
|
||||
|
||||
ppc.cli
|
||||
.command("test", "a command to run some test code")
|
||||
.alias("t")
|
||||
.action(async () => {});
|
||||
|
||||
ppc.cli
|
||||
.command("skip [num]", "command to skip a habitica todo")
|
||||
.alias("sk")
|
||||
.action((num = 1) => {
|
||||
skip_habitica_todo(ppc, parseInt(num));
|
||||
});
|
||||
|
||||
ppc.cli.command("dumpLog", "dump the complete habitica log").action(() => {
|
||||
dump_habitica_logs(ppc);
|
||||
});
|
||||
|
||||
ppc.cli
|
||||
.command("listDailies", "list all dailies")
|
||||
.action(async (folder, options) => {
|
||||
const allDailies = await ppc.c2vi.db.select().from(dailiesTable).all();
|
||||
for (const task of allDailies) {
|
||||
console.log(task.id + ": " + task.text);
|
||||
}
|
||||
});
|
||||
|
||||
ppc.cli
|
||||
.command("printTask <id>", "print a specific todo")
|
||||
.action(async (id) => {
|
||||
const data = await ppc.habitica.api_request("GET", `/tasks/${id}`, {});
|
||||
console.log(data.history);
|
||||
});
|
||||
}
|
||||
|
||||
class C2vi {
|
||||
[key: string]: any;
|
||||
|
||||
constructor(ppc: PPC) {
|
||||
this.ppc = ppc;
|
||||
this.db = drizzle(
|
||||
createClient({
|
||||
url: "file://" + ppc.config.local_storage_path + "/data.db",
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function formatDate(d) {
|
||||
const pad = (n) => n.toString().padStart(2, "0");
|
||||
|
||||
// Custom YYYY-MM-DD format
|
||||
const formatted = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||||
return formatted;
|
||||
}
|
||||
|
||||
// ============= SCHEMA DEFINITION =============
|
||||
const dailiesTable = sqliteTable("habitica_dailies", {
|
||||
id: text("id").primaryKey(),
|
||||
text: text("text").notNull(),
|
||||
notes: text("notes"),
|
||||
priority: text("priority"), // 0.1, 1, 1.5, 2
|
||||
frequency: text("frequency"), // 'daily', 'weekly', etc.
|
||||
});
|
||||
const habiticaLogTable = sqliteTable("habitica_log", {
|
||||
date: text("date").primaryKey(),
|
||||
data: text("data").notNull(),
|
||||
});
|
||||
|
||||
async function save_habitica_dailies(ppc) {
|
||||
console.log("######### cli bed cmd #########");
|
||||
await ppc.c2vi.db.run(
|
||||
"CREATE TABLE IF NOT EXISTS habitica_dailies (id TEXT PRIMARY KEY, text TEXT NOT NULL, notes TEXT, priority TEXT, frequency TEXT)",
|
||||
);
|
||||
await ppc.c2vi.db.run(
|
||||
"CREATE TABLE IF NOT EXISTS habitica_log (date TEXT PRIMARY KEY, data TEXT NOT NULL)",
|
||||
);
|
||||
|
||||
// ============= DATABASE INITIALIZATION =============
|
||||
if (!ppc.config.habitica.user_id || !ppc.config.habitica.api_token) {
|
||||
console.error(
|
||||
"Error: HABITICA_USER_ID and HABITICA_API_TOKEN env vars required",
|
||||
);
|
||||
console.error(
|
||||
"Get these from Habitica Settings > API and configure them in the ppc.config",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const dailies = await ppc.habitica.get_tasks("dailys");
|
||||
|
||||
await writeDailiesToDatabase(dailies, ppc);
|
||||
}
|
||||
|
||||
async function dump_habitica_logs(ppc) {
|
||||
const entries = await ppc.c2vi.db.select().from(habiticaLogTable).all();
|
||||
for (const entry of entries) {
|
||||
console.log(entry.date + ": ", JSON.parse(entry.data));
|
||||
}
|
||||
}
|
||||
|
||||
async function skip_habitica_todo(ppc, num) {
|
||||
await ppc.c2vi.db.run(
|
||||
"CREATE TABLE IF NOT EXISTS habitica_dailies (id TEXT PRIMARY KEY, text TEXT NOT NULL, notes TEXT, priority TEXT, frequency TEXT)",
|
||||
);
|
||||
await ppc.c2vi.db.run(
|
||||
"CREATE TABLE IF NOT EXISTS habitica_log (date TEXT PRIMARY KEY, data TEXT NOT NULL)",
|
||||
);
|
||||
|
||||
const todos = await ppc.habitica.get_tasks("todos");
|
||||
|
||||
const date = new Date();
|
||||
const save_for_yesterday = date.getHours() < 12;
|
||||
if (save_for_yesterday) {
|
||||
console.log(
|
||||
"Saving logs for yesterday!!!! because it is " +
|
||||
date.getHours() +
|
||||
"hours of the day",
|
||||
);
|
||||
date.setDate(date.getDate() - 1);
|
||||
}
|
||||
|
||||
const result = await ppc.c2vi.db
|
||||
.select()
|
||||
.from(habiticaLogTable)
|
||||
.where(eq(habiticaLogTable.date, formatDate(date)));
|
||||
|
||||
const data = result[0]
|
||||
? JSON.parse(result[0].data)
|
||||
: {
|
||||
dailies_done: [],
|
||||
dailies_skipped: [],
|
||||
todos_done: [],
|
||||
todos_skipped: [],
|
||||
};
|
||||
|
||||
for (let i = 0; i < num; i++) {
|
||||
const todo = todos[i];
|
||||
if (!todo) continue;
|
||||
await ppc.habitica.delete_task(todo.id);
|
||||
await incrementHabit(ppc);
|
||||
|
||||
data.todos_skipped.push({
|
||||
id: todo.id,
|
||||
text: todo.text,
|
||||
notes: todo.notes || "",
|
||||
checklist: todo.checklist || [],
|
||||
tags: todo.tags || [],
|
||||
});
|
||||
}
|
||||
|
||||
// saving to db
|
||||
await ppc.c2vi.db
|
||||
.insert(habiticaLogTable)
|
||||
.values({ date: formatDate(date), data: JSON.stringify(data) })
|
||||
.onConflictDoUpdate({
|
||||
target: habiticaLogTable.date,
|
||||
set: {
|
||||
data: JSON.stringify(data),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function save_habitica_logs(ppc) {
|
||||
const date = new Date();
|
||||
const save_for_yesterday = date.getHours() < 12;
|
||||
if (save_for_yesterday) {
|
||||
console.log(
|
||||
"Saving logs for yesterday!!!! because it is " +
|
||||
date.getHours() +
|
||||
"hours of the day",
|
||||
);
|
||||
date.setDate(date.getDate() - 1);
|
||||
}
|
||||
|
||||
const result = await ppc.c2vi.db
|
||||
.select()
|
||||
.from(habiticaLogTable)
|
||||
.where(eq(habiticaLogTable.date, formatDate(date)));
|
||||
|
||||
const data = result[0]
|
||||
? JSON.parse(result[0].data)
|
||||
: {
|
||||
dailies_done: [],
|
||||
dailies_skipped: [],
|
||||
todos_done: [],
|
||||
todos_skipped: [],
|
||||
};
|
||||
|
||||
// dailies
|
||||
const dailies = await ppc.habitica.get_tasks("dailys");
|
||||
for (const daily of dailies) {
|
||||
let completed = daily.completed;
|
||||
let isDue = daily.isDue;
|
||||
if (save_for_yesterday) {
|
||||
const yesterday = daily.history.reduce((prev, current) => {
|
||||
return prev.date > current.date ? prev : current;
|
||||
});
|
||||
completed = yesterday.completed;
|
||||
isDue = yesterday.isDue;
|
||||
}
|
||||
if (!isDue) {
|
||||
continue;
|
||||
}
|
||||
if (completed) {
|
||||
data.dailies_done.push(daily.id);
|
||||
console.log("daily-done: " + daily.text);
|
||||
} else {
|
||||
data.dailies_skipped.push(daily.id);
|
||||
console.log("daily-skipped: " + daily.text);
|
||||
}
|
||||
}
|
||||
|
||||
// todos done
|
||||
const todos = await ppc.habitica.get_tasks("completedTodos");
|
||||
for (const todo of todos) {
|
||||
const dateCompleted = new Date(todo.dateCompleted);
|
||||
|
||||
// check if this todo is already saved in yesterday's log entry
|
||||
if (save_for_yesterday) {
|
||||
// get yesterday log entry
|
||||
const result = await ppc.c2vi.db
|
||||
.select()
|
||||
.from(habiticaLogTable)
|
||||
.where(eq(habiticaLogTable.date, formatDate(date)));
|
||||
|
||||
const data = result[0]
|
||||
? JSON.parse(result[0].data)
|
||||
: {
|
||||
dailies_done: [],
|
||||
dailies_skipped: [],
|
||||
todos_done: [],
|
||||
todos_skipped: [],
|
||||
};
|
||||
|
||||
// check if this todo is already saved in yesterday's log entry
|
||||
const todoIndex = data.todos_done.findIndex((t) => t.id === todo.id);
|
||||
if (todoIndex !== -1) {
|
||||
continue; // skipp saving this todo
|
||||
}
|
||||
}
|
||||
|
||||
if (dateCompleted.toDateString() == date.toDateString()) {
|
||||
console.log("todo-done:", todo.text);
|
||||
data.todos_done.push({
|
||||
id: todo.id,
|
||||
text: todo.text,
|
||||
notes: todo.notes || "",
|
||||
checklist: todo.checklist || [],
|
||||
tags: todo.tags || [],
|
||||
});
|
||||
}
|
||||
|
||||
// we save_for_yesterday but the todo was completed today... also save that for this day
|
||||
if (
|
||||
save_for_yesterday &&
|
||||
dateCompleted.toDateString() == new Date().toDateString()
|
||||
) {
|
||||
console.log("todo-done:", todo.text);
|
||||
data.todos_done.push({
|
||||
id: todo.id,
|
||||
text: todo.text,
|
||||
notes: todo.notes || "",
|
||||
checklist: todo.checklist || [],
|
||||
tags: todo.tags || [],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// saving to db
|
||||
await ppc.c2vi.db
|
||||
.insert(habiticaLogTable)
|
||||
.values({ date: formatDate(date), data: JSON.stringify(data) })
|
||||
.onConflictDoUpdate({
|
||||
target: habiticaLogTable.date,
|
||||
set: {
|
||||
data: JSON.stringify(data),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function writeDailiesToDatabase(dailies, ppc) {
|
||||
console.log(`Syncing ${dailies.length} dailies to database...`);
|
||||
|
||||
const records = dailies.map((daily) => ({
|
||||
id: daily.id,
|
||||
text: daily.text,
|
||||
notes: daily.notes || "",
|
||||
priority: daily.priority?.toString() || null,
|
||||
frequency: daily.frequency || "daily",
|
||||
}));
|
||||
|
||||
async function upsertMany(records) {
|
||||
for (const record of records) {
|
||||
await ppc.c2vi.db
|
||||
.insert(dailiesTable)
|
||||
.values(record)
|
||||
.onConflictDoUpdate({
|
||||
target: dailiesTable.id,
|
||||
set: {
|
||||
text: record.text,
|
||||
notes: record.notes,
|
||||
priority: record.priority,
|
||||
frequency: record.frequency,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await upsertMany(records);
|
||||
}
|
||||
|
||||
async function incrementHabit(ppc) {
|
||||
const habits = await ppc.habitica.get_tasks("habits");
|
||||
let id = "";
|
||||
for (const habit of habits) {
|
||||
if ((habit.text = "skipped a planned task")) {
|
||||
id = habit.id;
|
||||
}
|
||||
}
|
||||
await ppc.habitica.api_request("POST", `tasks/${id}/score/down`);
|
||||
}
|
||||
|
||||
async function add_action_items(ppc: PPC) {
|
||||
let task_ids = [];
|
||||
|
||||
const tmpFile = path.join(os.tmpdir(), `habitica-tasks-${Date.now()}.md`);
|
||||
const initialContent = `
|
||||
gu 10min TIMER
|
||||
uw 15min FROG
|
||||
b coffee/tee/kakau
|
||||
uw FROG
|
||||
b breakfast, brush teeth, lüften
|
||||
uw FROG
|
||||
|
||||
lunch
|
||||
|
||||
uw 15min TIMER of next days FROG
|
||||
fw
|
||||
dt 30min TIMER
|
||||
|
||||
fun 20:00 (smth that can be stopped easily)
|
||||
se 21:40
|
||||
read
|
||||
bed 22:10
|
||||
`;
|
||||
|
||||
fs.writeFileSync(tmpFile, initialContent.trim());
|
||||
|
||||
spawnSync("nvim", [tmpFile], { stdio: "inherit" });
|
||||
|
||||
// read file
|
||||
const listStr = fs.readFileSync(tmpFile, "utf8");
|
||||
|
||||
// delete file
|
||||
fs.unlinkSync(tmpFile);
|
||||
|
||||
// Simple parser: filter out empty lines
|
||||
const tasks = listStr
|
||||
.split("\n")
|
||||
.map((t) => t.trim())
|
||||
.filter((t) => t.length > 0);
|
||||
|
||||
// 5. Add tasks to Habitica
|
||||
for (const todoText of tasks) {
|
||||
const data = await ppc.habitica.api_request(
|
||||
"POST",
|
||||
"tasks/user",
|
||||
{},
|
||||
{ text: todoText, type: "todo" },
|
||||
);
|
||||
task_ids.push(data.id);
|
||||
console.log(`Added to-do: '${todoText}' with id '${data.id}'`);
|
||||
}
|
||||
|
||||
// 6. Move tasks to bottom
|
||||
for (const taskId of task_ids) {
|
||||
await ppc.habitica.api_request("POST", `tasks/${taskId}/move/to/-1`);
|
||||
}
|
||||
}
|
||||
@@ -1,677 +0,0 @@
|
||||
use std::sync::Mutex;
|
||||
|
||||
use chrono::{Timelike, Utc};
|
||||
use clap::{Arg, Command};
|
||||
#[cfg(feature = "desktop")]
|
||||
use mize::item::ItemData;
|
||||
use rusqlite::{params, Connection};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
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;
|
||||
|
||||
#[mize_part]
|
||||
#[derive(Default)]
|
||||
pub struct C2vi {
|
||||
mize: Mize,
|
||||
db: Mutex<Option<Connection>>,
|
||||
}
|
||||
|
||||
impl MizePart for C2vi {
|
||||
fn opts(&self, mize: &mut Mize) {
|
||||
mize.new_opt("c2vi.local_storage_path");
|
||||
}
|
||||
}
|
||||
impl MizePartCreate for C2vi {}
|
||||
|
||||
impl C2vi {
|
||||
fn with_db<F, R>(&self, f: F) -> MizeResult<R>
|
||||
where
|
||||
F: FnOnce(&Connection) -> MizeResult<R>,
|
||||
{
|
||||
let guard = self
|
||||
.db
|
||||
.lock()
|
||||
.map_err(|e| mize_err!("DB lock poisoned: {}", e))?;
|
||||
let conn = guard
|
||||
.as_ref()
|
||||
.ok_or_else(|| mize_err!("DB not initialized"))?;
|
||||
f(conn)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn c2vi(mize: &mut Mize) -> MizeResult<()> {
|
||||
#[cfg(feature = "desktop")]
|
||||
if mize
|
||||
.get_config("c2vi.dash.enable")
|
||||
.unwrap_or(ItemData::empty())
|
||||
.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(())
|
||||
}
|
||||
|
||||
#[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<()> {
|
||||
//let storage_path = mize.get_config("c2vi.local_storage_path")?.as_
|
||||
let storage_path = "/home/me/work/app-data/ppc";
|
||||
//println!("storage_path: {}", storage_path);
|
||||
let db_path = std::path::PathBuf::from(&storage_path).join("data.db");
|
||||
let conn = Connection::open(&db_path)
|
||||
.map_err(|e| mize_err!("Failed to open C2vi database at {:?}: {}", db_path, e))?;
|
||||
|
||||
setup_tables(&conn)?;
|
||||
|
||||
let c2vi_part = C2vi {
|
||||
mize: mize.clone(),
|
||||
db: Mutex::new(Some(conn)),
|
||||
};
|
||||
mize.register_part(Box::new(c2vi_part))?;
|
||||
|
||||
// Register CLI subcommands
|
||||
let mut cli = mize.get_part_native::<CliPart>("cli")?;
|
||||
register_subcommands(&mut cli);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn setup_tables(conn: &Connection) -> MizeResult<()> {
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS habitica_dailies (
|
||||
id TEXT PRIMARY KEY,
|
||||
text TEXT NOT NULL,
|
||||
notes TEXT,
|
||||
priority TEXT,
|
||||
frequency TEXT
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| mize_err!("DB error creating habitica_dailies: {}", e))?;
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS habitica_log (
|
||||
date TEXT PRIMARY KEY,
|
||||
data TEXT NOT NULL
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| mize_err!("DB error creating habitica_log: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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)),
|
||||
);
|
||||
cli.subcommand(
|
||||
Command::new("bed").about("Command to run when c2vi goes to bed"),
|
||||
|_matches, mut mize| {
|
||||
save_habitica_dailies(&mut mize)?;
|
||||
save_habitica_logs(&mut mize)?;
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
|
||||
cli.subcommand(
|
||||
Command::new("clearTodos")
|
||||
.about("Clear all Habitica todos")
|
||||
.alias("clt"),
|
||||
|_matches, mut mize| {
|
||||
let todos = {
|
||||
let mut hab = mize.get_part_native::<Habitica>("habitica")?;
|
||||
hab.get_tasks("todos")?
|
||||
};
|
||||
let mut hab = mize.get_part_native::<Habitica>("habitica")?;
|
||||
if let Some(arr) = todos.as_array() {
|
||||
for todo in arr {
|
||||
if let Some(id) = todo["id"].as_str() {
|
||||
hab.delete_task(id)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
|
||||
cli.subcommand(
|
||||
Command::new("listTodos")
|
||||
.about("List all Habitica todos")
|
||||
.alias("dut"),
|
||||
|_matches, mut mize| {
|
||||
let mut hab = mize.get_part_native::<Habitica>("habitica")?;
|
||||
let todos = hab.get_tasks("todos")?;
|
||||
if let Some(arr) = todos.as_array() {
|
||||
for todo in arr {
|
||||
if let Some(text) = todo["text"].as_str() {
|
||||
println!("{}", text);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
|
||||
cli.subcommand(
|
||||
Command::new("buyHealthPotion")
|
||||
.about("Buy a health potion")
|
||||
.alias("buyh"),
|
||||
|_matches, mut mize| {
|
||||
let mut hab = mize.get_part_native::<Habitica>("habitica")?;
|
||||
hab.api_request(
|
||||
reqwest::Method::POST,
|
||||
"user/buy-health-potion".to_string(),
|
||||
json!({}),
|
||||
)?;
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
|
||||
cli.subcommand(
|
||||
Command::new("addActionItems")
|
||||
.about("Add action items from temp file")
|
||||
.alias("aal"),
|
||||
|_matches, mut mize| add_action_items(&mut mize),
|
||||
);
|
||||
|
||||
cli.subcommand(
|
||||
Command::new("skip")
|
||||
.about("Skip a Habitica todo")
|
||||
.alias("sk")
|
||||
.arg(Arg::new("num").default_value("1")),
|
||||
|matches, mut mize| {
|
||||
let num: usize = matches
|
||||
.get_one::<String>("num")
|
||||
.unwrap()
|
||||
.parse()
|
||||
.unwrap_or(1);
|
||||
skip_habitica_todo(&mut mize, num)
|
||||
},
|
||||
);
|
||||
|
||||
cli.subcommand(
|
||||
Command::new("dumpLog").about("Dump the complete Habitica log"),
|
||||
|_matches, mut mize| dump_habitica_logs(&mut mize),
|
||||
);
|
||||
|
||||
cli.subcommand(
|
||||
Command::new("listDailies").about("List all dailies from local DB"),
|
||||
|_matches, mut mize| {
|
||||
let c2vi = mize.get_part_native::<C2vi>("c2vi")?;
|
||||
c2vi.with_db(|conn| {
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT id, text FROM habitica_dailies")
|
||||
.map_err(|e| mize_err!("DB error: {}", e))?;
|
||||
let rows = stmt
|
||||
.query_map([], |row| {
|
||||
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
|
||||
})
|
||||
.map_err(|e| mize_err!("DB error: {}", e))?;
|
||||
for row in rows {
|
||||
let (id, text) = row.map_err(|e| mize_err!("DB error: {}", e))?;
|
||||
println!("{}: {}", id, text);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
},
|
||||
);
|
||||
|
||||
cli.subcommand(
|
||||
Command::new("printTask")
|
||||
.about("Print a specific task from Habitica")
|
||||
.arg(Arg::new("id").required(true)),
|
||||
|matches, mut mize| {
|
||||
let id = matches.get_one::<String>("id").unwrap();
|
||||
let mut hab = mize.get_part_native::<Habitica>("habitica")?;
|
||||
let data = hab.api_request(reqwest::Method::GET, format!("tasks/{}", id), json!({}))?;
|
||||
if let Some(history) = data.get("history") {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(history).unwrap_or_default()
|
||||
);
|
||||
} else {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&data).unwrap_or_default()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ============= Business Logic =============
|
||||
|
||||
fn format_date(dt: chrono::DateTime<Utc>) -> String {
|
||||
dt.format("%Y-%m-%d").to_string()
|
||||
}
|
||||
|
||||
/// Get the target date, adjusted for "save for yesterday" logic (before noon = yesterday)
|
||||
fn get_target_date() -> (String, bool) {
|
||||
let now = Utc::now();
|
||||
let save_for_yesterday = now.hour() < 12;
|
||||
let date = if save_for_yesterday {
|
||||
now - chrono::Duration::days(1)
|
||||
} else {
|
||||
now
|
||||
};
|
||||
if save_for_yesterday {
|
||||
println!(
|
||||
"Saving logs for yesterday because it is {} hours of the day",
|
||||
now.hour()
|
||||
);
|
||||
}
|
||||
(format_date(date), save_for_yesterday)
|
||||
}
|
||||
|
||||
/// Load existing log entry from DB, or return a default empty one
|
||||
fn get_or_create_log(conn: &Connection, date: &str) -> MizeResult<Value> {
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT data FROM habitica_log WHERE date = ?1")
|
||||
.map_err(|e| mize_err!("DB error: {}", e))?;
|
||||
let result: Option<String> = stmt.query_row(params![date], |row| row.get(0)).ok();
|
||||
match result {
|
||||
Some(data_str) => {
|
||||
serde_json::from_str(&data_str).map_err(|e| mize_err!("JSON parse error: {}", e))
|
||||
}
|
||||
None => Ok(json!({
|
||||
"dailies_done": [],
|
||||
"dailies_skipped": [],
|
||||
"todos_done": [],
|
||||
"todos_skipped": []
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
/// Upsert a log entry into the database
|
||||
fn upsert_log(conn: &Connection, date: &str, data: &Value) -> MizeResult<()> {
|
||||
let data_str =
|
||||
serde_json::to_string(data).map_err(|e| mize_err!("JSON serialize error: {}", e))?;
|
||||
conn.execute(
|
||||
"INSERT INTO habitica_log (date, data) VALUES (?1, ?2)
|
||||
ON CONFLICT(date) DO UPDATE SET data=excluded.data",
|
||||
params![date, data_str],
|
||||
)
|
||||
.map_err(|e| mize_err!("DB error upserting log: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save_habitica_dailies(mize: &mut Mize) -> MizeResult<()> {
|
||||
println!("######### cli bed cmd #########");
|
||||
|
||||
// Fetch dailies from Habitica
|
||||
let dailies = {
|
||||
let mut hab = mize.get_part_native::<Habitica>("habitica")?;
|
||||
hab.get_tasks("dailys")?
|
||||
};
|
||||
|
||||
// Write to database
|
||||
let c2vi = mize.get_part_native::<C2vi>("c2vi")?;
|
||||
c2vi.with_db(|conn| {
|
||||
if let Some(arr) = dailies.as_array() {
|
||||
println!("Syncing {} dailies to database...", arr.len());
|
||||
for daily in arr {
|
||||
let id = daily["id"].as_str().unwrap_or("");
|
||||
let text = daily["text"].as_str().unwrap_or("");
|
||||
let notes = daily["notes"].as_str().unwrap_or("");
|
||||
let priority = daily["priority"].to_string();
|
||||
let frequency = daily["frequency"].as_str().unwrap_or("daily");
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO habitica_dailies (id, text, notes, priority, frequency)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
text=excluded.text,
|
||||
notes=excluded.notes,
|
||||
priority=excluded.priority,
|
||||
frequency=excluded.frequency",
|
||||
params![id, text, notes, priority, frequency],
|
||||
)
|
||||
.map_err(|e| mize_err!("DB error writing daily: {}", e))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn save_habitica_logs(mize: &mut Mize) -> MizeResult<()> {
|
||||
let (date_str, save_for_yesterday) = get_target_date();
|
||||
|
||||
// Fetch dailies and completed todos from Habitica
|
||||
let (dailies, completed_todos) = {
|
||||
let mut hab = mize.get_part_native::<Habitica>("habitica")?;
|
||||
let dailies = hab.get_tasks("dailys")?;
|
||||
let completed_todos = hab.get_tasks("completedTodos")?;
|
||||
(dailies, completed_todos)
|
||||
};
|
||||
|
||||
let c2vi = mize.get_part_native::<C2vi>("c2vi")?;
|
||||
c2vi.with_db(|conn| {
|
||||
let mut data = get_or_create_log(conn, &date_str)?;
|
||||
|
||||
// Process dailies
|
||||
if let Some(arr) = dailies.as_array() {
|
||||
for daily in arr {
|
||||
let is_due = if save_for_yesterday {
|
||||
// Look at history for yesterday's status
|
||||
daily["history"]
|
||||
.as_array()
|
||||
.and_then(|h| h.iter().max_by_key(|e| e["date"].as_i64().unwrap_or(0)))
|
||||
.map(|e| e["isDue"].as_bool().unwrap_or(false))
|
||||
.unwrap_or(false)
|
||||
} else {
|
||||
daily["isDue"].as_bool().unwrap_or(false)
|
||||
};
|
||||
|
||||
if !is_due {
|
||||
continue;
|
||||
}
|
||||
|
||||
let completed = if save_for_yesterday {
|
||||
daily["history"]
|
||||
.as_array()
|
||||
.and_then(|h| h.iter().max_by_key(|e| e["date"].as_i64().unwrap_or(0)))
|
||||
.map(|e| e["completed"].as_bool().unwrap_or(false))
|
||||
.unwrap_or(false)
|
||||
} else {
|
||||
daily["completed"].as_bool().unwrap_or(false)
|
||||
};
|
||||
|
||||
let daily_id = daily["id"].as_str().unwrap_or("");
|
||||
let daily_text = daily["text"].as_str().unwrap_or("");
|
||||
|
||||
if completed {
|
||||
data["dailies_done"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.push(json!(daily_id));
|
||||
println!("daily-done: {}", daily_text);
|
||||
} else {
|
||||
data["dailies_skipped"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.push(json!(daily_id));
|
||||
println!("daily-skipped: {}", daily_text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process completed todos
|
||||
if let Some(arr) = completed_todos.as_array() {
|
||||
let today_str = format_date(Utc::now());
|
||||
for todo in arr {
|
||||
let date_completed_str = todo["dateCompleted"].as_str().unwrap_or("");
|
||||
|
||||
// Parse the completion date (ISO 8601 format from Habitica)
|
||||
let date_completed = chrono::DateTime::parse_from_rfc3339(date_completed_str)
|
||||
.map(|d| format_date(d.with_timezone(&Utc)))
|
||||
.unwrap_or_default();
|
||||
|
||||
// Check if already in the log for this date
|
||||
if save_for_yesterday {
|
||||
let existing_todos = data["todos_done"].as_array().unwrap();
|
||||
let todo_id = todo["id"].as_str().unwrap_or("");
|
||||
if existing_todos
|
||||
.iter()
|
||||
.any(|t| t["id"].as_str() == Some(todo_id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let todo_entry = json!({
|
||||
"id": todo["id"],
|
||||
"text": todo["text"],
|
||||
"notes": todo.get("notes").unwrap_or(&json!("")),
|
||||
"checklist": todo.get("checklist").unwrap_or(&json!([])),
|
||||
"tags": todo.get("tags").unwrap_or(&json!([])),
|
||||
});
|
||||
|
||||
// Save if completed on the target date
|
||||
if date_completed == date_str {
|
||||
println!("todo-done: {}", todo["text"].as_str().unwrap_or(""));
|
||||
data["todos_done"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.push(todo_entry.clone());
|
||||
}
|
||||
|
||||
// If saving for yesterday but todo was completed today, also record it
|
||||
if save_for_yesterday && date_completed == today_str {
|
||||
println!("todo-done: {}", todo["text"].as_str().unwrap_or(""));
|
||||
data["todos_done"].as_array_mut().unwrap().push(todo_entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
upsert_log(conn, &date_str, &data)?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn skip_habitica_todo(mize: &mut Mize, num: usize) -> MizeResult<()> {
|
||||
let (date_str, _) = get_target_date();
|
||||
|
||||
// Fetch todos from Habitica
|
||||
let todos = {
|
||||
let mut hab = mize.get_part_native::<Habitica>("habitica")?;
|
||||
hab.get_tasks("todos")?
|
||||
};
|
||||
|
||||
let arr = todos
|
||||
.as_array()
|
||||
.ok_or_else(|| mize_err!("Expected array of todos"))?;
|
||||
|
||||
// Delete and log each skipped todo
|
||||
for i in 0..num {
|
||||
let todo = match arr.get(i) {
|
||||
Some(t) => t,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let todo_id = todo["id"].as_str().unwrap_or("");
|
||||
|
||||
// Delete the todo and score the skip habit
|
||||
{
|
||||
let mut hab = mize.get_part_native::<Habitica>("habitica")?;
|
||||
hab.delete_task(todo_id)?;
|
||||
}
|
||||
increment_habit(mize)?;
|
||||
|
||||
// Record in log
|
||||
let c2vi = mize.get_part_native::<C2vi>("c2vi")?;
|
||||
c2vi.with_db(|conn| {
|
||||
let mut data = get_or_create_log(conn, &date_str)?;
|
||||
data["todos_skipped"].as_array_mut().unwrap().push(json!({
|
||||
"id": todo["id"],
|
||||
"text": todo["text"],
|
||||
"notes": todo.get("notes").unwrap_or(&json!("")),
|
||||
"checklist": todo.get("checklist").unwrap_or(&json!([])),
|
||||
"tags": todo.get("tags").unwrap_or(&json!([])),
|
||||
}));
|
||||
upsert_log(conn, &date_str, &data)?;
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn increment_habit(mize: &mut Mize) -> MizeResult<()> {
|
||||
let mut hab = mize.get_part_native::<Habitica>("habitica")?;
|
||||
let habits = hab.get_tasks("habits")?;
|
||||
if let Some(arr) = habits.as_array() {
|
||||
for habit in arr {
|
||||
if habit["text"].as_str() == Some("skipped a planned task") {
|
||||
let id = habit["id"].as_str().unwrap_or("");
|
||||
hab.api_request(
|
||||
reqwest::Method::POST,
|
||||
format!("tasks/{}/score/down", id),
|
||||
json!({}),
|
||||
)?;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn add_action_items(mize: &mut Mize) -> MizeResult<()> {
|
||||
let initial_content = "\
|
||||
gu 10min TIMER
|
||||
uw 15min FROG
|
||||
b coffee/tee/kakau
|
||||
uw FROG
|
||||
b breakfast, brush teeth, lüften
|
||||
uw FROG
|
||||
|
||||
lunch
|
||||
|
||||
uw 15min TIMER of next days FROG
|
||||
fw
|
||||
dt 30min TIMER
|
||||
|
||||
fun 20:00 (smth that can be stopped easily)
|
||||
se 21:40
|
||||
read
|
||||
bed 22:10";
|
||||
|
||||
let tmp_file =
|
||||
std::env::temp_dir().join(format!("habitica-tasks-{}.md", Utc::now().timestamp()));
|
||||
std::fs::write(&tmp_file, initial_content)
|
||||
.map_err(|e| mize_err!("Failed to write temp file: {}", e))?;
|
||||
|
||||
// Open in nvim for editing
|
||||
std::process::Command::new("nvim")
|
||||
.arg(&tmp_file)
|
||||
.status()
|
||||
.map_err(|e| mize_err!("Failed to run nvim: {}", e))?;
|
||||
|
||||
// Read back and parse
|
||||
let list_str = std::fs::read_to_string(&tmp_file)
|
||||
.map_err(|e| mize_err!("Failed to read temp file: {}", e))?;
|
||||
let _ = std::fs::remove_file(&tmp_file);
|
||||
|
||||
let tasks: Vec<&str> = list_str
|
||||
.lines()
|
||||
.map(|l| l.trim())
|
||||
.filter(|l| !l.is_empty())
|
||||
.collect();
|
||||
|
||||
// Add tasks to Habitica
|
||||
let mut task_ids = Vec::new();
|
||||
{
|
||||
let mut hab = mize.get_part_native::<Habitica>("habitica")?;
|
||||
for todo_text in &tasks {
|
||||
let data = hab.api_request(
|
||||
reqwest::Method::POST,
|
||||
"tasks/user".to_string(),
|
||||
json!({ "text": todo_text, "type": "todo" }),
|
||||
)?;
|
||||
let id = data["id"].as_str().unwrap_or("").to_string();
|
||||
println!("Added to-do: '{}' with id '{}'", todo_text, id);
|
||||
task_ids.push(id);
|
||||
}
|
||||
|
||||
// Move all tasks to bottom
|
||||
for task_id in &task_ids {
|
||||
hab.api_request(
|
||||
reqwest::Method::POST,
|
||||
format!("tasks/{}/move/to/-1", task_id),
|
||||
json!({}),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn dump_habitica_logs(mize: &mut Mize) -> MizeResult<()> {
|
||||
let c2vi = mize.get_part_native::<C2vi>("c2vi")?;
|
||||
c2vi.with_db(|conn| {
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT date, data FROM habitica_log ORDER BY date")
|
||||
.map_err(|e| mize_err!("DB error: {}", e))?;
|
||||
let rows = stmt
|
||||
.query_map([], |row| {
|
||||
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
|
||||
})
|
||||
.map_err(|e| mize_err!("DB error: {}", e))?;
|
||||
for row in rows {
|
||||
let (date, data_str) = row.map_err(|e| mize_err!("DB error: {}", e))?;
|
||||
let data: Value =
|
||||
serde_json::from_str(&data_str).unwrap_or(json!({"parse_error": data_str}));
|
||||
println!(
|
||||
"{}: {}",
|
||||
date,
|
||||
serde_json::to_string_pretty(&data).unwrap_or_default()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
export function c2vi_obsidian_canvas_patch(mize: any) {
|
||||
const plugin = mize.get_part_native("obsidian");
|
||||
|
||||
window.pc = patchCanvas;
|
||||
window.upc = () => {
|
||||
unpatchCanvas(plugin, plugin.app.workspace.activeLeaf);
|
||||
};
|
||||
|
||||
console.log("hereeeeeeeeeeeeeeeee");
|
||||
// canvas patching
|
||||
plugin.registerEvent(
|
||||
plugin.app.workspace.on("file-open", (file: any) => {
|
||||
if (file?.extension === "canvas") {
|
||||
maybePathCanvas(plugin, plugin.app.workspace.activeLeaf);
|
||||
}
|
||||
}),
|
||||
);
|
||||
plugin.registerEvent(
|
||||
plugin.app.workspace.on("active-leaf-change", (file: any) => {
|
||||
if (file?.extension === "canvas") {
|
||||
maybePathCanvas(plugin, plugin.app.workspace.activeLeaf);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const maybePathCanvas = (plugin: PPCObsidianPlugin, leaf: any | null) => {
|
||||
console.log("maybePathCanvas called");
|
||||
const file = plugin.app.workspace.getActiveFile();
|
||||
|
||||
if (file?.extension !== "canvas") return;
|
||||
console.log("patching canvas.....");
|
||||
|
||||
const canvas = plugin.app.workspace.activeLeaf.view.canvas;
|
||||
if ("isPatched" in canvas) return;
|
||||
|
||||
patchCanvas(plugin, leaf, canvas);
|
||||
};
|
||||
|
||||
function patchCanvas(plugin: PPCObsidianPlugin, leaf: any, canvas: any) {
|
||||
canvas.isPatched = true;
|
||||
const canvasEl = canvas.canvasEl;
|
||||
const canvasWrapperEl = canvasEl.parentElement;
|
||||
const overlay = createDiv();
|
||||
overlay.setAttr("class", "c2vi-canvas-overlay");
|
||||
const canvas_card_menue = canvasWrapperEl.childNodes[1];
|
||||
canvasWrapperEl.insertBefore(overlay, canvas_card_menue);
|
||||
Object.assign(overlay.style, {
|
||||
position: "absolute",
|
||||
inset: "0",
|
||||
//zIndex: "1337",
|
||||
});
|
||||
overlay.addEventListener("contextmenu", (e) => {
|
||||
if (e.button === 2) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
e.stopImmediatePropagation();
|
||||
}
|
||||
});
|
||||
overlay.addEventListener("mouseout", (e) => {
|
||||
const menu = document.getElementsByClassName("menu")[0];
|
||||
if (!menu) return;
|
||||
menu.addEventListener("pointerup", (e) => {
|
||||
console.log("pointerup on menu", e);
|
||||
e.target.click();
|
||||
/*
|
||||
menu.dispatchEvent(
|
||||
new MouseEvent("mousedown", {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
composed: true,
|
||||
clientX: e.clientX,
|
||||
clientY: e.clientY,
|
||||
button: e.button,
|
||||
buttons: e.buttons,
|
||||
view: window,
|
||||
}),
|
||||
);
|
||||
*/
|
||||
});
|
||||
});
|
||||
|
||||
setupEventPropagation("pointerdown", PointerEvent, overlay, canvasWrapperEl);
|
||||
setupEventPropagation("pointerup", PointerEvent, overlay, canvasWrapperEl);
|
||||
setupEventPropagation("mousedown", MouseEvent, overlay, canvasWrapperEl);
|
||||
setupEventPropagation("mouseup", MouseEvent, overlay, canvasWrapperEl);
|
||||
setupEventPropagation("click", MouseEvent, overlay, canvasWrapperEl);
|
||||
setupEventPropagation("dragstart", DragEvent, overlay, canvasWrapperEl);
|
||||
setupEventPropagation("dragstop", DragEvent, overlay, canvasWrapperEl);
|
||||
|
||||
window.a = canvasWrapperEl;
|
||||
window.b = overlay;
|
||||
|
||||
const mouseEvents = [
|
||||
"mousedown",
|
||||
"mouseup",
|
||||
"click",
|
||||
"dblclick",
|
||||
//"mousemove",
|
||||
"mouseover",
|
||||
"mouseout",
|
||||
"wheel",
|
||||
];
|
||||
|
||||
mouseEvents.forEach((eventType) => {
|
||||
canvasWrapperEl.addEventListener(
|
||||
eventType,
|
||||
(event) => {
|
||||
console.log(`Mouse Event Triggered: ${event.type}`, event);
|
||||
},
|
||||
{ passive: true },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function unpatchCanvas(plugin: PPCObsidianPlugin, leaf: any) {
|
||||
const canvas = plugin.app.workspace.activeLeaf.view.canvas;
|
||||
if (!canvas.isPatched) return;
|
||||
canvas.isPatched = false;
|
||||
const canvasEl = canvas.canvasEl;
|
||||
const canvasWrapperEl = canvasEl.parentElement;
|
||||
|
||||
const targets = canvasEl.querySelectorAll(":scope > .c2vi-canvas-overlay");
|
||||
|
||||
targets.forEach((child) => child.remove());
|
||||
}
|
||||
|
||||
function setupEventPropagation(type: string, evClass, overlay: any, target) {
|
||||
overlay.addEventListener(type, (originalEvent) => {
|
||||
originalEvent.stopPropagation();
|
||||
originalEvent.stopImmediatePropagation();
|
||||
originalEvent.preventDefault();
|
||||
const newEvent = new evClass(type, originalEvent);
|
||||
if (type == "pointerdown" && originalEvent.ctrlKey == true) {
|
||||
dispatchContextMenue(
|
||||
target,
|
||||
originalEvent.clientX,
|
||||
originalEvent.clientY,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (type === "pointerdown") {
|
||||
window.downEv = newEvent;
|
||||
}
|
||||
if (type === "pointerup") {
|
||||
window.upEv = newEvent;
|
||||
}
|
||||
newEvent.isTrusted = true;
|
||||
console.log("original Event of", type, originalEvent);
|
||||
console.log("new Event of", type, newEvent);
|
||||
target.dispatchEvent(newEvent);
|
||||
});
|
||||
}
|
||||
|
||||
function dispatchContextMenue(target, x, y) {
|
||||
const newEvent = new PointerEvent("contextmenu", {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
composed: true,
|
||||
view: window,
|
||||
clientX: x,
|
||||
clientY: y,
|
||||
pointerType: "mouse",
|
||||
button: 2,
|
||||
buttons: 2,
|
||||
pointerId: 1,
|
||||
isPrimary: true,
|
||||
});
|
||||
target.dispatchEvent(newEvent);
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
use clap::{ArgMatches, Command};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use mize::{mize_part, Mize, MizePart, MizePartCreate, MizeResult};
|
||||
|
||||
#[mize_part("cli")]
|
||||
#[derive(Default)]
|
||||
pub struct CliPart {
|
||||
mize: Mize,
|
||||
cmd: Option<Command>,
|
||||
actions: HashMap<
|
||||
String,
|
||||
Box<dyn FnOnce(&ArgMatches, Mize) -> MizeResult<()> + Send + Sync + 'static>,
|
||||
>,
|
||||
parsers:
|
||||
Option<Vec<Box<dyn FnOnce(Mize, Vec<String>) -> MizeResult<()> + Send + Sync + 'static>>>,
|
||||
}
|
||||
|
||||
pub fn cli(mize: &mut Mize) -> MizeResult<()> {
|
||||
let command = Command::new("marts-cli").allow_external_subcommands(true);
|
||||
let cli_part = CliPart {
|
||||
mize: mize.clone(),
|
||||
cmd: Some(command),
|
||||
actions: HashMap::new(),
|
||||
parsers: Some(Vec::new()),
|
||||
};
|
||||
|
||||
mize.add_part(Box::new(cli_part))
|
||||
}
|
||||
|
||||
impl MizePartCreate for CliPart {}
|
||||
|
||||
impl MizePart for CliPart {
|
||||
fn init(&mut self, _mize: &mut Mize) -> MizeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
fn run(&mut self, mize: &mut Mize) -> MizeResult<()> {
|
||||
let matches = self.cmd.take().unwrap().get_matches();
|
||||
let sub_cmd = match matches.subcommand_name() {
|
||||
Some(sub_cmd) => sub_cmd,
|
||||
None => {
|
||||
println!("No subcommand provided");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let action = match self.actions.remove(sub_cmd) {
|
||||
Some(action) => action,
|
||||
None => {
|
||||
// external parsers
|
||||
for parser in self.parsers.take().unwrap() {
|
||||
parser(
|
||||
mize.clone(),
|
||||
matches
|
||||
.subcommand_matches(sub_cmd)
|
||||
.unwrap()
|
||||
.get_many::<String>("")
|
||||
.unwrap()
|
||||
.map(|s| s.to_string())
|
||||
.collect::<Vec<String>>(),
|
||||
)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
action(matches.subcommand_matches(sub_cmd).unwrap(), mize.clone())?;
|
||||
Ok(())
|
||||
}
|
||||
fn opts(&self, mize: &mut Mize) {
|
||||
mize.new_opt("cli.name");
|
||||
}
|
||||
}
|
||||
|
||||
impl CliPart {
|
||||
pub fn subcommand<T: FnOnce(&ArgMatches, Mize) -> MizeResult<()> + Send + Sync + 'static>(
|
||||
&mut self,
|
||||
subcmd: Command,
|
||||
action: T,
|
||||
) -> &mut Command {
|
||||
let name = subcmd.get_name().to_string();
|
||||
let cmd = self.cmd.take().unwrap().subcommand(subcmd);
|
||||
self.actions.insert(name, Box::new(action));
|
||||
self.cmd = Some(cmd);
|
||||
self.cmd.as_mut().unwrap()
|
||||
}
|
||||
pub fn add_sub_parser<
|
||||
T: FnOnce(Mize, Vec<String>) -> MizeResult<()> + Send + Sync + 'static,
|
||||
>(
|
||||
&mut self,
|
||||
parser: T,
|
||||
) -> MizeResult<()> {
|
||||
self.parsers.as_mut().unwrap().push(Box::new(parser));
|
||||
Ok(())
|
||||
}
|
||||
pub fn with_cmd(
|
||||
&mut self,
|
||||
func: fn(mize: Mize, cmd: Command) -> MizeResult<Command>,
|
||||
) -> MizeResult<()> {
|
||||
let cmd = func(self.mize.clone(), self.cmd.take().unwrap())?;
|
||||
self.cmd = Some(cmd);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"name": "@ppc/marts",
|
||||
"imports": {},
|
||||
"exports": {
|
||||
".": "./index.ts"
|
||||
},
|
||||
"tasks": {}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
(() => {
|
||||
// habitica.ts
|
||||
var opts = {
|
||||
"habitica.api_url": {
|
||||
env_var_name: "PPC_HABITICA_API_URL",
|
||||
default_val: "https://habitica.com/api/v3"
|
||||
},
|
||||
"habitica.user_id": {
|
||||
env_var_name: "PPC_HABITICA_USER_ID"
|
||||
},
|
||||
"habitica.client_name": {
|
||||
default_val: "3544a0b8-d71a-46e0-9bb1-6ddbb2abcddb-PPC-Software"
|
||||
},
|
||||
"habitica.api_token": {
|
||||
env_var_name: "PPC_HABITICA_API_TOKEN"
|
||||
}
|
||||
};
|
||||
async function habitica(mize) {
|
||||
Deno.core.print("hiiiiiiiiiiiiiiiiiiii from habitica");
|
||||
log("hiiiiiiiiiiiiiiiiiiii");
|
||||
mize.add_opts(opts);
|
||||
mize.add_part(new Habitica(mize));
|
||||
}
|
||||
async function handleRateLimit(response) {
|
||||
const limit = response.headers.get("X-RateLimit-Limit") || "NONE";
|
||||
const remaining = parseInt(response.headers.get("X-RateLimit-Remaining") || "10", 10);
|
||||
const reset = response.headers.get("X-RateLimit-Reset");
|
||||
console.log(`RateLimit: ${limit} | Remaining: ${remaining} | Reset: ${reset}`);
|
||||
if (remaining < 2 && reset) {
|
||||
const resetDate = new Date(reset);
|
||||
const now = /* @__PURE__ */ new Date();
|
||||
const waitMs = resetDate.getTime() - now.getTime() + 1e3;
|
||||
if (waitMs > 0) {
|
||||
console.log(`Waiting ${Math.round(waitMs / 1e3)} secs for next rate limit window...`);
|
||||
await new Promise((resolve) => setTimeout(resolve, waitMs));
|
||||
}
|
||||
}
|
||||
}
|
||||
var Habitica = class {
|
||||
mize;
|
||||
constructor(mize) {
|
||||
this.mize = mize;
|
||||
}
|
||||
async get_tasks(type = "todos") {
|
||||
return await this.api_request("GET", `tasks/user?type=${type}`);
|
||||
}
|
||||
async delete_task(id) {
|
||||
await this.api_request("DELETE", `tasks/${id}`);
|
||||
}
|
||||
async api_request(method, path, extraHeaders = {}, data = {}) {
|
||||
const mize = this.mize;
|
||||
if (!path.startsWith("/")) {
|
||||
path = "/" + path;
|
||||
}
|
||||
const headers = Object.assign({
|
||||
"Content-Type": "application/json",
|
||||
"x-api-user": mize.get_config("habitica.user_id"),
|
||||
"x-api-key": mize.get_config("habitica.api_token"),
|
||||
"x-client": mize.get_config("habitica.client_name")
|
||||
}, extraHeaders);
|
||||
const response = await fetch(mize.get_config("habitica.api_url") + path, {
|
||||
method,
|
||||
headers,
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
await handleRateLimit(response);
|
||||
if (!response.ok) {
|
||||
console.log("request_url:", mize.get_config("habitica.api_url") + path);
|
||||
throw new Error(`Habitica API error: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
return (await response.json()).data;
|
||||
}
|
||||
};
|
||||
habitica(globalThis.mize);
|
||||
Deno.core.print("hiiiiiiiiiiiiiiiiiiii from habitica one");
|
||||
})();
|
||||
@@ -1,12 +0,0 @@
|
||||
import * as esbuild from "npm:esbuild";
|
||||
|
||||
import { denoPlugin } from "jsr:@deno/esbuild-plugin";
|
||||
|
||||
await esbuild.build({
|
||||
plugins: [denoPlugin()],
|
||||
entryPoints: ["./habitica.ts"],
|
||||
outfile: "./deno_dist/habitica.js",
|
||||
bundle: true,
|
||||
format: "iife",
|
||||
});
|
||||
esbuild.stop();
|
||||
@@ -1,128 +0,0 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
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;
|
||||
use std::time::Duration;
|
||||
|
||||
#[mize_part]
|
||||
#[derive(Default)]
|
||||
pub struct Habitica {
|
||||
mize: Mize,
|
||||
client: Client,
|
||||
}
|
||||
|
||||
pub fn habitica(mize: &mut Mize) -> MizeResult<()> {
|
||||
let client = Client::new();
|
||||
mize.register_part(Box::new(Habitica {
|
||||
mize: mize.clone(),
|
||||
client,
|
||||
}))
|
||||
}
|
||||
|
||||
impl MizePartCreate for Habitica {}
|
||||
impl MizePart for Habitica {
|
||||
fn opts(&self, mize: &mut Mize) {
|
||||
mize.new_opt("habitica.api_url");
|
||||
mize.new_opt("habitica.user_id");
|
||||
mize.new_opt("habitica.api_token");
|
||||
mize.new_opt("habitica.client_name");
|
||||
}
|
||||
}
|
||||
|
||||
impl Habitica {
|
||||
pub fn api_request(&mut self, method: Method, path: String, data: Value) -> MizeResult<Value> {
|
||||
let api_url = self.mize.get_config("habitica.api_url")?.to_string();
|
||||
let user_id = self.mize.get_config("habitica.user_id")?.to_string();
|
||||
let api_token = self.mize.get_config("habitica.api_token")?.to_string();
|
||||
let client_name = self.mize.get_config("habitica.client_name")?.to_string();
|
||||
|
||||
let mut headers = header::HeaderMap::new();
|
||||
headers.insert(
|
||||
"Content-Type",
|
||||
header::HeaderValue::from_static("application/json"),
|
||||
);
|
||||
headers.insert("x-api-user", header::HeaderValue::from_str(&user_id)?);
|
||||
headers.insert("x-api-key", header::HeaderValue::from_str(&api_token)?);
|
||||
headers.insert("x-client", header::HeaderValue::from_str(&client_name)?);
|
||||
|
||||
let url = format!("{}/{}", api_url, path.trim_start_matches('/'));
|
||||
|
||||
let mut request_builder = self.client.request(method, &url).headers(headers);
|
||||
|
||||
if data != json!({}) {
|
||||
request_builder = request_builder.json(&data);
|
||||
}
|
||||
|
||||
let response = request_builder.send()?;
|
||||
|
||||
handle_rate_limit(&response);
|
||||
|
||||
if !response.status().is_success() {
|
||||
let status = response.status();
|
||||
let text = response.text().unwrap_or_default();
|
||||
println!("request_url: {}", url);
|
||||
return Err(mize_err!(
|
||||
"Habitica API error: {} {} - {}",
|
||||
status.as_u16(),
|
||||
status.canonical_reason().unwrap_or(""),
|
||||
text
|
||||
));
|
||||
}
|
||||
|
||||
let json_response: Value = response.json()?;
|
||||
Ok(json_response.get("data").cloned().unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
pub fn get_tasks(&mut self, task_type: &str) -> MizeResult<Value> {
|
||||
self.api_request(
|
||||
Method::GET,
|
||||
format!("tasks/user?type={}", task_type),
|
||||
json!({}),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn delete_task(&mut self, id: &str) -> MizeResult<Value> {
|
||||
self.api_request(Method::DELETE, format!("tasks/{}", id), json!({}))
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_rate_limit(response: &Response) {
|
||||
let headers = response.headers();
|
||||
let limit = headers
|
||||
.get("X-RateLimit-Limit")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or("NONE");
|
||||
let remaining = headers
|
||||
.get("X-RateLimit-Remaining")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|s| s.parse::<i32>().ok())
|
||||
.unwrap_or(10);
|
||||
let reset = headers
|
||||
.get("X-RateLimit-Reset")
|
||||
.and_then(|v| v.to_str().ok());
|
||||
|
||||
println!(
|
||||
"RateLimit: {} | Remaining: {} | Reset: {}",
|
||||
limit,
|
||||
remaining,
|
||||
reset.unwrap_or("N/A")
|
||||
);
|
||||
|
||||
if remaining < 2 {
|
||||
if let Some(reset_str) = reset {
|
||||
if let Ok(reset_date) = DateTime::parse_from_rfc2822(reset_str) {
|
||||
let now = Utc::now();
|
||||
let wait_duration = reset_date.signed_duration_since(now).to_std();
|
||||
if let Ok(wait_duration) = wait_duration {
|
||||
let wait_ms = wait_duration.as_millis() as u64 + 1000;
|
||||
println!(
|
||||
"Waiting {} secs for next rate limit window...",
|
||||
(wait_ms / 1000)
|
||||
);
|
||||
sleep(Duration::from_millis(wait_ms));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
export * from "./task/obsidian-otask-parse";
|
||||
export * from "./c2vi/obsidian-canvas-patch";
|
||||
|
||||
export * from "./js/stub_deno";
|
||||
@@ -1,53 +0,0 @@
|
||||
use deno_core::extension;
|
||||
use deno_core::op2;
|
||||
use deno_core::OpState;
|
||||
use mize::{Mize, MizeError};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::CliPart;
|
||||
use crate::JsPart;
|
||||
|
||||
#[op2(fast)]
|
||||
fn op_mize_get_part(#[string] name: &str) {
|
||||
println!("js wants the part {}", name);
|
||||
}
|
||||
|
||||
#[op2]
|
||||
#[string]
|
||||
fn op_mize_get_config(state: &mut OpState, #[string] key: &str) -> String {
|
||||
let mize: Mize = state.borrow::<Mize>().clone();
|
||||
format!("config_value_for_{}", key)
|
||||
}
|
||||
|
||||
#[op2(fast)]
|
||||
fn op_mize_add_part(state: &mut OpState, #[string] key: &str) {
|
||||
let mize: Mize = state.borrow::<Mize>().clone();
|
||||
println!("adding part {}", key);
|
||||
}
|
||||
|
||||
#[op2(fast)]
|
||||
fn op_cli_subcommand(state: &mut OpState, #[string] name: String) {
|
||||
let mut mize: Mize = state.borrow::<Mize>().clone();
|
||||
let mut cli = mize.get_part_native::<CliPart>("cli").unwrap();
|
||||
cli.subcommand(
|
||||
clap::Command::new(name.clone()),
|
||||
move |_sub_matches, mut mize| {
|
||||
let mut js = mize.get_part_native::<JsPart>("js").unwrap();
|
||||
js.eval("log(\"cli command being called\")".to_string())?;
|
||||
js.eval(format!("mize.vars.cli.subcommand({name})"))?;
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Create an extension with your custom ops
|
||||
extension!(
|
||||
my_extension,
|
||||
ops = [op_mize_get_part, op_mize_get_config],
|
||||
options = {
|
||||
mize: Mize,
|
||||
},
|
||||
state = |state: &mut OpState, config: Config| {
|
||||
state.put::<Mize>(config.mize);
|
||||
},
|
||||
);
|
||||
@@ -1,11 +0,0 @@
|
||||
import { Mize } from "./stub_deno.ts";
|
||||
|
||||
function argsToMessage(...args) {
|
||||
return args.map((arg) => JSON.stringify(arg)).join(" ");
|
||||
}
|
||||
|
||||
globalThis.log = (...args) => {
|
||||
Deno.core.print(`[out]: ${argsToMessage(...args)}\n`, false);
|
||||
};
|
||||
|
||||
globalThis.mize = new Mize();
|
||||
@@ -1,136 +0,0 @@
|
||||
use deno_core::error::AnyError;
|
||||
use deno_core::url::Url;
|
||||
use deno_core::v8::OneByteConst;
|
||||
use deno_core::{
|
||||
ascii_str_include, extension, op2, JsRuntime, ModuleSpecifier, PollEventLoopOptions,
|
||||
RuntimeOptions,
|
||||
};
|
||||
use deno_core::{FastStaticString, FsModuleLoader};
|
||||
use mize::async_trait;
|
||||
use mize::instance::MizePartCreate;
|
||||
use mize::{mize_part, Mize, MizePart, MizeResult};
|
||||
use std::future::Future;
|
||||
use std::path::Path;
|
||||
use std::pin::Pin;
|
||||
use std::rc::Rc;
|
||||
use std::str::FromStr;
|
||||
use tokio::runtime::Builder;
|
||||
use tokio::task::{spawn_local, LocalSet};
|
||||
|
||||
mod glue_deno;
|
||||
|
||||
#[mize_part("js")]
|
||||
#[derive(Default)]
|
||||
pub struct JsPart {
|
||||
mize: Mize,
|
||||
sender: Option<flume::Sender<JsRuntimeThreadMessage>>,
|
||||
}
|
||||
|
||||
pub type BoxFuture<'a> = Pin<Box<dyn Future<Output = MizeResult<()>> + 'a>>;
|
||||
pub type BoxClosure = Box<dyn for<'a> FnOnce(&'a mut JsRuntime) -> BoxFuture<'a> + Send + 'static>;
|
||||
|
||||
impl MizePart for JsPart {
|
||||
fn run(&mut self, mize: &mut Mize) -> MizeResult<()> {
|
||||
println!("js part run");
|
||||
self.sender
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.send(JsRuntimeThreadMessage::DoRunPhase)
|
||||
.unwrap();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn js(mize: &mut Mize) -> MizeResult<()> {
|
||||
let (sender, receiver) = flume::unbounded::<JsRuntimeThreadMessage>();
|
||||
let mize_clone = mize.clone();
|
||||
|
||||
// the thread which will run any js
|
||||
mize.spawn_and_wait("js_runtime_thread", || {
|
||||
js_runtime_thread(mize_clone, receiver)
|
||||
})?;
|
||||
|
||||
mize.add_part(Box::new(JsPart {
|
||||
mize: mize.clone(),
|
||||
sender: Some(sender),
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn part_from_file(
|
||||
mize: &mut Mize,
|
||||
name: &'static str,
|
||||
code: FastStaticString,
|
||||
) -> MizeResult<()> {
|
||||
let mut js = mize.get_part_native::<JsPart>("js")?;
|
||||
js.execute_init_js(code)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl JsPart {
|
||||
pub fn execute_init_js(&mut self, code: FastStaticString) -> MizeResult<()> {
|
||||
self.sender
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.send(JsRuntimeThreadMessage::RunInitJs(code))
|
||||
.unwrap();
|
||||
Ok(())
|
||||
}
|
||||
pub fn eval(&mut self, code: String) -> MizeResult<()> {
|
||||
self.sender
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.send(JsRuntimeThreadMessage::RunJs(code))
|
||||
.unwrap();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn js_runtime_thread(
|
||||
mize: Mize,
|
||||
receiver: flume::Receiver<JsRuntimeThreadMessage>,
|
||||
) -> MizeResult<()> {
|
||||
let mut js_runtime = JsRuntime::new(RuntimeOptions {
|
||||
//module_loader: Some(Rc::new(FsModuleLoader)),
|
||||
//extensions: vec![glue_deno::my_extension::init(mize.clone())],
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
js_runtime
|
||||
.execute_script("[stub]", ascii_str_include!("../deno_dist/glue_deno.js"))
|
||||
.unwrap();
|
||||
|
||||
loop {
|
||||
println!("js thread waiting for smth");
|
||||
let msg = receiver.recv().unwrap();
|
||||
println!("js thread got smth");
|
||||
match msg {
|
||||
JsRuntimeThreadMessage::RunInitJs(js_code) => {
|
||||
if let Err(err) = js_runtime.execute_script("[init]", js_code) {
|
||||
println!("err: {}", err);
|
||||
}
|
||||
println!("done running js");
|
||||
}
|
||||
JsRuntimeThreadMessage::RunJs(js_code) => {
|
||||
if let Err(err) = js_runtime.execute_script("[idk]", js_code) {
|
||||
println!("err: {}", err);
|
||||
}
|
||||
println!("done running js");
|
||||
}
|
||||
JsRuntimeThreadMessage::DoRunPhase => {
|
||||
if let Err(err) = js_runtime.execute_script("[runPhase]", "mize.runPhase()") {
|
||||
println!("err: {}", err);
|
||||
}
|
||||
println!("done with runPhase");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum JsRuntimeThreadMessage {
|
||||
//Closure(Box<dyn FnOnce(&mut JsRuntime) -> MizeResult<()> + Send>),
|
||||
//AsyncClosure(BoxClosure),
|
||||
RunInitJs(FastStaticString),
|
||||
RunJs(String),
|
||||
DoRunPhase,
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
export class Mize {
|
||||
async get_config(key: string): Promise<any> {
|
||||
return "hiiiiiii";
|
||||
}
|
||||
async add_opts(opts: any): Promise<void> {}
|
||||
async add_part(part: any): Promise<void> {}
|
||||
async report_err(err: MizeError) {}
|
||||
runPhase() {
|
||||
Deno.core.print("runPhase in js \n");
|
||||
}
|
||||
}
|
||||
|
||||
type MizeError = string;
|
||||
|
||||
export class Cli {
|
||||
constructor(mize: Mize) {}
|
||||
async sub_command(name: string, cmd: any): Promise<void> {}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
#[cfg(feature = "target-os")]
|
||||
mod cli;
|
||||
#[cfg(feature = "target-os")]
|
||||
pub use cli::*;
|
||||
|
||||
#[cfg(feature = "target-os")]
|
||||
pub mod habitica;
|
||||
#[cfg(feature = "target-os")]
|
||||
pub use habitica::*;
|
||||
|
||||
#[cfg(feature = "target-os")]
|
||||
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")]
|
||||
//pub use js::*;
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"name": "@ppc/marts",
|
||||
"version": "1.0.0",
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@flowershow/remark-wiki-link": "^3.4.0",
|
||||
"builtin-modules": "^5.0.0",
|
||||
"esbuild": "^0.27.3",
|
||||
"mdast": "^3.0.0",
|
||||
"obsidian": "^1.12.3",
|
||||
"remark-frontmatter": "^5.0.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"remark-parse": "^11.0.0",
|
||||
"remark-stringify": "^11.0.0",
|
||||
"typescript": "^5.9.3",
|
||||
"unified": "^11.0.5",
|
||||
"unist-util-visit": "^5.1.0"
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
use mize::{mize_part, Mize, MizePart, MizePartCreate, MizeResult};
|
||||
|
||||
use crate::auth::client::ClientAuth;
|
||||
use generated::spacetime::DbConnection;
|
||||
|
||||
#[mize_part]
|
||||
#[derive(Default)]
|
||||
pub struct SpacetimePart {
|
||||
mize: Mize,
|
||||
con: Option<DbConnection>,
|
||||
}
|
||||
|
||||
impl MizePartCreate for SpacetimePart {}
|
||||
impl MizePart for SpacetimePart {
|
||||
fn name(&self) -> &'static str {
|
||||
"spacetime"
|
||||
}
|
||||
}
|
||||
|
||||
impl SpacetimePart {
|
||||
pub fn con(&mut self) -> &mut DbConnection {
|
||||
self.con.as_mut().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spacetime(mize: &mut Mize) -> MizeResult<()> {
|
||||
let auth = mize.get_part_native::<ClientAuth>("client_auth")?;
|
||||
let db_url = mize.get_config("spacetime.url")?.value_string()?;
|
||||
|
||||
let con = DbConnection::builder()
|
||||
.with_token(Some(auth.id_token()?))
|
||||
.with_database_name("ppc")
|
||||
.with_uri(db_url)
|
||||
//.on_connect(callback)
|
||||
//.on_disconnect(callback)
|
||||
//.on_connect_error(callback)
|
||||
//.with_compression(...)
|
||||
.build()?;
|
||||
|
||||
con.run_threaded();
|
||||
|
||||
mize.register_part(Box::new(SpacetimePart {
|
||||
mize: mize.clone(),
|
||||
con: Some(con),
|
||||
}))
|
||||
}
|
||||
246
packages/marts/src/matrix/mod.rs
Normal file
246
packages/marts/src/matrix/mod.rs
Normal file
@@ -0,0 +1,246 @@
|
||||
use mize::{Mize, MizeResult, MizePart, MizePartCreate, mize_part};
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::spawn_local;
|
||||
use js_sys::Function;
|
||||
use web_sys::HtmlElement;
|
||||
|
||||
use matrix_sdk::{
|
||||
Client, ClientConfig, SyncState,
|
||||
ruma::{
|
||||
user_id::UserId,
|
||||
events::room::message::RoomMessageEventContent,
|
||||
},
|
||||
};
|
||||
|
||||
mod ui;
|
||||
use ui::mount_chat_app;
|
||||
|
||||
const ROOM_ID: &str = "!XwqdXGPlmaLatdGUiN:ppc.social";
|
||||
const ACCOUNT_NAME: &str = "default";
|
||||
const INITIAL_LOAD_LIMIT: usize = 50;
|
||||
|
||||
/// Matrix part that manages Matrix client and UI
|
||||
#[mize_part("matrix")]
|
||||
#[derive(Clone)]
|
||||
pub struct MatrixPart {
|
||||
mize: Mize,
|
||||
pub client: Option<Client>,
|
||||
pub timeline: Vec<matrix_sdk::SyncRoomEvent>,
|
||||
pub message_draft: String,
|
||||
pub edit_event_id: Option<String>,
|
||||
}
|
||||
|
||||
impl MizePart for MatrixPart {}
|
||||
impl MizePartCreate for MatrixPart {}
|
||||
|
||||
impl MatrixPart {
|
||||
/// Create a new MatrixPart
|
||||
pub fn new(mize: Mize) -> Self {
|
||||
Self {
|
||||
mize,
|
||||
client: None,
|
||||
timeline: Vec::new(),
|
||||
message_draft: String::new(),
|
||||
edit_event_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Initialize the Matrix client from config
|
||||
pub async fn init_client(&mut self) -> Result<(), String> {
|
||||
let homeserver = self.mize
|
||||
.get_config(&format!("matrix.accounts.{}.homeserver", ACCOUNT_NAME))
|
||||
.map_err(|e| format!("Failed to get homeserver config: {:?}", e))?;
|
||||
|
||||
let access_token = self.mize
|
||||
.get_config(&format!("matrix.accounts.{}.access_token", ACCOUNT_NAME))
|
||||
.map_err(|e| format!("Failed to get access_token config: {:?}", e))?;
|
||||
|
||||
let user_id_str = self.mize
|
||||
.get_config(&format!("matrix.accounts.{}.user_id", ACCOUNT_NAME))
|
||||
.map_err(|e| format!("Failed to get user_id config: {:?}", e))?;
|
||||
|
||||
let device_id = self.mize
|
||||
.get_config(&format!("matrix.accounts.{}.device_id", ACCOUNT_NAME))
|
||||
.map_err(|e| format!("Failed to get device_id config: {:?}", e))?;
|
||||
|
||||
let user_id = UserId::parse(&user_id_str)
|
||||
.map_err(|e| format!("Invalid user_id: {:?}", e))?;
|
||||
|
||||
let config = ClientConfig::new()
|
||||
.homeserver_url(homeserver)
|
||||
.device_id(device_id);
|
||||
|
||||
let client = Client::new_with_config(user_id, Some(access_token), config)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to create client: {:?}", e))?;
|
||||
|
||||
self.client = Some(client.clone());
|
||||
|
||||
// Start sync in background
|
||||
self.start_sync(client).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start sync and set up event listeners
|
||||
async fn start_sync(&mut self, client: Client) -> Result<(), String> {
|
||||
let room_id = ROOM_ID.to_string();
|
||||
let mize = self.mize.clone();
|
||||
|
||||
// Start sync
|
||||
let sync_token = client.sync_token().await;
|
||||
let mut sync_state = SyncState::new(sync_token);
|
||||
|
||||
let client_clone = client.clone();
|
||||
|
||||
spawn_local(async move {
|
||||
loop {
|
||||
match client_clone.sync(&mut sync_state).await {
|
||||
Ok(response) => {
|
||||
// Process sync response - update MatrixPart via mize
|
||||
if let Some(rooms) = response.rooms {
|
||||
if let Some(join) = rooms.join {
|
||||
if let Some(room_events) = join.get(&room_id) {
|
||||
// Get MatrixPart and update timeline
|
||||
if let Ok(mut matrix_part) = mize.get_part_native::<MatrixPart>("matrix") {
|
||||
for event in &room_events.timeline.events {
|
||||
if event.room_id() == room_id {
|
||||
matrix_part.timeline.push(event.clone());
|
||||
// Keep only last INITIAL_LOAD_LIMIT events
|
||||
if matrix_part.timeline.len() > INITIAL_LOAD_LIMIT {
|
||||
matrix_part.timeline.remove(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if we should stop syncing
|
||||
if sync_state.should_stop() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
console_log!("Sync error: {:?}", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Send a message to the room
|
||||
pub async fn send_message(&mut self) -> MizeResult<()> {
|
||||
let client = self.client.as_ref()
|
||||
.ok_or_else(|| mize::error::Error::new("Client not initialized"))?;
|
||||
|
||||
if self.message_draft.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let content = RoomMessageEventContent::text_plain(&self.message_draft);
|
||||
|
||||
if let Some(_event_id) = &self.edit_event_id {
|
||||
// Editing existing message - placeholder for now
|
||||
console_log!("Editing message (not yet implemented)");
|
||||
}
|
||||
|
||||
// Send message
|
||||
client.send_room_message(ROOM_ID, content).await?;
|
||||
|
||||
// Clear draft after sending
|
||||
self.message_draft.clear();
|
||||
self.edit_event_id = None;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Entry point for the Matrix part
|
||||
pub fn part_matrix(mize: &mut Mize) -> MizeResult<()> {
|
||||
#[cfg(feature = "target_obsidian")] {
|
||||
use crate::ObsidianPart;
|
||||
|
||||
// Get the Obsidian part
|
||||
let obsidian = mize.get_part_native::<ObsidianPart>("obsidian")?;
|
||||
|
||||
// Create and register MatrixPart
|
||||
let matrix_part = MatrixPart::new(mize.clone());
|
||||
mize.register_part(Box::new(matrix_part));
|
||||
|
||||
// Get the registered MatrixPart to initialize it
|
||||
let mize_clone = mize.clone();
|
||||
spawn_local(async move {
|
||||
if let Ok(mut matrix_part) = mize_clone.get_part_native::<MatrixPart>("matrix") {
|
||||
if let Err(e) = matrix_part.init_client().await {
|
||||
console_log!("Failed to initialize Matrix client: {}", e);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Create a JS function that will be called when the view is opened
|
||||
let mize_for_view = mize.clone();
|
||||
let view_creator = Closure::<dyn Fn(JsValue)>::wrap(Box::new(move |leaf: JsValue| {
|
||||
if let Some(element) = extract_dom_element(leaf) {
|
||||
// Get MatrixPart state for the UI
|
||||
if let Ok(matrix_part) = mize_for_view.get_part_native::<MatrixPart>("matrix") {
|
||||
let timeline = matrix_part.timeline.clone();
|
||||
let message_draft = matrix_part.message_draft.clone();
|
||||
let edit_event_id = matrix_part.edit_event_id.clone();
|
||||
|
||||
mount_chat_app(element, timeline, message_draft, edit_event_id, mize_for_view.clone());
|
||||
}
|
||||
} else {
|
||||
console_log!("Failed to extract DOM element from leaf");
|
||||
}
|
||||
}));
|
||||
|
||||
// Convert closure to JS Function
|
||||
let view_creator_fn: &Function = view_creator.as_ref().unchecked_ref();
|
||||
|
||||
// Register the view with Obsidian
|
||||
ObsidianPart::register_view(&obsidian.plugin(), "matrix-chat-view", view_creator_fn)?;
|
||||
|
||||
// Prevent the closure from being dropped
|
||||
view_creator.forget();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Extract DOM element from Obsidian leaf JSValue
|
||||
fn extract_dom_element(leaf: JsValue) -> Option<HtmlElement> {
|
||||
use wasm_bindgen::JsCast;
|
||||
use js_sys::Reflect;
|
||||
|
||||
// Try to get the containerEl from the leaf
|
||||
let container_value = Reflect::get(&leaf, &"containerEl".into()).ok()?;
|
||||
let container = container_value.dyn_into::<HtmlElement>().ok()?;
|
||||
|
||||
// Create a div to mount into
|
||||
let doc = web_sys::window()?.document()?;
|
||||
let mount_point = doc.create_element("div").ok()?;
|
||||
mount_point.set_attribute("style", "height: 100%; width: 100%;").ok()?;
|
||||
|
||||
container.append_child(&mount_point).ok()?;
|
||||
mount_point.dyn_into::<HtmlElement>().ok()
|
||||
}
|
||||
|
||||
// Console log macros
|
||||
#[macro_export]
|
||||
macro_rules! console_log {
|
||||
($($t:tt)*) => {
|
||||
web_sys::console::log_1(&format!($($t)*).into());
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! console_error {
|
||||
($($t:tt)*) => {
|
||||
web_sys::console::error_1(&format!($($t)*).into());
|
||||
};
|
||||
}
|
||||
269
packages/marts/src/matrix/ui.rs
Normal file
269
packages/marts/src/matrix/ui.rs
Normal file
@@ -0,0 +1,269 @@
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_web::events::FormEvent;
|
||||
use mize::Mize;
|
||||
use matrix_sdk::SyncRoomEvent;
|
||||
|
||||
const ROOM_ID: &str = "!XwqdXGPlmaLatdGUiN:ppc.social";
|
||||
|
||||
/// Props for the chat component
|
||||
#[derive(Props, Clone)]
|
||||
pub struct ChatProps {
|
||||
pub mize: Mize,
|
||||
pub initial_timeline: Vec<SyncRoomEvent>,
|
||||
pub initial_draft: String,
|
||||
pub initial_edit_id: Option<String>,
|
||||
}
|
||||
|
||||
/// Message component - renders a single message
|
||||
#[component]
|
||||
pub fn Message(cx: Scope, event: SyncRoomEvent) -> Element {
|
||||
let sender = event.sender().to_string();
|
||||
let timestamp = event.origin_server_ts();
|
||||
|
||||
// Extract display name from MXID (basic version)
|
||||
let display_name = if let Some(at_pos) = sender.find('@') {
|
||||
if let Some(colon_pos) = sender.rfind(':') {
|
||||
&sender[at_pos + 1..colon_pos]
|
||||
} else {
|
||||
&sender[at_pos + 1..]
|
||||
}
|
||||
} else {
|
||||
&sender
|
||||
};
|
||||
|
||||
// Format timestamp
|
||||
let time_str = {
|
||||
let dt = js_sys::Date::new(&(timestamp as f64));
|
||||
dt.to_locale_string()
|
||||
};
|
||||
|
||||
// Extract message content
|
||||
let content = event
|
||||
.as_original()
|
||||
.and_then(|e| e.content().deserialize().ok())
|
||||
.and_then(|c: matrix_sdk::ruma::events::room::message::RoomMessageEventContent| {
|
||||
c.body().map(|s| s.to_string())
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
// Check if this is an edit
|
||||
let is_edit = event
|
||||
.as_original()
|
||||
.map(|e| {
|
||||
e.content()
|
||||
.get("m.relates_to")
|
||||
.and_then(|v| v.as_object())
|
||||
.and_then(|o| o.get("rel_type"))
|
||||
.and_then(|v| v.as_str())
|
||||
== Some("m.replace")
|
||||
})
|
||||
.unwrap_or(false);
|
||||
|
||||
cx.render(rsx! {
|
||||
div {
|
||||
class: "matrix-chat-event",
|
||||
style: "margin: 14px 16px; padding-bottom: 10px; border-bottom: 1px solid var(--background-modifier-border);",
|
||||
|
||||
div {
|
||||
class: "matrix-chat-msghead",
|
||||
style: "font-size: 1em; font-weight: 500; color: var(--interactive-accent); display: flex; align-items: center; gap: 10px;",
|
||||
|
||||
span { display_name }
|
||||
span {
|
||||
style: "font-size: 0.85em; color: var(--text-muted); margin-left: auto;",
|
||||
{time_str.clone()}
|
||||
if is_edit { " · edited" }
|
||||
}
|
||||
}
|
||||
|
||||
div {
|
||||
class: "matrix-chat-msgbody",
|
||||
style: "margin: 6px 0 0 0; font-size: 1em;",
|
||||
{content}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Editor component - message input area
|
||||
#[component]
|
||||
pub fn Editor(cx: Scope, mize: Mize, draft: UseSignal<String>, edit_id: UseSignal<Option<String>>) -> Element {
|
||||
let on_input = move |evt: FormEvent| {
|
||||
draft.set(evt.value.clone());
|
||||
};
|
||||
|
||||
let on_send = move |_| {
|
||||
let mize_clone = mize.clone();
|
||||
let draft_val = draft.read().clone();
|
||||
let edit_id_val = edit_id.read().clone();
|
||||
|
||||
cx.spawn(async move {
|
||||
if let Ok(mut matrix_part) = mize_clone.get_part_native::<crate::matrix::MatrixPart>("matrix") {
|
||||
matrix_part.message_draft = draft_val;
|
||||
matrix_part.edit_event_id = edit_id_val;
|
||||
if let Err(e) = matrix_part.send_message().await {
|
||||
console_log!("Failed to send message: {:?}", e);
|
||||
}
|
||||
// Clear local draft
|
||||
draft.set(String::new());
|
||||
edit_id.set(None);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
let on_keydown = move |evt: dioxus_web::events::KeyboardEvent| {
|
||||
if (evt.ctrl_key() || evt.meta_key()) && evt.key() == "Enter" {
|
||||
on_send(evt);
|
||||
}
|
||||
};
|
||||
|
||||
let on_cancel = move |_| {
|
||||
draft.set(String::new());
|
||||
edit_id.set(None);
|
||||
};
|
||||
|
||||
cx.render(rsx! {
|
||||
div {
|
||||
class: "matrix-chat-editor",
|
||||
style: "border-top: 1px solid var(--background-modifier-border); background: var(--background-primary); padding: 8px 12px;",
|
||||
|
||||
div {
|
||||
class: "matrix-chat-editor-inner",
|
||||
style: "border: 1px solid var(--background-modifier-border); border-radius: 6px; overflow: hidden; background: var(--background-secondary);",
|
||||
|
||||
textarea {
|
||||
r#type: "text",
|
||||
rows: "3",
|
||||
style: "width: 99%; min-height: 40px; resize: vertical; background: transparent; border: none; outline: none; padding: 8px; font-family: inherit; font-size: inherit; color: var(--text-normal);",
|
||||
value: "{draft}",
|
||||
oninput: on_input,
|
||||
onkeydown: on_keydown,
|
||||
}
|
||||
}
|
||||
|
||||
button {
|
||||
r#type: "button",
|
||||
style: "margin-top: 3px; float: right; padding: 6px 14px; font-size: 0.97em; border-radius: 5px; border: none; background: var(--interactive-accent); color: white; cursor: pointer;",
|
||||
onclick: on_send,
|
||||
if edit_id.read().is_some() { "Save" } else { "Send" }
|
||||
}
|
||||
|
||||
if edit_id.read().is_some() {
|
||||
button {
|
||||
r#type: "button",
|
||||
style: "margin-right: 12px; padding: 6px 12px; font-size: 0.93em; border-radius: 5px; border: none; color: var(--text-normal); background: var(--background-secondary); cursor: pointer;",
|
||||
onclick: on_cancel,
|
||||
"Cancel"
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Timeline component - list of messages
|
||||
#[component]
|
||||
pub fn Timeline(cx: Scope, mize: Mize, timeline: UseSignal<Vec<SyncRoomEvent>>) -> Element {
|
||||
// Periodically refresh timeline from MatrixPart
|
||||
cx.use_effect((), move |_| {
|
||||
let mize_clone = mize.clone();
|
||||
let timeline_clone = timeline.clone();
|
||||
|
||||
// Set up interval to poll for updates
|
||||
let interval = js_sys::set_interval(
|
||||
&Closure::<dyn FnMut()>::wrap(Box::new(move || {
|
||||
if let Ok(matrix_part) = mize_clone.get_part_native::<crate::matrix::MatrixPart>("matrix") {
|
||||
*timeline_clone.write() = matrix_part.timeline.clone();
|
||||
}
|
||||
})),
|
||||
1000, // 1 second
|
||||
);
|
||||
|
||||
// Cleanup on unmount
|
||||
move || {
|
||||
js_sys::clear_interval(interval);
|
||||
}
|
||||
});
|
||||
|
||||
cx.render(rsx! {
|
||||
div {
|
||||
class: "matrix-chat-scroll",
|
||||
style: "flex-grow: 1; overflow-y: auto; padding: 8px 0; background: var(--background-secondary);",
|
||||
|
||||
// Room name header
|
||||
div {
|
||||
class: "matrix-chat-roomname",
|
||||
style: "font-weight: 600; text-align: center; font-size: 1.1em; margin: 2px 0 12px 0; border-bottom: 1px solid var(--background-modifier-border); color: var(--text-accent); background: var(--background-primary);",
|
||||
"Matrix Chat - {ROOM_ID}"
|
||||
}
|
||||
|
||||
// Messages
|
||||
for event in timeline.read().iter() {
|
||||
rsx! { Message { event: event.clone() } }
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Root chat component
|
||||
#[component]
|
||||
pub fn Chat(cx: Scope, props: ChatProps) -> Element {
|
||||
let timeline = use_signal(&cx, || props.initial_timeline);
|
||||
let draft = use_signal(&cx, || props.initial_draft);
|
||||
let edit_id = use_signal(&cx, || props.initial_edit_id);
|
||||
|
||||
cx.render(rsx! {
|
||||
div {
|
||||
class: "matrix-chat-root",
|
||||
style: "height: 100%; display: flex; flex-direction: column; background: var(--background-primary); color: var(--text-normal);",
|
||||
|
||||
// Title
|
||||
div {
|
||||
class: "matrix-chat-title",
|
||||
style: "padding: 12px; font-weight: bold; font-size: 1.2em; text-align: center; border-bottom: 1px solid var(--background-modifier-border);",
|
||||
"Matrix Chat"
|
||||
}
|
||||
|
||||
// Info
|
||||
div {
|
||||
class: "matrix-chat-info",
|
||||
style: "font-size: 0.85em; color: var(--text-muted); text-align: center; margin-bottom: 5px;",
|
||||
"Room: {ROOM_ID}"
|
||||
}
|
||||
|
||||
// Timeline
|
||||
Timeline { mize: props.mize.clone(), timeline }
|
||||
|
||||
// Editor
|
||||
Editor { mize: props.mize.clone(), draft, edit_id }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Mount the Dioxus app into a DOM element
|
||||
pub fn mount_chat_app(
|
||||
element: web_sys::HtmlElement,
|
||||
initial_timeline: Vec<SyncRoomEvent>,
|
||||
initial_draft: String,
|
||||
initial_edit_id: Option<String>,
|
||||
mize: Mize,
|
||||
) {
|
||||
dioxus_web::launch(
|
||||
dioxus::prelude::App::new(move || rsx! {
|
||||
Chat {
|
||||
mize: mize.clone(),
|
||||
initial_timeline: initial_timeline.clone(),
|
||||
initial_draft: initial_draft.clone(),
|
||||
initial_edit_id: initial_edit_id.clone(),
|
||||
}
|
||||
}),
|
||||
element,
|
||||
);
|
||||
}
|
||||
|
||||
// Console log macro
|
||||
#[macro_export]
|
||||
macro_rules! console_log {
|
||||
($($t:tt)*) => {
|
||||
web_sys::console::log_1(&format!($($t)*).into());
|
||||
};
|
||||
}
|
||||
@@ -1,538 +0,0 @@
|
||||
import remarkParse from "remark-parse";
|
||||
import remarkStringify from "remark-stringify";
|
||||
import { unified } from "unified";
|
||||
import { visit } from "unist-util-visit";
|
||||
import { Root, Content, Heading, List, ListItem, Text } from "mdast";
|
||||
import remarkFrontmatter from "remark-frontmatter";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import wikiLinkPlugin from "@flowershow/remark-wiki-link";
|
||||
import { TFile } from "obsidian";
|
||||
|
||||
const OTASK_PROP_NAMES = ["short", "outcome", "priority"];
|
||||
const ACTION_PROP_NAMES = [];
|
||||
|
||||
const REMARK = unified()
|
||||
.use(remarkParse)
|
||||
.use(remarkFrontmatter)
|
||||
.use(remarkGfm)
|
||||
.use(remarkStringify, { bullet: "-" });
|
||||
|
||||
export function task_obsidian_otask_parse(mize: any) {
|
||||
const obsidian_plugin = mize.get_part_native("obsidian");
|
||||
|
||||
obsidian_plugin.addCommand({
|
||||
id: "full-parse",
|
||||
name: "Parse all otask files into the db",
|
||||
callback: async () => {
|
||||
await full_parse();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function full_parse() {
|
||||
console.log("full parse.......................... yay");
|
||||
let otasks = [];
|
||||
OTASK_PARSE_QUEUE = [];
|
||||
OTASK_LIST = [];
|
||||
|
||||
const root_file = app.vault.getAbstractFileByPath("task/my-projects.md");
|
||||
|
||||
const content = await app.vault.read(root_file);
|
||||
const list = await getListUnderHeading(content, "root");
|
||||
|
||||
for (const entry of list) {
|
||||
queue_otasks_from_list_item(entry, []);
|
||||
}
|
||||
|
||||
// go through the queue of otaskParseTasks
|
||||
// using a queue instead of recursive calls, to make it more debuggable...
|
||||
do {
|
||||
const task = OTASK_PARSE_QUEUE.shift();
|
||||
dbg("task", task);
|
||||
if (task.file) {
|
||||
const otask = await otasks_from_file(
|
||||
task.file,
|
||||
task.otask_path,
|
||||
task.priority,
|
||||
);
|
||||
dbg("otask", otask);
|
||||
if (otask) {
|
||||
OTASK_LIST.push(otask);
|
||||
}
|
||||
} else {
|
||||
const otask = await otasks_from_list_item(
|
||||
task.listItem,
|
||||
task.otask_path,
|
||||
task.priority,
|
||||
);
|
||||
dbg("otask", otask);
|
||||
if (otask) {
|
||||
OTASK_LIST.push(otask);
|
||||
}
|
||||
}
|
||||
} while (OTASK_PARSE_QUEUE.length > 0);
|
||||
|
||||
console.log("otasks::", OTASK_LIST);
|
||||
|
||||
render_sub0_file(OTASK_LIST);
|
||||
}
|
||||
|
||||
let OTASK_PARSE_QUEUE: any = [];
|
||||
let OTASK_LIST = [];
|
||||
let DBG = false;
|
||||
|
||||
function dbg() {
|
||||
if (DBG) {
|
||||
console.log(arguments);
|
||||
}
|
||||
}
|
||||
|
||||
function queue_otasks_from_list_item(listItem, otask_path, priority = 0) {
|
||||
OTASK_PARSE_QUEUE.push({
|
||||
listItem,
|
||||
otask_path,
|
||||
priority,
|
||||
});
|
||||
}
|
||||
|
||||
function queue_otasks_from_file(file, otask_path, priority = 0) {
|
||||
OTASK_PARSE_QUEUE.push({
|
||||
file,
|
||||
otask_path,
|
||||
priority,
|
||||
});
|
||||
}
|
||||
|
||||
// parsing helper functions
|
||||
|
||||
async function render_sub0_file(otasks) {
|
||||
const sub0_file = app.vault.getAbstractFileByPath("private/sub0-tasks.md");
|
||||
if (!(sub0_file instanceof TFile)) {
|
||||
console.error(
|
||||
"SystemC2: sub0_file not found:",
|
||||
"private/sub0-tasks.md",
|
||||
sub0_file,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
//render sub0
|
||||
const sub0_otasks = otasks.filter(
|
||||
(otask) => otask.priority == 0 && !otask.is_file,
|
||||
);
|
||||
console.log("sub0 otasks...", sub0_otasks);
|
||||
|
||||
let rendered_otasks_string = "";
|
||||
|
||||
for (const otask of sub0_otasks) {
|
||||
const path_part = otask.path.length > 0 ? otask.path.join(": ") + ": " : "";
|
||||
|
||||
let content_part = otask.content ? otask.content + "\n" : "";
|
||||
content_part = content_part
|
||||
.split("\n")
|
||||
.map((line) => "\t" + line)
|
||||
.join("\n"); // add a \t in front of every otask.content line
|
||||
|
||||
rendered_otasks_string += `- ${path_part}${otask.longName}\n${content_part}\n`;
|
||||
}
|
||||
//console.log("newContent...", rendered_otasks_string)
|
||||
|
||||
await replaceHeading(sub0_file, "sub0", rendered_otasks_string);
|
||||
|
||||
//render sub-1
|
||||
}
|
||||
|
||||
async function replaceHeading(
|
||||
file: TFile,
|
||||
heading: string,
|
||||
newContent: string,
|
||||
) {
|
||||
const data = await this.app.vault.read(file);
|
||||
|
||||
// Parse the Markdown into an AST
|
||||
const tree = REMARK.parse(data) as Root;
|
||||
|
||||
// Split new content into AST nodes
|
||||
const newContentAst = REMARK.parse(newContent) as Root;
|
||||
|
||||
const children = tree.children;
|
||||
const newChildren: Content[] = [];
|
||||
let insideTarget = false;
|
||||
let targetLevel = 0;
|
||||
|
||||
for (let i = 0; i < children.length; i++) {
|
||||
const node = children[i];
|
||||
|
||||
if (node.type === "heading") {
|
||||
const headingNode = node as Heading;
|
||||
const text = headingNode.children
|
||||
.filter((c) => c.type === "text")
|
||||
.map((c: any) => c.value)
|
||||
.join("");
|
||||
|
||||
// If we encounter our target heading
|
||||
if (text.trim() === heading) {
|
||||
insideTarget = true;
|
||||
targetLevel = headingNode.depth;
|
||||
newChildren.push(node); // Keep the heading itself
|
||||
// Insert new content right after
|
||||
newChildren.push(...newContentAst.children);
|
||||
continue;
|
||||
}
|
||||
|
||||
// If we’re currently inside target section and see a heading of same or higher level
|
||||
if (insideTarget && headingNode.depth <= targetLevel) {
|
||||
insideTarget = false;
|
||||
}
|
||||
}
|
||||
|
||||
// If we’re not inside the target section, keep the node
|
||||
if (!insideTarget) {
|
||||
newChildren.push(node);
|
||||
}
|
||||
}
|
||||
|
||||
const newTree: Root = { ...tree, children: newChildren };
|
||||
|
||||
// Convert AST back to Markdown
|
||||
const newMarkdown = await REMARK.stringify(newTree);
|
||||
|
||||
await this.app.vault.modify(file, newMarkdown);
|
||||
}
|
||||
|
||||
async function otasks_from_list_item(listItem, otask_path, priority = 0) {
|
||||
try {
|
||||
// the main otask this listItem is about
|
||||
let otask = {
|
||||
description: [],
|
||||
actions: [],
|
||||
path: [],
|
||||
priority,
|
||||
};
|
||||
dbg("SystemC2: otasks_from_list_item", listItem, otask_path);
|
||||
|
||||
if (!listItem.children[0].type === "paragraph") {
|
||||
dbg(
|
||||
"listItem[0] of a otask item is not a paragraph... the otask:",
|
||||
listItem,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
let longName = nodeToString(listItem.children[0]);
|
||||
|
||||
dbg("longName:", longName);
|
||||
|
||||
// check for [[anotherotask]], call otasks_from_file, return those
|
||||
const match = longName.match(/\[\[([^\]]+)\]\]/);
|
||||
if (match) {
|
||||
const file = app.metadataCache.getFirstLinkpathDest(match[1], "");
|
||||
if (file) {
|
||||
const metadata = app.metadataCache.getFileCache(file);
|
||||
|
||||
if (metadata?.frontmatter?.tags?.includes("t/otask")) {
|
||||
queue_otasks_from_file(file, otask_path);
|
||||
return null;
|
||||
} else {
|
||||
dbg(
|
||||
"SystemC2: listItem with Link to '",
|
||||
match[1],
|
||||
"', which is not an otask",
|
||||
longName,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//check for [x] and remove from name
|
||||
if (longName.startsWith("[ ") || longName.startsWith("[x")) {
|
||||
longName = longName.slice(4);
|
||||
}
|
||||
|
||||
//check for "ot:" and remove from name
|
||||
if (longName.startsWith("ot:")) {
|
||||
longName = longName.slice(4);
|
||||
}
|
||||
|
||||
otask.longName = longName;
|
||||
otask.short = longName;
|
||||
otask.path = otask_path;
|
||||
let new_otask_path = [...otask_path, otask.short];
|
||||
|
||||
// go through sub list items
|
||||
// - if it's a prop for the otask... handle that
|
||||
// - if it's an "ac:" handle that
|
||||
// - if it's "ot: " handle as another otask -> recursive call
|
||||
// - if it's "[ ]" handle as another otask -> recursive call
|
||||
// - if it's a link to a otask file... handle as another otask -> call otasks_from_file()
|
||||
// - else add it as description item list to otask
|
||||
if (!listItem.children || listItem.children.length < 2) {
|
||||
return otask;
|
||||
}
|
||||
|
||||
// add content as text to otask
|
||||
if (otask.longName == "hosting updates") {
|
||||
console.log("listItem... ", listItem.children[1]);
|
||||
let hii = REMARK.stringify(listItem.children[1]);
|
||||
console.log("text...", hii);
|
||||
}
|
||||
let content_text = REMARK.stringify(listItem.children[1]);
|
||||
otask.content = content_text;
|
||||
|
||||
for (const subListItem of listItem.children[1].children) {
|
||||
let text = nodeToString(subListItem.children[0]);
|
||||
|
||||
// check prop
|
||||
if (check_otask_prop_from_list_item(subListItem, otask)) {
|
||||
new_otask_path = [...otask_path, otask.short]; // have to redo it here, in case short changed from aprop
|
||||
continue; // don't do any other processing on this sub-listItem
|
||||
}
|
||||
|
||||
// remove "[ ]"
|
||||
if (text.startsWith("[ ") || text.startsWith("[x")) {
|
||||
text = text.slice(4);
|
||||
}
|
||||
|
||||
// check ac
|
||||
if (text.startsWith("ac:")) {
|
||||
otask.actions = [
|
||||
...otask.actions,
|
||||
action_from_list_item(subListItem, new_otask_path, otask.priority),
|
||||
];
|
||||
|
||||
continue; // don't do any other processing on this sub-listItem
|
||||
}
|
||||
|
||||
// check ot
|
||||
if (text.startsWith("ot:")) {
|
||||
queue_otasks_from_list_item(
|
||||
subListItem,
|
||||
new_otask_path,
|
||||
otask.priority,
|
||||
);
|
||||
|
||||
continue; // don't do any other processing on this sub-listItem
|
||||
}
|
||||
|
||||
// check [ ]
|
||||
if (text.startsWith("[ ] ") || text.startsWith("[x] ")) {
|
||||
queue_otasks_from_list_item(
|
||||
subListItem,
|
||||
new_otask_path,
|
||||
otask.priority,
|
||||
);
|
||||
|
||||
continue; // don't do any other processing on this sub-listItem
|
||||
}
|
||||
|
||||
// check link to otask file
|
||||
const match = text.match(/\[\[([^\]]+)\]\]/);
|
||||
if (match) {
|
||||
const file = app.metadataCache.getFirstLinkpathDest(match[1], "");
|
||||
if (file) {
|
||||
const metadata = app.metadataCache.getFileCache(file);
|
||||
|
||||
if (metadata?.frontmatter?.tags?.includes("t/otask")) {
|
||||
queue_otasks_from_file(file, new_otask_path, otask.priority);
|
||||
continue;
|
||||
} else {
|
||||
dbg(
|
||||
"SystemC2: listItem with Link to '",
|
||||
match[1],
|
||||
"', which is not an otask",
|
||||
longName,
|
||||
);
|
||||
}
|
||||
|
||||
continue; // don't do any other processing on this sub-listItem
|
||||
}
|
||||
}
|
||||
|
||||
// add as description
|
||||
const desc = REMARK.stringify(subListItem);
|
||||
otask.description.push(desc);
|
||||
}
|
||||
|
||||
return otask;
|
||||
} catch (error) {
|
||||
console.log("failed to parse list item:", listItem);
|
||||
}
|
||||
}
|
||||
|
||||
async function otasks_from_file(file: TFile, otask_path, priority = 0) {
|
||||
try {
|
||||
dbg("SystemC2: otasks_from_file", file, otask_path);
|
||||
|
||||
// the main otask this file is about
|
||||
let otask = {
|
||||
description: [],
|
||||
actions: [],
|
||||
path: [],
|
||||
priority,
|
||||
is_file: true,
|
||||
};
|
||||
|
||||
otask.longName = file.basename;
|
||||
otask.short = otask.longName;
|
||||
otask.path = otask_path;
|
||||
let new_otask_path = [...otask_path, otask.short];
|
||||
|
||||
const content = await app.vault.read(file);
|
||||
|
||||
// parse listItems at the top... for props
|
||||
const topListItems = getListItemsBeforeFirstHeading(content);
|
||||
for (const topListItem of topListItems) {
|
||||
const text = nodeToString(topListItem);
|
||||
|
||||
// check for prop
|
||||
if (check_otask_prop_from_list_item(topListItem, otask)) {
|
||||
new_otask_path = [...otask_path, otask.short];
|
||||
continue; // don't do any other processing on this sub-listItem
|
||||
}
|
||||
}
|
||||
|
||||
// parse all the sub sections
|
||||
const SUB_COUNT = 10;
|
||||
for (let sub_number = 0; sub_number < SUB_COUNT; sub_number++) {
|
||||
let listItems = await getListUnderHeading(content, "sub" + sub_number);
|
||||
|
||||
// "sub" without a number should have priority 5
|
||||
if (sub_number == 5) {
|
||||
listItems = listItems.concat(await getListUnderHeading(content, "sub"));
|
||||
}
|
||||
|
||||
//dbg(`sub section ${sub_number} has items:`, listItems)
|
||||
|
||||
for (const listItem of listItems) {
|
||||
// check if listItem is an action...
|
||||
let text = nodeToString(listItem.children[0]);
|
||||
if (
|
||||
text.startsWith("ac:") ||
|
||||
text.startsWith("[ ] ac:") ||
|
||||
text.startsWith("[x] ac:")
|
||||
) {
|
||||
const action = action_from_list_item(listItem, otask_path);
|
||||
otask.actions.push(action);
|
||||
}
|
||||
|
||||
queue_otasks_from_list_item(
|
||||
listItem,
|
||||
new_otask_path,
|
||||
otask.priority + sub_number,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return otask;
|
||||
} catch (error) {
|
||||
console.log("failed to parse file: ", file.path);
|
||||
}
|
||||
}
|
||||
|
||||
function action_from_list_item(listItem, otask_path) {
|
||||
dbg("SystemC2: action_from_list_item", listItem, otask_path);
|
||||
let action = {};
|
||||
let text = nodeToString(listItem.children[0]).slice(4);
|
||||
|
||||
if (text.startsWith("[")) {
|
||||
text = text.slice(4);
|
||||
}
|
||||
|
||||
action.name = text;
|
||||
|
||||
return action;
|
||||
}
|
||||
|
||||
function check_otask_prop_from_list_item(listItem, otask) {
|
||||
let text = nodeToString(listItem.children[0]);
|
||||
|
||||
for (const prop_name of OTASK_PROP_NAMES) {
|
||||
if (text.startsWith(prop_name + ":")) {
|
||||
const value = text.slice(prop_name.length + 2);
|
||||
|
||||
if (prop_name == "priority") {
|
||||
// parse priority as int
|
||||
otask[prop_name] = parseInt(value);
|
||||
} else if (prop_name == "outcome") {
|
||||
// add sub items to it
|
||||
let fullText = REMARK.stringify(listItem).slice(prop_name.length + 4);
|
||||
otask[prop_name] = fullText;
|
||||
} else {
|
||||
otask[prop_name] = value;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Extract plain text from a node
|
||||
function nodeToString(node: any): string {
|
||||
let result = "";
|
||||
visit(node, "text", (textNode: Text) => {
|
||||
result += textNode.value;
|
||||
});
|
||||
return result.trim();
|
||||
}
|
||||
|
||||
async function getListUnderHeading(
|
||||
markdown: string,
|
||||
headingText: string,
|
||||
): string[] {
|
||||
const tree = REMARK.parse(markdown);
|
||||
//dbg("tree", tree)
|
||||
|
||||
let capture = false;
|
||||
let items: string[] = [];
|
||||
|
||||
for (let i = 0; i < tree.children.length; i++) {
|
||||
const node: Content = tree.children[i];
|
||||
|
||||
// Detect the target heading
|
||||
if (
|
||||
node.type === "heading" &&
|
||||
nodeToString(node).toLowerCase() === headingText.toLowerCase()
|
||||
) {
|
||||
capture = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Stop if another heading of the same or higher level comes
|
||||
if (capture && node.type === "heading") {
|
||||
break;
|
||||
}
|
||||
|
||||
// Collect list items if capturing
|
||||
if (capture && node.type === "list") {
|
||||
for (const li of (node as List).children) {
|
||||
if (li.type === "listItem") {
|
||||
items.push(li);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
function getListItemsBeforeFirstHeading(markdown: string) {
|
||||
const tree = REMARK.parse(markdown);
|
||||
|
||||
let items = [];
|
||||
|
||||
for (const node of tree.children) {
|
||||
if (node.type === "heading") {
|
||||
// stop at first heading
|
||||
break;
|
||||
}
|
||||
if (node.type === "list") {
|
||||
for (const li of (node as List).children) {
|
||||
if (li.type === "listItem") {
|
||||
items.push(li);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
2886
packages/mize/Cargo.lock
generated
2886
packages/mize/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,97 +0,0 @@
|
||||
[package]
|
||||
name = "mize"
|
||||
version = "0.0.1"
|
||||
edition = "2021"
|
||||
license = "GPL-3.0"
|
||||
description = 'A strongly typed "filesystem" for the age of connectivity.'
|
||||
repository = "https://github.com/c2vi/mize"
|
||||
|
||||
[package.metadata.wasm-pack.profile.dev]
|
||||
wasm-opt = false
|
||||
|
||||
[lib]
|
||||
name = "mize"
|
||||
path = "src/lib.rs"
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[[bin]]
|
||||
name = "mize"
|
||||
path = "src/platform/os/main.rs"
|
||||
required-features = [ "target-os" ]
|
||||
|
||||
[features]
|
||||
default = [ "target-os" ]
|
||||
target-os= [ "clap", "home", "nix", "sysinfo", "ciborium/default", "tracing-subscriber", "async", "tracing-subscriber/env-filter", "libloading", "ciborium-io", "tracing-core", "tar", "flate2", "http_req" ]
|
||||
target-js = [ "wasm-bindgen", "console_error_panic_hook", "web-sys", "web-sys/Worker", "web-sys/Window", "web-sys/Request", "web-sys/RequestInit", "web-sys/RequestMode", "web-sys/Response", "web-sys/WorkerOptions", "web-sys/WorkerType", "serde-wasm-bindgen", "wasm-bindgen-futures", "wee_alloc"]
|
||||
async = ["tokio/net", "tokio", "tokio/rt-multi-thread", "tokio/io-util"]
|
||||
|
||||
|
||||
[dependencies]
|
||||
# core dependencies
|
||||
colored = "2.0.0"
|
||||
uuid = "1.3.0"
|
||||
ciborium = { version = "0.2.2", default-features = false }
|
||||
serde = "1.0.203"
|
||||
interner = { git = "https://github.com/c2vi/interner" }
|
||||
tracing = "0.1.40"
|
||||
serde_json = { version = "1.0.117", optional = false }
|
||||
toml = { version = "0.8.13", features = ["parse"], optional = false }
|
||||
dyn-clone = "1.0.17"
|
||||
sha2 = "0.10.8"
|
||||
flume = "0.11.1"
|
||||
mize_macros = { path = "../ac_mize_macros" }
|
||||
async-trait = "0.1.89"
|
||||
|
||||
# builtin modules
|
||||
#mize_module_blob = { path = "./modules/modules/Blob" }
|
||||
|
||||
# wasm dependencies
|
||||
wasm-bindgen = { version = "0.2.84", optional = true }
|
||||
console_error_panic_hook = { version = "0.1.7", optional = true }
|
||||
web-sys = { version = "0.3.70", optional = true }
|
||||
serde-wasm-bindgen = { version = "0.6.5", optional = true }
|
||||
wasm-bindgen-futures = { version = "0.4.49", optional = true }
|
||||
wee_alloc = { version = "0.4.5", optional = true }
|
||||
|
||||
# os dependencies
|
||||
clap = { version = "4.4.11", features = ["cargo"], optional = true }
|
||||
home = { version = "0.5.9", optional = true }
|
||||
daemonize = { version = "0.5.0", optional = true }
|
||||
nix = { version = "0.27.1", features = ["signal"], optional = true }
|
||||
sysinfo = { version = "0.30.12", optional = true }
|
||||
tracing-subscriber = { version = "0.3.18", optional = true }
|
||||
tokio = { version = "1.46.1", features = ["sync"], optional = true }
|
||||
libloading = { version = "0.8.5", optional = true }
|
||||
ciborium-io = { version = "0.2.2", optional = true }
|
||||
tracing-core = { version = "0.1.32", optional = true }
|
||||
tar = { version = "0.4.42", optional = true }
|
||||
flate2 = { version = "1.0.33", optional = true }
|
||||
http_req = { version = "0.12.0", default-features = false, features = [ "rust-tls" ], optional = true }
|
||||
#http_req = { git = "https://github.com/c2vi/http_req", optional = true, default-features = false, features = [ "native-tls" ] }
|
||||
|
||||
# bare dependencies
|
||||
|
||||
# unused dependencies
|
||||
axum = { version = "0.6.1", features = ["ws", "headers"], optional = true }
|
||||
axum-extra = { version = "0.4.2", features = ["spa"], optional = true }
|
||||
axum-macros = { version = "0.3.0", optional = true }
|
||||
#tokio-core = "0.1.18"
|
||||
#tokio-io = "0.1.13"
|
||||
|
||||
#tokio-stream = { version = "0.1.9", optional = true }
|
||||
#derive_more = "0.99.17"
|
||||
#futures-util = "0.3.24"
|
||||
#itertools = "0.10.5"
|
||||
#lazy_static = "1.4.0"
|
||||
#rmp-serde = "1.1.1"
|
||||
#rmpv = { version = "1.0.0", features = ["serde", "with-serde"] }
|
||||
#toml = "0.5.10"
|
||||
#tower-http = "0.3.5"
|
||||
|
||||
|
||||
[dev-dependencies]
|
||||
wasm-bindgen-test = { version = "0.3.34" }
|
||||
|
||||
[profile.release]
|
||||
# Tell `rustc` to optimize for small code size.
|
||||
opt-level = "s"
|
||||
@@ -1,674 +0,0 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -1,25 +0,0 @@
|
||||
//use std::env;
|
||||
|
||||
fn main() {
|
||||
// compile the string plugin
|
||||
//let mut string_module = Command::new("bash");
|
||||
//string_module.arg("-c");
|
||||
//string_module.arg("echo hiiiiiiiiiiiiiiiii");
|
||||
//string_module.arg("--help");
|
||||
//string_module.arg("--out-dir");
|
||||
//string_module.arg(out_dir);
|
||||
//string_module.env("PWD", "/hoem/me/work/mize/module/modules/Blob");
|
||||
|
||||
//let _res = string_module.spawn();
|
||||
//let _child = Command::new("cargo")
|
||||
//.arg("build")
|
||||
//.arg("--lib")
|
||||
//.arg("--manifest-path")
|
||||
//.arg("/home/me/work/mize/modules/modules/Blob/Cargo.toml")
|
||||
//.spawn()
|
||||
//.expect("failed to start wasm build");
|
||||
|
||||
//to outdir (), using the nightly feature --out-dir to have the result there. By default I get a libhearts.rlib
|
||||
|
||||
//println!("cargo:rustc-link-arg=-zstack-size=0x1000000");
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"name": "@ppc/mize",
|
||||
"imports": {},
|
||||
"exports": "./src/platform/js/index.ts"
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
|
||||
set -e
|
||||
|
||||
|
||||
|
||||
if [[ "$1" == "a" ]]
|
||||
then
|
||||
ssh acern mkdir -p /tmp/mize-src
|
||||
ssh acern mkdir -p ~/work/modules
|
||||
rsync -rv --exclude="target" --exclude="gitignore" ./* acern:/tmp/mize-src/
|
||||
rsync -rv --exclude="target" --exclude="gitignore" --exclude="node_modules" ~/work/modules acern:work/
|
||||
path=$(ssh acern /home/me/out/nix/bin/nix build /tmp/mize-src#dist -L --print-out-paths)
|
||||
|
||||
echo doneeeeeeeeeeeeeee building
|
||||
echo path: $path
|
||||
|
||||
#scp -r acern:$path/* ocih:host/webserver/webfiles
|
||||
tmp=$(mktemp -d)
|
||||
[[ "$path" != "" ]] && rsync -rv -p --chmod=u+w acern:$path/* $tmp
|
||||
[[ "$path" != "" ]] && rsync -rv $tmp/* ocih:host/data/my-website --rsync-path="sudo rsync"
|
||||
|
||||
|
||||
|
||||
elif [[ "$1" == "c" ]] # only copy files to acern
|
||||
then
|
||||
ssh acern mkdir -p /tmp/mize-src
|
||||
ssh acern mkdir -p ~/work/modules
|
||||
rsync -rv --exclude="target" --exclude="gitignore" ./* acern:/tmp/mize-src/
|
||||
rsync -rv --exclude="target" --exclude="gitignore" --exclude="node_modules" ~/work/modules acern:work/
|
||||
|
||||
|
||||
|
||||
else
|
||||
path=$(nix build .#dist -L -v --print-out-paths $@)
|
||||
|
||||
echo doneeeeeeeeeeeeeee building
|
||||
echo path: $path
|
||||
|
||||
#scp -r $path/* ocih:host/webserver/webfiles
|
||||
[[ "$path" != "" ]] && rsync -rv $path/* ocih:host/data/my-website --rsync-path="sudo rsync"
|
||||
fi
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
|
||||
nix develop .#mizeFor.x86_64-linux-gnu.main.devShell --override-input nixpkgs github:NixOS/nixpkgs/ea6033ce4ddf2c0ede2ea147a450d4f880796128
|
||||
@@ -1,22 +0,0 @@
|
||||
|
||||
# Use mize in a js project
|
||||
|
||||
## On the Web
|
||||
```bash
|
||||
npm init wasm-app project_dir
|
||||
cd project_dir
|
||||
npm install @c2vi/mize
|
||||
```
|
||||
|
||||
|
||||
|
||||
## Build npm package yourself
|
||||
### with nix
|
||||
```bash
|
||||
nix build github:c2vi/mize#npmPackage
|
||||
```
|
||||
|
||||
### without nix
|
||||
```bash
|
||||
wasm-pack build -- --features target-wasm
|
||||
```
|
||||
@@ -1,18 +0,0 @@
|
||||
#!/bin/sh
|
||||
#set -e
|
||||
|
||||
# this is a Victorinix Wrapper
|
||||
source $($VIC_BINARY print-wrapper-path)
|
||||
|
||||
BINARY=/home/me/work/mize/target/debug/mize
|
||||
|
||||
function vic_build_func() {
|
||||
nix develop ~/work/victorinix --impure -c cargo build --manifest-path ~/work/victorinix/Cargo.toml
|
||||
}
|
||||
|
||||
vic_wrapper_run "$@"
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
use crate::mize_err;
|
||||
use crate::MizeResult;
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
use crate::item::ItemData;
|
||||
use crate::Mize;
|
||||
use crate::MizeError;
|
||||
|
||||
type ConfigThunk = Box<dyn Fn() -> ItemData + Send + Sync>;
|
||||
|
||||
pub struct ConfigOpt {
|
||||
pub name: String,
|
||||
pub val: Option<ItemData>,
|
||||
pub thunk: Option<ConfigThunk>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ConfigOptNameAndMize {
|
||||
pub name: String,
|
||||
pub mize: Mize,
|
||||
}
|
||||
|
||||
impl ConfigOptNameAndMize {
|
||||
pub fn default_val(self, val: ItemData) -> ConfigOptNameAndMize {
|
||||
let mut config_opts = self.mize.config_opts.lock().unwrap();
|
||||
let opt = config_opts.get_mut(&self.name).unwrap();
|
||||
opt.val = Some(val);
|
||||
self.clone()
|
||||
}
|
||||
pub fn fun(self, thunk: ConfigThunk) -> Self {
|
||||
let mut config_opts = self.mize.config_opts.lock().unwrap();
|
||||
let opt = config_opts.get_mut(&self.name).unwrap();
|
||||
opt.thunk = Some(thunk);
|
||||
self.clone()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn gather_config(mize: &mut Mize) -> MizeResult<()> {
|
||||
let mut config_opts = mize.config_opts.lock().unwrap();
|
||||
let parts = mize.parts.lock().unwrap();
|
||||
|
||||
for part in parts.values() {
|
||||
part.as_deref().unwrap().opts(&mut mize.clone());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,348 +0,0 @@
|
||||
use colored::Colorize;
|
||||
use core::result::Result;
|
||||
use core::result::Result::Ok;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::format;
|
||||
use std::fmt::Debug;
|
||||
use std::fmt::Display;
|
||||
use std::io;
|
||||
use std::string::FromUtf8Error;
|
||||
use tracing::{debug, error, info, trace, warn};
|
||||
|
||||
//use crate::proto::MizeMessage;
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! mize_err {
|
||||
($($arg:tt)*) => { MizeError::new().msg(format!( $($arg)*)) };
|
||||
}
|
||||
|
||||
pub type MizeResult<T> = Result<T, MizeError>;
|
||||
|
||||
pub trait MizeResultTrait<T> {
|
||||
fn critical(self) -> T;
|
||||
fn as_std(self) -> Result<T, MizeErrorWhichImplementsError>;
|
||||
}
|
||||
|
||||
pub trait IntoMizeResult<T, S> {
|
||||
fn mize_result(self) -> MizeResult<T>;
|
||||
fn mize_result_msg(self, msg: S) -> MizeResult<T>
|
||||
where
|
||||
S: std::fmt::Display;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MizeError {
|
||||
pub category: Vec<String>,
|
||||
pub code: u32,
|
||||
pub messages: Vec<String>,
|
||||
//pub caused_by_msg: Option<CausedByMessage>,
|
||||
pub code_location: Option<MizeCodeLocation>,
|
||||
pub backtrace: String,
|
||||
}
|
||||
|
||||
/*
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CausedByMessage {
|
||||
// peer: &Connection, // TODO: add later
|
||||
msg: Box<MizeMessage>,
|
||||
}
|
||||
*/
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MizeCodeLocation {
|
||||
file: String,
|
||||
line: u32,
|
||||
column: u32,
|
||||
}
|
||||
|
||||
impl Display for MizeCodeLocation {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"file: {} line: {} column: {}",
|
||||
self.file, self.line, self.column
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&std::panic::Location<'_>> for MizeCodeLocation {
|
||||
fn from(panic_location: &std::panic::Location) -> MizeCodeLocation {
|
||||
let file = panic_location.file().to_string();
|
||||
let line = panic_location.line();
|
||||
let column = panic_location.column();
|
||||
MizeCodeLocation { file, line, column }
|
||||
}
|
||||
}
|
||||
|
||||
impl MizeError {
|
||||
#[track_caller]
|
||||
pub fn code(code: u32) -> MizeError {
|
||||
let caller_location = std::panic::Location::caller();
|
||||
|
||||
get_error_by_code(code, caller_location)
|
||||
}
|
||||
|
||||
pub fn set_code(mut self, code: u32) -> MizeError {
|
||||
self.code = code;
|
||||
return self;
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
pub fn new() -> MizeError {
|
||||
let caller_location = std::panic::Location::caller();
|
||||
|
||||
return MizeError {
|
||||
category: Vec::new(),
|
||||
code: 0,
|
||||
messages: Vec::new(),
|
||||
code_location: Some(caller_location.into()),
|
||||
backtrace: format!("{}", std::backtrace::Backtrace::capture()),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn msg<E>(mut self, msg: E) -> MizeError
|
||||
where
|
||||
E: std::fmt::Display,
|
||||
{
|
||||
self.messages.push(format!("{}", msg));
|
||||
return self;
|
||||
}
|
||||
|
||||
pub fn category<T>(mut self, category: T) -> MizeError
|
||||
where
|
||||
T: Into<String>,
|
||||
{
|
||||
self.category.push(category.into());
|
||||
return self;
|
||||
}
|
||||
|
||||
fn send(self) -> MizeError {
|
||||
self
|
||||
}
|
||||
|
||||
fn add_to_err_item(self) -> MizeError {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn log(self) -> MizeError {
|
||||
error!("MizeError encountered!");
|
||||
|
||||
if let Some(ref location) = self.code_location {
|
||||
error!("[ {} ] {}", "LOCATION".yellow(), location);
|
||||
};
|
||||
|
||||
error!("[ {} ] {}", "BACKTRACE".yellow(), self.backtrace);
|
||||
|
||||
for msg in &self.messages {
|
||||
error!("[ {} ] {}", "MSG".yellow(), msg);
|
||||
}
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
pub fn handle(self) -> MizeError {
|
||||
return self.send().add_to_err_item().log();
|
||||
}
|
||||
|
||||
pub fn critical(self) {
|
||||
let mut msg_iter = self.messages.iter();
|
||||
match msg_iter.next() {
|
||||
None => {
|
||||
error!("{} MizeError with code: {}", "CRITICAL".red(), self.code);
|
||||
}
|
||||
Some(msg) => {
|
||||
error!(
|
||||
"{} MizeError with code: {} - {}",
|
||||
"CRITICAL".red(),
|
||||
self.code,
|
||||
msg
|
||||
);
|
||||
}
|
||||
}
|
||||
for msg in msg_iter {
|
||||
error!("{} {}", "MSG".red(), msg)
|
||||
}
|
||||
if let Some(location) = self.code_location {
|
||||
error!("{} {}", "LOCATION".red(), location)
|
||||
}
|
||||
panic!();
|
||||
}
|
||||
|
||||
pub fn location(mut self, location: MizeCodeLocation) -> MizeError {
|
||||
self.code_location = Some(location);
|
||||
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
pub trait MizeResultExtension<T> {
|
||||
fn extra_msg<E>(self, msg: E) -> Result<T, MizeError>
|
||||
where E: std::fmt::Display
|
||||
;
|
||||
fn handle(self) -> Result<T, MizeError>;
|
||||
|
||||
fn is_critical(self) -> T;
|
||||
}
|
||||
|
||||
impl<T> MizeResultExtension<T> for Result<T, MizeError> {
|
||||
fn msg<E>(mut self, msg: E) -> Result<T, MizeError>
|
||||
where E: std::fmt::Display
|
||||
{
|
||||
match self {
|
||||
Err(ref mut e) => {
|
||||
e.msg.push(format!("{}", msg));
|
||||
return self;
|
||||
},
|
||||
Ok(something) => Ok(something),
|
||||
}
|
||||
}
|
||||
fn handle(self) -> Result<T, MizeError> {
|
||||
match self {
|
||||
Err(e) => {
|
||||
Err(e.send().add_to_err_item().write_to_stderr())
|
||||
},
|
||||
Ok(something) => Ok(something)
|
||||
}
|
||||
}
|
||||
fn is_critical(self) -> T {
|
||||
self.expect("Aborting because of a critical Error")
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
/*
|
||||
impl From<FromUtf8Error> for MizeError {
|
||||
#[track_caller]
|
||||
fn from(utf_err: FromUtf8Error) -> MizeError{
|
||||
let caller_location = std::panic::Location::caller();
|
||||
|
||||
let mut err = MizeError::code(109).msg(format!("From std::string::FromUtf8Error: {}", utf_err));
|
||||
err.code_location = Some(caller_location.into());
|
||||
return err;
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
impl<T: Display> From<T> for MizeError {
|
||||
#[track_caller]
|
||||
fn from(value: T) -> Self {
|
||||
let caller_location = std::panic::Location::caller();
|
||||
MizeError::new()
|
||||
.msg(format!(
|
||||
"From {}: {}",
|
||||
std::any::type_name_of_val(&value),
|
||||
value
|
||||
))
|
||||
.location(caller_location.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> MizeResultTrait<T> for MizeResult<T> {
|
||||
fn critical(self) -> T {
|
||||
match self {
|
||||
Ok(val) => val,
|
||||
Err(err) => {
|
||||
err.critical();
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
}
|
||||
fn as_std(self) -> Result<T, MizeErrorWhichImplementsError> {
|
||||
match self {
|
||||
Ok(val) => Ok(val),
|
||||
Err(err) => Err(MizeErrorWhichImplementsError { inner: err }),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, E, S> IntoMizeResult<T, S> for Result<T, E>
|
||||
where
|
||||
E: std::fmt::Display,
|
||||
{
|
||||
#[track_caller]
|
||||
fn mize_result(self) -> MizeResult<T> {
|
||||
let caller_location = std::panic::Location::caller();
|
||||
|
||||
match self {
|
||||
Ok(val) => MizeResult::Ok(val),
|
||||
Err(err) => MizeResult::Err(MizeError::new().category("misc").msg(format!(
|
||||
"From {}: {}",
|
||||
std::any::type_name_of_val(&err),
|
||||
err
|
||||
))),
|
||||
}
|
||||
}
|
||||
#[track_caller]
|
||||
fn mize_result_msg(self, msg: S) -> MizeResult<T>
|
||||
where
|
||||
S: std::fmt::Display,
|
||||
{
|
||||
let caller_location = std::panic::Location::caller();
|
||||
match self {
|
||||
Ok(val) => MizeResult::Ok(val),
|
||||
Err(err) => MizeResult::Err(
|
||||
MizeError::new()
|
||||
.category("misc")
|
||||
.msg(format!("{}", msg))
|
||||
.msg(format!(
|
||||
"From {}: {}",
|
||||
std::any::type_name_of_val(&err),
|
||||
err
|
||||
)),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_error_by_code(code: u32, caller_location: &std::panic::Location) -> MizeError {
|
||||
let err = MizeError {
|
||||
category: Vec::new(),
|
||||
code: 0,
|
||||
messages: Vec::new(),
|
||||
code_location: Some(caller_location.into()),
|
||||
backtrace: format!("{}", std::backtrace::Backtrace::capture()),
|
||||
};
|
||||
|
||||
match code {
|
||||
109 => err
|
||||
.set_code(109)
|
||||
.category("decoding")
|
||||
.msg("conversion from utf8 failed"),
|
||||
108 => err
|
||||
.set_code(108)
|
||||
.category("decoding")
|
||||
.msg("serde deserialisation failed"),
|
||||
_ => err,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MizeErrorWhichImplementsError {
|
||||
inner: MizeError,
|
||||
}
|
||||
|
||||
impl Display for MizeErrorWhichImplementsError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "MizeError envountered!");
|
||||
|
||||
if let Some(ref location) = self.inner.code_location {
|
||||
write!(f, "[ {} ] {}", "LOCATION".yellow(), location);
|
||||
};
|
||||
|
||||
write!(f, "[ {} ] {}", "BACKTRACE".yellow(), self.inner.backtrace);
|
||||
|
||||
for msg in &self.inner.messages {
|
||||
write!(f, "[ {} ] {}", "MSG".yellow(), msg);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<MizeError> for MizeErrorWhichImplementsError {
|
||||
fn from(value: MizeError) -> Self {
|
||||
MizeErrorWhichImplementsError { inner: value }
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for MizeErrorWhichImplementsError {}
|
||||
@@ -1,199 +0,0 @@
|
||||
use core::fmt;
|
||||
use interner::{
|
||||
shared::{SharedPool, SharedString, SharedVecString},
|
||||
Pooled,
|
||||
};
|
||||
use std::collections::hash_map::RandomState;
|
||||
use std::path::Path;
|
||||
use std::{collections::binary_heap::Iter, fmt::write, hash::Hash};
|
||||
|
||||
use crate::error::{MizeError, MizeResult, MizeResultTrait};
|
||||
use crate::{
|
||||
instance::{store::Store, Mize},
|
||||
mize_err,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
|
||||
pub struct MizeId {
|
||||
pub path: SharedVecString,
|
||||
pub namespace: Namespace,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
|
||||
pub struct Namespace(pub SharedString);
|
||||
|
||||
impl Namespace {
|
||||
pub fn as_string(&self) -> SharedString {
|
||||
self.0.clone()
|
||||
}
|
||||
pub fn as_real_string(&self) -> String {
|
||||
let a = self.as_string();
|
||||
let b = a.to_string();
|
||||
return b;
|
||||
}
|
||||
}
|
||||
|
||||
pub trait IntoMizeId {
|
||||
fn to_mize_id(self, instance: &Mize) -> MizeResult<MizeId>;
|
||||
}
|
||||
|
||||
impl MizeId {
|
||||
pub fn store_part(&self) -> &str {
|
||||
self.path
|
||||
.iter()
|
||||
.nth(0)
|
||||
.expect("an empty MizeId found, that should absolutely not be possible!!!!")
|
||||
.as_str()
|
||||
}
|
||||
|
||||
pub fn nth_part(&self, n: usize) -> MizeResult<&str> {
|
||||
match self.path.iter().nth(n) {
|
||||
Some(val) => Ok(val.as_str()),
|
||||
None => Err(mize_err!("id does not have {} parts", n)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn path(&self) -> SharedVecString {
|
||||
self.path.clone()
|
||||
}
|
||||
|
||||
pub fn after_store_part(&self) -> Vec<String> {
|
||||
let tmp = self.path();
|
||||
let mut path_iter = tmp.into_iter();
|
||||
path_iter.next();
|
||||
let new_path: Vec<String> = path_iter.map(|v| v.to_owned()).collect();
|
||||
|
||||
return new_path;
|
||||
}
|
||||
|
||||
pub fn namespace(&self) -> Namespace {
|
||||
self.namespace.clone()
|
||||
}
|
||||
|
||||
pub fn namespace_str(&self) -> &str {
|
||||
&self.namespace.0
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for MizeId {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self.path.join("/"))
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoMizeId for &str {
|
||||
fn to_mize_id(self, instance: &Mize) -> MizeResult<MizeId> {
|
||||
instance.id_from_string(self.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoMizeId for String {
|
||||
fn to_mize_id(self, instance: &Mize) -> MizeResult<MizeId> {
|
||||
instance.id_from_string(self)
|
||||
}
|
||||
}
|
||||
impl IntoMizeId for &String {
|
||||
fn to_mize_id(self, instance: &Mize) -> MizeResult<MizeId> {
|
||||
instance.id_from_string(self.to_owned())
|
||||
}
|
||||
}
|
||||
impl IntoMizeId for Vec<String> {
|
||||
fn to_mize_id(self, instance: &Mize) -> MizeResult<MizeId> {
|
||||
instance.id_from_vec_string(self)
|
||||
}
|
||||
}
|
||||
impl IntoMizeId for Vec<&String> {
|
||||
fn to_mize_id(self, instance: &Mize) -> MizeResult<MizeId> {
|
||||
let owned = self
|
||||
.into_iter()
|
||||
.map(|s| s.to_owned())
|
||||
.collect::<Vec<String>>();
|
||||
instance.id_from_vec_string(owned)
|
||||
}
|
||||
}
|
||||
impl IntoMizeId for &[&str] {
|
||||
fn to_mize_id(self, instance: &Mize) -> MizeResult<MizeId> {
|
||||
let mut vec: Vec<String> = Vec::new();
|
||||
for i in self {
|
||||
vec.push((*i).to_owned())
|
||||
}
|
||||
instance.id_from_vec_string(vec)
|
||||
}
|
||||
}
|
||||
impl IntoMizeId for Vec<&str> {
|
||||
fn to_mize_id(self, instance: &Mize) -> MizeResult<MizeId> {
|
||||
let mut vec: Vec<String> = Vec::new();
|
||||
for i in self {
|
||||
vec.push((*i).to_owned())
|
||||
}
|
||||
instance.id_from_vec_string(vec)
|
||||
}
|
||||
}
|
||||
impl IntoMizeId for MizeId {
|
||||
fn to_mize_id(self, instance: &Mize) -> MizeResult<MizeId> {
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
|
||||
// would only work with a global id_pool
|
||||
// for now use Instance::new_id()
|
||||
//impl<T: Into<String>> From<T> for MizeId {
|
||||
//fn from(value: T) -> Self {
|
||||
//let string = value.into();
|
||||
//let path: Vec<String> = string.split("/").map(|v| v.to_owned()).collect();
|
||||
//return MizeId { MIZE_ID_POOL.get(path) }
|
||||
//}
|
||||
//}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::instance::Mize;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_id() -> MizeResult<()> {
|
||||
let instance = Mize::empty()?;
|
||||
|
||||
let id_one = instance.new_id("0/config/hi")?;
|
||||
assert_eq!(instance.get_namespace()?, id_one.namespace());
|
||||
assert_eq!("0", id_one.store_part());
|
||||
assert_eq!(
|
||||
vec!["config".to_owned(), "hi".to_owned()],
|
||||
id_one.after_store_part()
|
||||
);
|
||||
|
||||
let id_two = instance.new_id("test.ns:hello/config/hi")?;
|
||||
assert_eq!(
|
||||
instance.namespace_from_string("test.ns".to_owned())?,
|
||||
id_two.namespace()
|
||||
);
|
||||
assert_eq!("hello", id_two.store_part());
|
||||
assert_eq!(
|
||||
vec!["config".to_owned(), "hi".to_owned()],
|
||||
id_one.after_store_part()
|
||||
);
|
||||
|
||||
let id_three = instance.new_id("0/")?;
|
||||
assert_eq!(instance.get_namespace()?, id_three.namespace());
|
||||
assert_eq!("0", id_three.store_part());
|
||||
assert_eq!(Vec::<String>::new(), id_three.after_store_part());
|
||||
|
||||
let id_four = instance.new_id("test.ns:0/")?;
|
||||
assert_eq!(
|
||||
instance.namespace_from_string("test.ns".to_owned())?,
|
||||
id_four.namespace()
|
||||
);
|
||||
assert_eq!("0", id_four.store_part());
|
||||
assert_eq!(Vec::<String>::new(), id_four.after_store_part());
|
||||
|
||||
let id_fife = instance.new_id("0")?;
|
||||
assert_eq!(instance.get_namespace()?, id_fife.namespace());
|
||||
assert_eq!("0", id_fife.store_part());
|
||||
assert_eq!(Vec::<String>::new(), id_fife.after_store_part());
|
||||
|
||||
//TODO: add the parsing form mize:// urls....
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
use flume::{Receiver, Sender};
|
||||
use tracing::{debug, error, info, trace, warn};
|
||||
|
||||
use crate::error::{IntoMizeResult, MizeError, MizeResult};
|
||||
use crate::id::Namespace;
|
||||
use crate::mize_err;
|
||||
use crate::proto::MizeMessage;
|
||||
|
||||
use super::Mize;
|
||||
use crate::item::{get_raw_from_cbor, Item, ItemData};
|
||||
|
||||
// only created with Instance::new_connection()
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Connection {
|
||||
pub tx: Sender<MizeMessage>,
|
||||
pub id: u64,
|
||||
pub ns: Option<Namespace>,
|
||||
}
|
||||
|
||||
pub trait ConnListener: Send + Sync {
|
||||
fn listen(self, instance: Mize) -> MizeResult<()>;
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
pub fn send(&self, msg: MizeMessage) -> MizeResult<()> {
|
||||
Ok(self.tx.send(msg)?)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value_raw_con_by_id(item: &mut Item) -> MizeResult<ItemData> {
|
||||
if item.id().nth_part(3)? == "peer" {
|
||||
return value_raw_from_peer(item);
|
||||
} else {
|
||||
return Err(mize_err!("id with path: '{}' is not supported", item.id()));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value_raw_from_peer(item: &mut Item) -> MizeResult<ItemData> {
|
||||
let id = item.id();
|
||||
|
||||
let conn_id_str = id.nth_part(2)?;
|
||||
let conn_id: u64 = conn_id_str.parse()?;
|
||||
let tmp_path = id.path();
|
||||
let mut new_id_str = tmp_path.into_iter();
|
||||
let skipped = new_id_str.skip(4);
|
||||
let new_id = item.instance.new_id(skipped.collect::<Vec<&String>>())?;
|
||||
|
||||
let connection = item.instance.get_connection(conn_id)?;
|
||||
|
||||
let msg = MizeMessage::new_get(new_id.clone(), connection.id);
|
||||
|
||||
connection.tx.send(msg)?;
|
||||
|
||||
let data = item.instance.give_msg_wait(new_id)?;
|
||||
|
||||
return Ok(data);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,2 +0,0 @@
|
||||
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
use dyn_clone::DynClone;
|
||||
use std::fmt::Debug;
|
||||
use std::iter::Map;
|
||||
use std::option::Iter;
|
||||
|
||||
use crate::error::MizeResult;
|
||||
use crate::id::MizeId;
|
||||
use crate::instance::Mize;
|
||||
use crate::item::get_raw_from_cbor;
|
||||
use crate::item::{Item, ItemData};
|
||||
use crate::memstore::MemStore;
|
||||
|
||||
dyn_clone::clone_trait_object!(Store);
|
||||
|
||||
pub trait Store: DynClone + Send + Sync + Debug {
|
||||
// should have the ability to be multi threaded, if the underlying implementation supports
|
||||
// multithreaded IO operations
|
||||
// for now all refs to a store hold a Mutex but this mutex is part of where the MizeStore trait
|
||||
// is implemented, so that there can be a multithreaded implementation
|
||||
//fn get(self, id: MizeId) -> MizeResult<Item<Self>> where Self: Sized;
|
||||
|
||||
fn set(&self, id: MizeId, data: ItemData) -> MizeResult<()>;
|
||||
|
||||
// in the future should implement transactions, ....
|
||||
|
||||
// funcs to do with links, backlinks
|
||||
fn get_links(&self, item: Item) -> MizeResult<Vec<MizeId>>;
|
||||
|
||||
fn get_backlinks(&self, item: Item) -> MizeResult<Vec<MizeId>>;
|
||||
|
||||
fn new_id(&self) -> MizeResult<String>;
|
||||
|
||||
fn get_value_raw(&self, id: MizeId) -> MizeResult<Vec<u8>>;
|
||||
|
||||
fn get_value_data_full(&self, id: MizeId) -> MizeResult<ItemData>;
|
||||
|
||||
fn id_iter(&self) -> MizeResult<IdIter>;
|
||||
|
||||
fn next_id(&self, prev_id: &str) -> MizeResult<Option<String>>;
|
||||
|
||||
fn first_id(&self) -> MizeResult<String>;
|
||||
}
|
||||
|
||||
pub struct IdIter {
|
||||
cur_id: String,
|
||||
store: Box<dyn Store>,
|
||||
}
|
||||
|
||||
impl IdIter {
|
||||
pub fn new(store: Box<dyn Store>) -> MizeResult<IdIter> {
|
||||
Ok(IdIter {
|
||||
cur_id: store.first_id()?,
|
||||
store,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for IdIter {
|
||||
type Item = MizeResult<String>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
match self.store.next_id(&self.cur_id) {
|
||||
Err(err) => Some(Err(err)),
|
||||
Ok(Some(new_id)) => {
|
||||
self.cur_id = new_id.clone();
|
||||
Some(Ok(new_id))
|
||||
}
|
||||
Ok(None) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
use core::fmt;
|
||||
use flume::Sender;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use tracing::trace;
|
||||
|
||||
use crate::error::MizeResult;
|
||||
use crate::id::MizeId;
|
||||
use crate::instance::connection::Connection;
|
||||
use crate::item::Item;
|
||||
use crate::proto::MizeMessage;
|
||||
|
||||
use super::Mize;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Update {
|
||||
pub instance: Arc<Mize>,
|
||||
pub id: MizeId,
|
||||
}
|
||||
|
||||
impl Update {
|
||||
pub fn new_item(&self) -> MizeResult<Item> {
|
||||
self.instance.get(self.id.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub enum Subscription {
|
||||
Connection(Connection),
|
||||
Closure(Box<dyn Fn(Update) -> MizeResult<()> + Send>),
|
||||
Channel(Sender<Update>),
|
||||
}
|
||||
|
||||
impl Subscription {
|
||||
pub fn from_conn(conn: Connection) -> Subscription {
|
||||
Subscription::Connection(conn)
|
||||
}
|
||||
pub fn from_closure(closure: Box<dyn Fn(Update) -> MizeResult<()> + Send>) -> Subscription {
|
||||
Subscription::Closure(closure)
|
||||
}
|
||||
pub fn from_sender(tx: Sender<Update>) -> Subscription {
|
||||
Subscription::Channel(tx)
|
||||
}
|
||||
|
||||
pub fn handle(&mut self, update: Update) -> MizeResult<()> {
|
||||
trace!("handleing update");
|
||||
match &self {
|
||||
Subscription::Connection(conn) => {
|
||||
let msg = MizeMessage::new_update(
|
||||
update.id.clone(),
|
||||
update.new_item()?.as_data_full()?,
|
||||
conn.id,
|
||||
);
|
||||
conn.send(msg)?;
|
||||
}
|
||||
Subscription::Closure(closure) => closure(update)?,
|
||||
Subscription::Channel(tx) => {
|
||||
tx.send(update);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Subscription {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "...Subscription...")
|
||||
}
|
||||
}
|
||||
@@ -1,263 +0,0 @@
|
||||
use tracing_subscriber::registry::Data;
|
||||
|
||||
use crate::item::IntoItemData;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_sort_keys() -> MizeResult<()> {
|
||||
let mut data = ItemData::from_toml(
|
||||
r#"
|
||||
[hi]
|
||||
test = 4
|
||||
|
||||
[config]
|
||||
zzz = "hiiii"
|
||||
hi = "hello from config/hi"
|
||||
|
||||
[config.test]
|
||||
inner = "inner"
|
||||
"#,
|
||||
)?;
|
||||
|
||||
let data_sorted = ItemData::from_toml(
|
||||
r#"
|
||||
[config]
|
||||
hi = "hello from config/hi"
|
||||
test = { inner = "inner" }
|
||||
zzz = "hiiii"
|
||||
|
||||
[hi]
|
||||
test = 4
|
||||
"#,
|
||||
)?;
|
||||
|
||||
data.sort_keys()?;
|
||||
|
||||
assert_eq!(data.to_json()?, data_sorted.to_json()?);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_module_hash() -> MizeResult<()> {
|
||||
let mut instance = Mize::empty()?;
|
||||
|
||||
use crate::platform::os::get_part_hash;
|
||||
let selector_toml = r#"
|
||||
mize_version = "0.0.0"
|
||||
system = "x86_64-unknown-linux-gnu"
|
||||
toolchain_version = "rustc 1.78.0 (9b00956e5 2024-04-29)"
|
||||
"#;
|
||||
|
||||
instance.set_blocking("0/config/selector", ItemData::from_toml(&selector_toml)?)?;
|
||||
|
||||
let (hash, selector) = get_part_hash(&mut instance, "String", ItemData::new())?;
|
||||
|
||||
test_println!("hash: {}", hash);
|
||||
test_println!("selector: {}", selector);
|
||||
|
||||
assert_eq!(hash, "e96edf60216688314efc263c1aa8d6ce".to_owned());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_set_store_path() -> MizeResult<()> {
|
||||
let instance = Mize::empty()?;
|
||||
|
||||
let store_path = "/home/me/.mize".to_owned();
|
||||
|
||||
let config = instance.get("0/config")?.as_data_full()?;
|
||||
|
||||
test_println!("data at 0/config: {}", config);
|
||||
|
||||
instance.set_blocking("0/config/store_path", store_path.clone().into_item_data())?;
|
||||
|
||||
let store_path_new = instance.get("0/config/store_path")?.value_string()?;
|
||||
|
||||
assert_eq!(store_path_new, store_path);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_set_sub_path() -> MizeResult<()> {
|
||||
let instance = Mize::empty()?;
|
||||
|
||||
let data = ItemData::from_toml(
|
||||
r#"
|
||||
[config]
|
||||
hi = "hello from config/hi"
|
||||
|
||||
[config.test]
|
||||
inner = "inner"
|
||||
"#,
|
||||
)?;
|
||||
|
||||
let data_two = ItemData::from_toml(
|
||||
r#"
|
||||
[config]
|
||||
hi = "hello from config/hi"
|
||||
|
||||
[config.test]
|
||||
inner = "new inner"
|
||||
"#,
|
||||
)?;
|
||||
|
||||
let item = instance.new_item()?;
|
||||
instance.set_blocking(item.id(), data.clone())?;
|
||||
|
||||
assert_eq!(item.as_data_full()?, data);
|
||||
|
||||
// try to set a sub path of item
|
||||
instance.set_blocking(
|
||||
vec![item.id().store_part(), "config", "test", "inner"],
|
||||
"new inner".into_item_data(),
|
||||
)?;
|
||||
|
||||
// the contents of item should then be like data_two
|
||||
println!(
|
||||
"item with id '{}': {}",
|
||||
item.id(),
|
||||
instance.get(vec![item.id().store_part()])?.as_data_full()?
|
||||
);
|
||||
assert_eq!(
|
||||
instance
|
||||
.get(vec![item.id().store_part(), "config", "test", "inner"])?
|
||||
.as_data_full()?,
|
||||
ItemData::from_string("new inner")
|
||||
);
|
||||
assert_eq!(item.as_data_full()?, data_two);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_itemdata_set_path() -> MizeResult<()> {
|
||||
let mut data = ItemData::from_toml(
|
||||
r#"
|
||||
[config]
|
||||
hi = "hello from config/hi"
|
||||
|
||||
[config.test]
|
||||
inner = "inner"
|
||||
"#,
|
||||
)?;
|
||||
|
||||
let data_two = ItemData::from_toml(
|
||||
r#"
|
||||
[config]
|
||||
hi = "hello from config/hi"
|
||||
|
||||
[config.test]
|
||||
inner = "new inner"
|
||||
"#,
|
||||
)?;
|
||||
|
||||
data.set_path(
|
||||
vec!["config", "test", "inner"],
|
||||
ItemData::from_string("new inner"),
|
||||
)?;
|
||||
|
||||
assert_eq!(data, data_two);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_itemdata_merge() -> MizeResult<()> {
|
||||
let mut data = ItemData::from_toml(
|
||||
r#"
|
||||
[config]
|
||||
hi = "hello from config/hi"
|
||||
|
||||
[config.test]
|
||||
inner = "inner"
|
||||
"#,
|
||||
)?;
|
||||
|
||||
let data_two = ItemData::from_toml(
|
||||
r#"
|
||||
[config]
|
||||
hi = "hello from config/hi"
|
||||
|
||||
[config.test]
|
||||
inner = "new inner"
|
||||
"#,
|
||||
)?;
|
||||
|
||||
assert_eq!(
|
||||
data.get_path(vec!["config", "test", "inner"])?,
|
||||
ItemData::from_string("inner")
|
||||
);
|
||||
|
||||
data.merge(data_two.clone());
|
||||
|
||||
assert_eq!(data, data_two);
|
||||
|
||||
assert_eq!(
|
||||
data.get_path(vec!["config", "test", "inner"])?,
|
||||
ItemData::from_string("new inner")
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_item_merge() -> MizeResult<()> {
|
||||
let instance = Mize::empty()?;
|
||||
|
||||
let mut item = instance.new_item()?;
|
||||
|
||||
// here the item should contain "empty" data
|
||||
assert_eq!(item.as_data_full()?, ItemData::new());
|
||||
|
||||
let data = ItemData::from_toml(
|
||||
r#"
|
||||
[config]
|
||||
hi = "hello from config/hi"
|
||||
|
||||
[config.test]
|
||||
inner = "inner"
|
||||
"#,
|
||||
)?;
|
||||
|
||||
let data_two = ItemData::from_toml(
|
||||
r#"
|
||||
[config]
|
||||
hi = "hello from config/hi"
|
||||
|
||||
[config.test]
|
||||
inner = "new inner"
|
||||
"#,
|
||||
)?;
|
||||
|
||||
item.merge(data.clone())?;
|
||||
|
||||
// now it should contain data
|
||||
assert_eq!(item.as_data_full()?, data);
|
||||
|
||||
let mut sub_item = instance.get(vec![item.id().store_part(), "config", "test", "inner"])?;
|
||||
|
||||
// the sub item should have the string "inner"
|
||||
assert_eq!(sub_item.as_data_full()?, ItemData::from_string("inner"));
|
||||
|
||||
sub_item.merge(ItemData::from_string("new inner"));
|
||||
|
||||
assert_eq!(sub_item.as_data_full()?, ItemData::from_string("new inner"));
|
||||
|
||||
// also the item should be updated
|
||||
assert_eq!(item.as_data_full()?, data_two);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/*
|
||||
#[test]
|
||||
#[should_panic(expected = "correct panic")]
|
||||
fn test_cant_set_non_existent_item() -> () {
|
||||
let instance = Instance::empty().expect("wrong panic");
|
||||
instance.set_blocking("5", "hello world".into_item_data()).expect("correct panic");
|
||||
}
|
||||
*/
|
||||
@@ -1,223 +0,0 @@
|
||||
use flume::Receiver;
|
||||
use std::borrow::BorrowMut;
|
||||
use std::sync::Arc;
|
||||
use tracing::{error, trace, warn};
|
||||
|
||||
use crate::error::{MizeError, MizeResult, MizeResultTrait};
|
||||
use crate::id::MizeId;
|
||||
use crate::mize_err;
|
||||
use crate::proto::{MessageCmd, MizeMessage};
|
||||
use crate::{instance::Mize, item::ItemData};
|
||||
|
||||
use super::connection::{self, Connection};
|
||||
use super::subscription::{Subscription, Update};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Operation {
|
||||
Set(MizeId, ItemData, Option<Connection>), // bool: is_from_update_msg
|
||||
Msg(MizeMessage),
|
||||
}
|
||||
|
||||
// console_log macro
|
||||
// that can be copied into other files for debugging purposes
|
||||
#[cfg(feature = "wasm-target")]
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
#[cfg(feature = "wasm-target")]
|
||||
#[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())})
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "wasm-target"))]
|
||||
macro_rules! console_log {
|
||||
// Note that this is using the `log` function imported above during
|
||||
// `bare_bones`
|
||||
($($t:tt)*) => {};
|
||||
}
|
||||
//end of console_log macro
|
||||
|
||||
pub async fn updater_thread_async(operation_rx: Receiver<Operation>, instance: Mize) -> () {
|
||||
let mut count = 0;
|
||||
console_log!("inside an updater thread");
|
||||
|
||||
loop {
|
||||
let mut operation = match operation_rx.recv_async().await {
|
||||
Ok(val) => val,
|
||||
Err(e) => {
|
||||
instance.report_err(e.into());
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let op_str = match operation {
|
||||
Operation::Set(_, _, _) => "SET",
|
||||
Operation::Msg(_) => "MSG",
|
||||
};
|
||||
|
||||
trace!("OPERATION {} - {}", count, op_str);
|
||||
console_log!("OPERATION {} - {}", count, op_str);
|
||||
|
||||
let result = handle_operation(&mut operation, &instance);
|
||||
|
||||
trace!("OPERATION {} DONE", count);
|
||||
count += 1;
|
||||
|
||||
if let Err(err) = result {
|
||||
error!("OPERATION {} FAILED: {:?}", count, operation);
|
||||
err.log();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn updater_thread(operation_rx: Receiver<Operation>, instance: &Mize) -> MizeResult<()> {
|
||||
let mut count = 0;
|
||||
|
||||
loop {
|
||||
let mut operation = operation_rx.recv()?;
|
||||
let op_str = match operation {
|
||||
Operation::Set(_, _, _) => "SET",
|
||||
Operation::Msg(_) => "MSG",
|
||||
};
|
||||
|
||||
trace!("OPERATION {} - {}", count, op_str);
|
||||
|
||||
let result = handle_operation(&mut operation, instance);
|
||||
|
||||
trace!("OPERATION {} DONE", count);
|
||||
count += 1;
|
||||
|
||||
if let Err(err) = result {
|
||||
error!("OPERATION FAILED: {:?}", operation);
|
||||
err.log();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn handle_operation(operation: &mut Operation, instance: &Mize) -> MizeResult<()> {
|
||||
match operation {
|
||||
Operation::Set(id, value, maybe_conn) => {
|
||||
let item_data: ItemData = value.to_owned();
|
||||
let mut item = instance.get(id.clone())?;
|
||||
item.merge(item_data)?;
|
||||
|
||||
//check subs and handle them
|
||||
let mut subs_inner = instance.subs.lock()?;
|
||||
if let Some(vec) = subs_inner.get_mut(&id) {
|
||||
let update = Update {
|
||||
instance: Arc::new(instance.to_owned()),
|
||||
id: id.clone(),
|
||||
};
|
||||
for sub in vec.iter_mut() {
|
||||
// don't handle sub of type connection, in case the update comes from this
|
||||
// connection
|
||||
if let Some(conn) = maybe_conn {
|
||||
if let Subscription::Connection(conn2) = sub {
|
||||
if conn.id == conn2.id {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sub.handle(update.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Operation::Msg(msg) => handle_msg(msg, instance)?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_msg(msg: &mut MizeMessage, instance: &Mize) -> MizeResult<()> {
|
||||
match msg.cmd()? {
|
||||
MessageCmd::Get => {
|
||||
let id = msg.id(instance)?;
|
||||
let mut connection = instance.get_connection(msg.conn_id)?.clone();
|
||||
let item = instance.get(id.clone())?;
|
||||
let msg = MizeMessage::new_give(id, item.as_data_full()?, msg.conn_id);
|
||||
connection.send(msg)?;
|
||||
}
|
||||
|
||||
MessageCmd::GetSub => {
|
||||
let id = msg.id(instance)?;
|
||||
let mut connection = instance.get_connection(msg.conn_id)?.clone();
|
||||
let item = instance.get(id.clone())?;
|
||||
let msg = MizeMessage::new_give(id.clone(), item.as_data_full()?, msg.conn_id);
|
||||
connection.send(msg)?;
|
||||
let sub = Subscription::from_conn(connection.clone());
|
||||
instance.sub(id, sub)?;
|
||||
}
|
||||
|
||||
MessageCmd::Sub => {
|
||||
let id = msg.id(instance)?;
|
||||
let mut connection = instance.get_connection(msg.conn_id)?.clone();
|
||||
let sub = Subscription::from_conn(connection.clone());
|
||||
instance.sub(id, sub)?;
|
||||
}
|
||||
|
||||
MessageCmd::Update => {
|
||||
let data = msg.data()?;
|
||||
let id = msg.id(instance)?;
|
||||
let connection = instance.get_connection(msg.conn_id)?;
|
||||
instance
|
||||
.op_tx
|
||||
.send(Operation::Set(id.clone(), data, Some(connection)));
|
||||
}
|
||||
|
||||
// this should check, if the update is valid
|
||||
// but for now, we do just always accept it
|
||||
MessageCmd::UpdateRequest => {
|
||||
let data = msg.data()?;
|
||||
let id = msg.id(instance)?;
|
||||
let connection = instance.get_connection(msg.conn_id)?;
|
||||
instance
|
||||
.op_tx
|
||||
.send(Operation::Set(id.clone(), data, Some(connection)));
|
||||
}
|
||||
|
||||
MessageCmd::Give => {
|
||||
let id = msg.id(instance)?;
|
||||
let data = msg.data()?;
|
||||
let give_msg_wait_inner = instance.give_msg_wait.lock()?;
|
||||
if let Some(vec) = give_msg_wait_inner.get(&id) {
|
||||
for tx in vec {
|
||||
tx.send(data.clone());
|
||||
}
|
||||
} else {
|
||||
warn!(
|
||||
"got give msg for id '{}', that has no one waiting for it",
|
||||
id
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
MessageCmd::Create => {
|
||||
println!("instance.store: {:?}", instance.clone().store);
|
||||
let item = instance.new_item()?;
|
||||
let reply_msg = MizeMessage::new_create_reply(item.id(), msg.conn_id);
|
||||
let mut connection = instance.get_connection(msg.conn_id)?;
|
||||
connection.send(reply_msg)?;
|
||||
}
|
||||
|
||||
MessageCmd::CreateReply => {
|
||||
let create_msg_wait_inner = instance.create_msg_wait.lock()?;
|
||||
if let Some(sender) = create_msg_wait_inner.as_ref() {
|
||||
sender.send(msg.id(&mut instance.clone())?)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
_ => {
|
||||
return Err(mize_err!("got a message, that is not handeled"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,773 +0,0 @@
|
||||
use colored::Colorize;
|
||||
use core::fmt;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::fmt::Debug;
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::rc::Rc;
|
||||
use std::{collections::HashMap, fmt::Display, io::Cursor, path::PathBuf};
|
||||
use std::{i128, string};
|
||||
use tracing::{debug, error, info, instrument, trace, warn, Instrument};
|
||||
use tracing::{span, Level};
|
||||
|
||||
use crate::error::{IntoMizeResult, MizeError, MizeResult};
|
||||
use crate::id::MizeId;
|
||||
use crate::instance::connection::value_raw_con_by_id;
|
||||
use crate::instance::store::Store;
|
||||
use crate::instance::{connection, Mize};
|
||||
use crate::mize_err;
|
||||
use crate::proto::MizeMessage;
|
||||
use ciborium::Value as CborValue;
|
||||
|
||||
// a item always has to do with a Instance, which takes care of how it is updated
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Item<'a> {
|
||||
id: MizeId,
|
||||
pub instance: &'a Mize,
|
||||
}
|
||||
|
||||
// without an Instance it is not an item, but only the "data of an item"
|
||||
// and this type for now is just an alias to CborValue
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ItemData(pub CborValue);
|
||||
|
||||
impl Item<'_> {
|
||||
pub fn id(&self) -> MizeId {
|
||||
self.id.clone()
|
||||
}
|
||||
|
||||
pub fn new(id: MizeId, instance: &Mize) -> Item {
|
||||
Item { id, instance }
|
||||
}
|
||||
|
||||
pub fn value_raw(&self) -> MizeResult<Vec<u8>> {
|
||||
let data = self.as_data_full()?;
|
||||
let raw = get_raw_from_cbor(data.cbor(), vec![])?;
|
||||
return Ok(raw.to_owned());
|
||||
}
|
||||
|
||||
pub fn value_string(&self) -> MizeResult<String> {
|
||||
let raw = self.value_raw()?;
|
||||
String::from_utf8(raw.clone())
|
||||
.mize_result_msg(format!("failed to convert raw value from item '{}' into a utf-8 string. raw value was: '{:02X?}'", self.id(), raw))
|
||||
}
|
||||
|
||||
pub fn as_data_full(&self) -> MizeResult<ItemData> {
|
||||
let id = self.id();
|
||||
|
||||
// the instance we are
|
||||
if id.store_part() == "self" {
|
||||
debug!("getting item '{}' from self", self.id());
|
||||
|
||||
match id.nth_part(1)? {
|
||||
"con_by_id" => {
|
||||
return value_raw_con_by_id(&mut self.clone());
|
||||
}
|
||||
"namespace" => {
|
||||
let namespace_inner = self.instance.namespace.lock()?;
|
||||
return Ok(ItemData::from_string(namespace_inner.as_real_string()));
|
||||
}
|
||||
"self_namespace" => {
|
||||
let namespace_inner = self.instance.self_namespace.lock()?;
|
||||
return Ok(ItemData::from_string(namespace_inner.as_real_string()));
|
||||
}
|
||||
"config" => {
|
||||
let rest_path = id
|
||||
.path
|
||||
.into_iter()
|
||||
.skip(2)
|
||||
.map(|v| v.to_owned())
|
||||
.collect::<Vec<String>>()
|
||||
.join(".");
|
||||
let mut mize = self.instance.to_owned();
|
||||
return Ok(mize.get_config(rest_path.as_str())?);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
return Err(mize_err!(
|
||||
"a /self path, but the next element in the path '{:?}' is not valid",
|
||||
id.nth_part(1)
|
||||
));
|
||||
}
|
||||
|
||||
let self_namespace_inner = self.instance.self_namespace.lock()?;
|
||||
|
||||
if self.id().namespace() == self_namespace_inner.to_owned() {
|
||||
debug!("getting item '{}' from store", self.id());
|
||||
|
||||
if id.store_part() == "inst" {
|
||||
match id.nth_part(1)? {
|
||||
"con_by_id" => {
|
||||
return value_raw_con_by_id(&mut self.clone());
|
||||
}
|
||||
"namespace" => {
|
||||
let namespace_inner = self.instance.namespace.lock()?;
|
||||
return Ok(ItemData::from_string(namespace_inner.as_real_string()));
|
||||
}
|
||||
"self_namespace" => {
|
||||
let namespace_inner = self.instance.self_namespace.lock()?;
|
||||
return Ok(ItemData::from_string(namespace_inner.as_real_string()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let store_inner = self.instance.store.lock()?;
|
||||
return store_inner.get_value_data_full(self.id());
|
||||
} else {
|
||||
let mut connection = self.instance.get_connection_by_ns(self.id().namespace())?;
|
||||
|
||||
debug!(
|
||||
"getting item '{}' from connection '{}' from store",
|
||||
self.id(),
|
||||
connection.id
|
||||
);
|
||||
|
||||
let msg = MizeMessage::new_get(self.id(), connection.id);
|
||||
connection.send(msg);
|
||||
let data = self.instance.give_msg_wait(self.id())?;
|
||||
return Ok(data);
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(name = "fn.ItemData::merge")]
|
||||
pub fn merge<V: Into<ItemData> + Debug>(&mut self, mut value: V) -> MizeResult<()> {
|
||||
let mut data = self.as_data_full()?;
|
||||
//let mut data = data_full.get_path(id_path_without_store_part)?;
|
||||
trace!("item::merge data: {:?}", data);
|
||||
trace!("item::merge id: {:?}", self.id());
|
||||
|
||||
let new_data = value.into();
|
||||
|
||||
data.merge(new_data);
|
||||
trace!("item::merge new_data: {:?}", data);
|
||||
|
||||
// handle the case of /self/*
|
||||
if self.id().store_part() == "self" {
|
||||
let rest_path = self
|
||||
.id()
|
||||
.path
|
||||
.into_iter()
|
||||
.skip(1)
|
||||
.map(|v| v.to_owned())
|
||||
.collect::<Vec<String>>()
|
||||
.join("/");
|
||||
let id_for_store = self
|
||||
.instance
|
||||
.new_id("0".to_owned() + "/" + rest_path.as_str())?;
|
||||
|
||||
let store_inner = self.instance.store.lock()?;
|
||||
store_inner.set(id_for_store, data)?;
|
||||
} else if self.instance.we_are_namespace()? {
|
||||
let store_inner = self.instance.store.lock()?;
|
||||
store_inner.set(self.id(), data)?;
|
||||
} else {
|
||||
let namespace = self.id().namespace();
|
||||
let mut connection = self.instance.get_connection_by_ns(namespace)?;
|
||||
let msg = MizeMessage::new_update_request(self.id(), data, connection.id);
|
||||
connection.send(msg)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Display for Item<'a> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
//let item_data = self.as_data_full().map_err(|_| std::fmt::Error)?;
|
||||
write!(f, "Item with id: {}", self.id());
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
impl ItemData {
|
||||
pub fn new() -> ItemData {
|
||||
ItemData(CborValue::Null)
|
||||
}
|
||||
|
||||
pub fn empty() -> ItemData {
|
||||
ItemData(CborValue::Null)
|
||||
}
|
||||
|
||||
pub fn from_toml(toml_string: &str) -> MizeResult<ItemData> {
|
||||
let toml_deserializer = toml::Deserializer::new(&toml_string);
|
||||
|
||||
let value = CborValue::deserialize(toml_deserializer).mize_result_msg(format!(
|
||||
"Could not deserialize the toml string: {}",
|
||||
&toml_string
|
||||
))?;
|
||||
|
||||
return Ok(value.into_item_data());
|
||||
}
|
||||
|
||||
pub fn to_toml(&self) -> MizeResult<String> {
|
||||
let mut out_string = String::new();
|
||||
let toml_serializer = toml::Serializer::new(&mut out_string);
|
||||
CborValue::serialize(&self.cbor(), toml_serializer)?;
|
||||
Ok(out_string)
|
||||
}
|
||||
|
||||
pub fn value_string(self) -> MizeResult<String> {
|
||||
match self.cbor() {
|
||||
CborValue::Text(string) => Ok(string.to_owned()),
|
||||
_ => Err(mize_err!("this ItemData has no string value")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value_bool(self) -> MizeResult<bool> {
|
||||
match self.cbor() {
|
||||
CborValue::Bool(val) => Ok(*val),
|
||||
_ => 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 {
|
||||
let string = into_string.into();
|
||||
let data = CborValue::Text(string);
|
||||
return ItemData(data);
|
||||
}
|
||||
|
||||
pub fn to_json(self) -> MizeResult<String> {
|
||||
let mut result: Vec<u8> = Vec::new();
|
||||
|
||||
self.0
|
||||
.serialize(&mut serde_json::Serializer::new(&mut result))?;
|
||||
|
||||
Ok(String::from_utf8(result)?)
|
||||
}
|
||||
|
||||
pub fn from_json(json_str: String) -> MizeResult<ItemData> {
|
||||
let mut json_deserializer = serde_json::Deserializer::from_str(json_str.as_str());
|
||||
|
||||
let value = CborValue::deserialize(&mut json_deserializer).mize_result_msg(format!(
|
||||
"could not deserialize the json string: {}",
|
||||
json_str
|
||||
))?;
|
||||
|
||||
return Ok(value.into_item_data());
|
||||
}
|
||||
|
||||
pub fn merge(&mut self, other: ItemData) {
|
||||
item_data_merge(&mut self.0, &other.0);
|
||||
}
|
||||
|
||||
pub fn cbor(&self) -> &CborValue {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub fn from_cbor(cbor: CborValue) -> ItemData {
|
||||
ItemData(cbor)
|
||||
}
|
||||
|
||||
pub fn sort_keys(&mut self) -> MizeResult<()> {
|
||||
item_data_sort_keys(&mut self.0)
|
||||
}
|
||||
|
||||
pub fn null() -> CborValue {
|
||||
CborValue::Null
|
||||
}
|
||||
|
||||
pub fn parse<T: Into<String>>(value: T) -> ItemData {
|
||||
let value_str = value.into();
|
||||
if value_str == "false" {
|
||||
return CborValue::Bool(false).into_item_data();
|
||||
}
|
||||
if value_str == "false" {
|
||||
return CborValue::Bool(true).into_item_data();
|
||||
}
|
||||
if let Ok(int) = value_str.parse::<i128>() {
|
||||
return int.into_item_data();
|
||||
}
|
||||
return CborValue::Text(value_str).into_item_data();
|
||||
}
|
||||
|
||||
pub fn set_path<P: IntoPath, D: IntoItemData>(&mut self, path: P, value: D) -> MizeResult<()> {
|
||||
//trace!("[ {} ] ItemData::set_path()", "CALL".yellow());
|
||||
let path = path.into_path();
|
||||
let value = value.into_item_data();
|
||||
|
||||
item_data_set_path(&mut self.0, path, &value.0)
|
||||
}
|
||||
|
||||
pub fn get_path<P: IntoPath>(&self, path: P) -> MizeResult<ItemData> {
|
||||
let path = path.into_path();
|
||||
Ok(item_data_get_path(&self.0, path)?
|
||||
.to_owned()
|
||||
.into_item_data())
|
||||
}
|
||||
|
||||
pub fn get_paths_recursive(&mut self) -> MizeResult<Vec<String>> {
|
||||
let mut paths = Vec::new();
|
||||
let mut path_accu = Vec::new();
|
||||
get_paths(&mut self.0, &mut paths, &mut path_accu, true)?;
|
||||
Ok(paths)
|
||||
}
|
||||
|
||||
pub fn get_paths(&mut self) -> MizeResult<Vec<String>> {
|
||||
let mut paths = Vec::new();
|
||||
let mut path_accu = Vec::new();
|
||||
get_paths(&mut self.0, &mut paths, &mut path_accu, false)?;
|
||||
Ok(paths)
|
||||
}
|
||||
}
|
||||
|
||||
fn get_paths(
|
||||
val: &mut CborValue,
|
||||
paths: &mut Vec<String>,
|
||||
path_accu: &mut Vec<String>,
|
||||
recurse: bool,
|
||||
) -> MizeResult<()> {
|
||||
let map = val
|
||||
.as_map_mut()
|
||||
.ok_or(mize_err!("ItemData is not map... when calling get_paths"))?;
|
||||
for (key, val) in map {
|
||||
let text = key
|
||||
.as_text()
|
||||
.ok_or(mize_err!("ItemData::get_paths but key is not of type text"))?
|
||||
.to_owned();
|
||||
if recurse && val.is_map() {
|
||||
let mut path_accu = path_accu.clone();
|
||||
path_accu.push(text);
|
||||
get_paths(val, paths, &mut path_accu, recurse)?;
|
||||
} else {
|
||||
let path = path_accu.join("/") + "/" + text.as_str();
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Default for ItemData {
|
||||
fn default() -> Self {
|
||||
ItemData::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn data_from_string(data_string: String) -> MizeResult<ItemData> {
|
||||
let mut data = ItemData::new();
|
||||
|
||||
// in case it's just a string
|
||||
if !data_string.contains("=") {
|
||||
let cbor = CborValue::Text(data_string);
|
||||
return Ok(ItemData::from_cbor(cbor));
|
||||
}
|
||||
|
||||
for option in data_string.split(":") {
|
||||
//trace!("data_from_string: option: {}", option);
|
||||
if option == "".to_owned() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let path = option
|
||||
.split("=")
|
||||
.nth(0)
|
||||
.ok_or(MizeError::new().msg(format!(
|
||||
"Failed to parse Option: option '{}' has an empty path (thing before =)",
|
||||
option
|
||||
)))?;
|
||||
|
||||
//trace!("data_from_string: path: {}", path);
|
||||
|
||||
let value = option
|
||||
.split("=")
|
||||
.nth(1)
|
||||
.ok_or(MizeError::new().msg(format!(
|
||||
"Failed to parse Option: option '{}' has an empty value (thing after =)",
|
||||
option
|
||||
)))?;
|
||||
//trace!("data_from_string: value: {}", value);
|
||||
|
||||
let mut path_vec = Vec::new();
|
||||
path_vec.extend(path.split("."));
|
||||
|
||||
//trace!("data_from_string: path_vec: {:?}", path_vec);
|
||||
|
||||
data.set_path(path_vec, ItemData::parse(value))?;
|
||||
}
|
||||
|
||||
trace!("data_from_string: data: {}", data);
|
||||
return Ok(data);
|
||||
}
|
||||
|
||||
pub fn item_data_get_path(data: &CborValue, path: Vec<String>) -> MizeResult<&CborValue> {
|
||||
let mut path_iter = path.clone().into_iter();
|
||||
//println!("data: {:?}", data);
|
||||
//println!("path: {:?}", path);
|
||||
|
||||
let path_el = match path_iter.nth(0) {
|
||||
Some(val) => val,
|
||||
None => return Ok(data), // our base case
|
||||
};
|
||||
|
||||
let mut sub_data = &CborValue::Null;
|
||||
match data {
|
||||
CborValue::Map(ref map) => {
|
||||
for (key, val) in map {
|
||||
//println!("key: {:?}", key);
|
||||
//println!("path_el: {}", path_el);
|
||||
if let CborValue::Text(key_str) = key {
|
||||
if key_str == &path_el {
|
||||
sub_data = val;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val => {
|
||||
return Err(MizeError::new()
|
||||
.msg(format!(
|
||||
"Failed to get path '{:?}' from ItemData, the data at '{}' is not a map",
|
||||
path, path_el
|
||||
))
|
||||
.msg(format!("{:?} is: {:?}", path_el, val)));
|
||||
}
|
||||
};
|
||||
item_data_get_path(sub_data, path_iter.collect())
|
||||
}
|
||||
|
||||
pub fn item_data_sort_keys(data: &mut CborValue) -> MizeResult<()> {
|
||||
// for a list, sort each item of the list
|
||||
if data.is_array() {
|
||||
for el in data.as_array_mut().unwrap().iter_mut() {
|
||||
item_data_sort_keys(el)?
|
||||
}
|
||||
}
|
||||
|
||||
// sort the keys of a map
|
||||
if data.is_map() {
|
||||
let map: &mut Vec<(CborValue, CborValue)> = data.as_map_mut().unwrap();
|
||||
//map.sort_by_key(|el| el.0);
|
||||
map.sort_by(|a, b| {
|
||||
match a.0.partial_cmp(&b.0) {
|
||||
Some(val) => val,
|
||||
None => {
|
||||
// just say the two values are equal, if they can't be ordered
|
||||
std::cmp::Ordering::Equal
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// also sort every sub value
|
||||
for (key, val) in map {
|
||||
item_data_sort_keys(val)?
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn item_data_set_path(
|
||||
data: &mut CborValue,
|
||||
path: Vec<String>,
|
||||
data_to_set: &CborValue,
|
||||
) -> MizeResult<()> {
|
||||
//trace!("[ {} ] item_data_set_path()", "CALL".yellow());
|
||||
//trace!("[ {} ] data: {}", "ARG".yellow(), data.clone().into_item_data());
|
||||
//trace!("[ {} ] path: {:?}", "ARG".yellow(), path);
|
||||
//trace!("[ {} ] data_to_set: {}", "ARG".yellow(), data_to_set.clone().into_item_data());
|
||||
|
||||
test_println!("item_data_set_path ###########################");
|
||||
test_println!("data: {}", ItemData::from_cbor(data.clone()));
|
||||
test_println!("path: {:?}", path);
|
||||
test_println!("data_to_set: {}", ItemData::from_cbor(data_to_set.clone()));
|
||||
test_println!("###########################");
|
||||
|
||||
let mut path_iter = path.clone().into_iter();
|
||||
let path_el = match path_iter.nth(0) {
|
||||
Some(val) => val,
|
||||
None => {
|
||||
//trace!("item_data_set_path: base_case");
|
||||
// our base case
|
||||
*data = data_to_set.to_owned();
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
match data {
|
||||
CborValue::Map(ref mut map) => {
|
||||
for (key, val) in &mut *map {
|
||||
if let CborValue::Text(key_str) = key {
|
||||
if key_str == &path_el {
|
||||
//trace!("item_data_set_path: setting key {key_str} in map with recursive call");
|
||||
return item_data_set_path(val, path_iter.collect(), data_to_set);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// if we get here, that means, the key (which is the variable path_el) does not exist
|
||||
// in the map
|
||||
// so add it... but also with a recursive call which is needed, in case path_iter
|
||||
// longer than 1
|
||||
//trace!("item_data_set_path: adding key {path_el} to map");
|
||||
let mut inner_value = CborValue::Null;
|
||||
item_data_set_path(&mut inner_value, path_iter.collect(), data_to_set);
|
||||
map.push((CborValue::Text(path_el.clone()), inner_value));
|
||||
return Ok(());
|
||||
}
|
||||
CborValue::Null => {
|
||||
//trace!("item_data_set_path: CborValue::Null case");
|
||||
let mut inner_value = CborValue::Null;
|
||||
item_data_set_path(&mut inner_value, path_iter.collect(), data_to_set);
|
||||
|
||||
let map_vec = vec![(CborValue::Text(path_el), inner_value)];
|
||||
*data = CborValue::Map(map_vec);
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
val => {
|
||||
return Err(MizeError::new()
|
||||
.msg(format!(
|
||||
"Failed to get path '{:?}' from ItemData, the data at '{}' is not a map",
|
||||
path, path_el
|
||||
))
|
||||
.msg(format!("{:?} is: {:?}", path_el, val)));
|
||||
}
|
||||
};
|
||||
|
||||
return Err(MizeError::new().msg("unreachable"));
|
||||
}
|
||||
|
||||
pub fn item_data_merge(merge_into: &mut CborValue, other: &CborValue) {
|
||||
// needs to be recursive
|
||||
|
||||
match (merge_into, other) {
|
||||
// if both are maps
|
||||
// merge the keys/vals in the maps and call recursively on them
|
||||
(CborValue::Map(ref mut merge_into_map), CborValue::Map(ref other_map)) => {
|
||||
// go through other_map and merge those keys/values to merge_into
|
||||
for (other_key, other_val) in other_map {
|
||||
// so find that same vale in merge_into, if exists recursively merge, else just add to
|
||||
// vec
|
||||
let mut found_value = CborValue::Null;
|
||||
let mut value_found = false;
|
||||
let mut new_value_for_merge_into: Vec<(CborValue, CborValue)> = Vec::new(); // here we collect the
|
||||
// new contents of the
|
||||
// map, to assign later
|
||||
// to merge_into_map
|
||||
|
||||
for (merge_into_key, merge_into_val) in merge_into_map.clone() {
|
||||
if merge_into_key == *other_key {
|
||||
value_found = true;
|
||||
found_value = merge_into_val.to_owned();
|
||||
// if we found it, also don't add it to new_value_for_merge_into
|
||||
} else {
|
||||
//if not found push to new_value_for_merge_into
|
||||
new_value_for_merge_into
|
||||
.push((merge_into_key.to_owned(), merge_into_val.to_owned()));
|
||||
}
|
||||
}
|
||||
|
||||
if value_found {
|
||||
// we found it so merge and asign
|
||||
item_data_merge(&mut found_value, other_val);
|
||||
|
||||
// to asign push to new_value_for_merge_into, because the old was removed already
|
||||
new_value_for_merge_into.push((other_key.to_owned(), found_value));
|
||||
} else {
|
||||
// if not found, just add the other_key/val to new_value_for_merge_into
|
||||
new_value_for_merge_into.push((other_key.to_owned(), other_val.to_owned()));
|
||||
}
|
||||
|
||||
// finally, we need to asign the new_value_for_merge_into into merge_into
|
||||
*merge_into_map = new_value_for_merge_into;
|
||||
}
|
||||
}
|
||||
|
||||
// if other is Null, don't asign
|
||||
// this is gonna have repercussions.... because it's not clean behaviour
|
||||
(merge_into, CborValue::Null) => {}
|
||||
|
||||
// in any other case we just want to set merge_into to other
|
||||
// also this is the base case
|
||||
(merge_into, other) => {
|
||||
*merge_into = other.to_owned();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(name = "fn.get_raw_from_cbor")]
|
||||
pub fn get_raw_from_cbor<'a>(value: &'a CborValue, path: Vec<&String>) -> MizeResult<&'a [u8]> {
|
||||
trace!("[ {} ] value: {:?}", "ARG".yellow(), value);
|
||||
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",
|
||||
path.iter().map(|p| p.as_str()).collect::<Vec<_>>().join("."),
|
||||
other
|
||||
));
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
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());
|
||||
}
|
||||
CborValue::Map(map) => {
|
||||
let mut inner_val: &CborValue = &CborValue::Null;
|
||||
let mut inner_val_found = false;
|
||||
|
||||
// find the inner_val at path
|
||||
for (key, val) in map.into_iter() {
|
||||
if let CborValue::Text(key_text) = key {
|
||||
if key_text == path_el {
|
||||
inner_val = val;
|
||||
inner_val_found = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// if there is no value at that path
|
||||
if inner_val_found == false {
|
||||
return Err(MizeError::new()
|
||||
// jesus christ, this is a pfusch...
|
||||
.msg(format!(
|
||||
"get_raw_from_cbor: Path '{}' not Found",
|
||||
path.clone()
|
||||
.into_iter()
|
||||
.map(|v| v.to_owned())
|
||||
.collect::<Vec<String>>()
|
||||
.join("/")
|
||||
)));
|
||||
}
|
||||
|
||||
//path_iter.next();
|
||||
let inner_path = path_iter.collect();
|
||||
let ret_value = get_raw_from_cbor(inner_val, inner_path);
|
||||
trace!("[ {} ] ret value: {:?}", "RET".yellow(), ret_value);
|
||||
return ret_value;
|
||||
}
|
||||
_ => Err(MizeError::new().msg(format!(
|
||||
"get_raw_from_cbor: value is not a map, text or bytes ... value: {:?}",
|
||||
value
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
trait IntoPath {
|
||||
fn into_path(self) -> Vec<String>;
|
||||
}
|
||||
|
||||
pub trait IntoItemData {
|
||||
fn into_item_data(self) -> ItemData;
|
||||
}
|
||||
|
||||
impl IntoPath for &str {
|
||||
fn into_path(self) -> Vec<String> {
|
||||
self.to_owned().split("/").map(|v| v.to_owned()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoPath for &[&str] {
|
||||
fn into_path(self) -> Vec<String> {
|
||||
self.into_iter().map(|v| (*v).to_owned()).collect()
|
||||
}
|
||||
}
|
||||
impl IntoPath for Vec<String> {
|
||||
fn into_path(self) -> Vec<String> {
|
||||
self
|
||||
}
|
||||
}
|
||||
impl IntoPath for Vec<&str> {
|
||||
fn into_path(self) -> Vec<String> {
|
||||
self.into_iter().map(|v| v.to_owned()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoItemData for &str {
|
||||
fn into_item_data(self) -> ItemData {
|
||||
ItemData::parse(self)
|
||||
}
|
||||
}
|
||||
impl IntoItemData for String {
|
||||
fn into_item_data(self) -> ItemData {
|
||||
ItemData(self.into())
|
||||
}
|
||||
}
|
||||
impl IntoItemData for &String {
|
||||
fn into_item_data(self) -> ItemData {
|
||||
ItemData(self.to_owned().into())
|
||||
}
|
||||
}
|
||||
impl IntoItemData for CborValue {
|
||||
fn into_item_data(self) -> ItemData {
|
||||
ItemData(self)
|
||||
}
|
||||
}
|
||||
impl IntoItemData for ItemData {
|
||||
fn into_item_data(self) -> ItemData {
|
||||
self
|
||||
}
|
||||
}
|
||||
impl IntoItemData for i128 {
|
||||
fn into_item_data(self) -> ItemData {
|
||||
ItemData(self.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ItemData {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "ItemData: ");
|
||||
let display_writer = DisplayWriter(f);
|
||||
self.0
|
||||
.serialize(&mut serde_json::Serializer::pretty(display_writer))
|
||||
.map_err(|serde_err| std::fmt::Error)
|
||||
}
|
||||
}
|
||||
|
||||
// thanks to: https://stackoverflow.com/a/61768916
|
||||
struct DisplayWriter<'a, 'b>(&'a mut fmt::Formatter<'b>);
|
||||
|
||||
impl<'a, 'b> io::Write for DisplayWriter<'a, 'b> {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::result::Result<usize, std::io::Error> {
|
||||
self.0
|
||||
.write_str(&String::from_utf8_lossy(bytes))
|
||||
.map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;
|
||||
|
||||
Ok(bytes.len())
|
||||
}
|
||||
fn flush(&mut self) -> std::result::Result<(), std::io::Error> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for ItemData {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
let mut buf: Vec<u8> = Vec::new();
|
||||
let mut buf_other: Vec<u8> = Vec::new();
|
||||
|
||||
ciborium::into_writer(&self.0, &mut buf);
|
||||
ciborium::into_writer(&other.0, &mut buf_other);
|
||||
|
||||
buf == buf_other
|
||||
}
|
||||
}
|
||||
impl Eq for ItemData {}
|
||||
@@ -1,3 +0,0 @@
|
||||
|
||||
#![ allow( warnings ) ]
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
// console_log macro
|
||||
// that can be copied into other files for debugging purposes
|
||||
#[cfg(feature = "wasm-target")]
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
#[cfg(feature = "wasm-target")]
|
||||
#[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())})
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! add_parts {
|
||||
($mize:expr, $($part:expr),+) => {
|
||||
$(
|
||||
let part = $part.create($mize.clone());
|
||||
$mize.add_part(
|
||||
part
|
||||
);
|
||||
)+
|
||||
mize.init_parts();
|
||||
};
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
use ciborium::Value as CborValue;
|
||||
use colored::Colorize;
|
||||
use std::collections::binary_heap::Iter;
|
||||
use std::collections::HashMap;
|
||||
use std::iter::Map;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tracing::{instrument, trace};
|
||||
|
||||
use crate::error::{IntoMizeResult, MizeError, MizeResult};
|
||||
use crate::id::MizeId;
|
||||
use crate::instance::store::{IdIter, Store};
|
||||
use crate::instance::Mize;
|
||||
use crate::item::get_raw_from_cbor;
|
||||
use crate::item::{Item, ItemData};
|
||||
use crate::mize_err;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MemStore {
|
||||
inner: Arc<Mutex<MemStoreInner>>,
|
||||
}
|
||||
|
||||
pub type MemStoreId = u64;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct MemStoreInner {
|
||||
map: HashMap<u64, ItemData>,
|
||||
next_id: u64,
|
||||
}
|
||||
|
||||
impl Store for MemStore {
|
||||
fn set(&self, id: MizeId, data: ItemData) -> MizeResult<()> {
|
||||
let mut inner = self.inner.lock()?;
|
||||
|
||||
if let Some(old_data) = inner.map.get(&id_to_u64(id.clone())?) {
|
||||
//if there is already data there, set at the correct path
|
||||
let mut old_data = old_data.to_owned();
|
||||
let path = id.after_store_part();
|
||||
old_data.set_path(path, data)?;
|
||||
inner.map.insert(id_to_u64(id)?, old_data);
|
||||
} else {
|
||||
// if no data exists for that store_part, just insert
|
||||
inner.map.insert(id_to_u64(id)?, data);
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
fn get_links(&self, item: Item) -> MizeResult<Vec<MizeId>> {
|
||||
let inner = self.inner.lock()?;
|
||||
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn get_backlinks(&self, item: Item) -> MizeResult<Vec<MizeId>> {
|
||||
let inner = self.inner.lock()?;
|
||||
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn new_id(&self) -> MizeResult<String> {
|
||||
let mut inner = self.inner.lock()?;
|
||||
|
||||
let id_string = format!("{}", inner.next_id);
|
||||
inner.next_id += 1;
|
||||
return Ok(id_string);
|
||||
}
|
||||
|
||||
#[instrument(name="fn.MemStore::get_value_raw" skip(self))]
|
||||
fn get_value_raw(&self, id: MizeId) -> MizeResult<Vec<u8>> {
|
||||
trace!("[ {} ] id: {:?}", "ARG".yellow(), id);
|
||||
let inner = self.inner.lock()?;
|
||||
|
||||
let cbor_val = inner
|
||||
.map
|
||||
.get(&id_to_u64(id.clone())?)
|
||||
.ok_or(MizeError::new().msg(format!(
|
||||
"Item with store_part: {}, id: {} does not exist in MemStore",
|
||||
id_to_u64(id.clone())?,
|
||||
id
|
||||
)))?;
|
||||
|
||||
let path = id.path();
|
||||
let mut id_iter = path.iter();
|
||||
id_iter.next();
|
||||
let id_without_first = id_iter.collect();
|
||||
|
||||
Ok(get_raw_from_cbor(&cbor_val.0, id_without_first)?.to_owned())
|
||||
}
|
||||
|
||||
fn get_value_data_full(&self, id: MizeId) -> MizeResult<ItemData> {
|
||||
let inner = self.inner.lock()?;
|
||||
|
||||
let data = match inner.map.get(&id_to_u64(id.clone())?) {
|
||||
Some(val) => val.to_owned(),
|
||||
None => ItemData::new(),
|
||||
};
|
||||
|
||||
let new_path = id.after_store_part();
|
||||
let ret_data = data.get_path(new_path)?;
|
||||
|
||||
return Ok(ret_data);
|
||||
}
|
||||
fn id_iter(&self) -> MizeResult<IdIter> {
|
||||
IdIter::new(Box::new(self.to_owned()))
|
||||
}
|
||||
|
||||
fn next_id(&self, prev_id_str: &str) -> MizeResult<Option<String>> {
|
||||
let inner = self.inner.lock()?;
|
||||
|
||||
let mut id = str_to_u64(prev_id_str)?;
|
||||
|
||||
loop {
|
||||
id += 1;
|
||||
|
||||
if id > inner.next_id {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
if inner.map.contains_key(&id) {
|
||||
println!("returning: {}", id);
|
||||
return Ok(Some(format!("{}", id)));
|
||||
} else {
|
||||
// try id +1
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn first_id(&self) -> MizeResult<String> {
|
||||
Ok("0".to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
impl MemStore {
|
||||
pub fn new() -> MemStore {
|
||||
let inner = MemStoreInner {
|
||||
map: HashMap::new(),
|
||||
next_id: 0,
|
||||
};
|
||||
return MemStore {
|
||||
inner: Arc::new(Mutex::new(inner)),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn id_to_u64(id: MizeId) -> MizeResult<u64> {
|
||||
str_to_u64(id.store_part())
|
||||
}
|
||||
|
||||
fn str_to_u64(id_str: &str) -> MizeResult<u64> {
|
||||
id_str.parse().mize_result_msg(format!(
|
||||
"Could not parse the store_part of mizeid {} into a u64 for the MemStore",
|
||||
id_str
|
||||
))
|
||||
}
|
||||
@@ -1,402 +0,0 @@
|
||||
use core::fmt;
|
||||
use serde::Serialize;
|
||||
use std::io;
|
||||
|
||||
use ciborium::{value::Integer, Value as CborValue};
|
||||
|
||||
use crate::{
|
||||
error::{IntoMizeResult, MizeError, MizeResult},
|
||||
id::MizeId,
|
||||
instance::{self, connection::Connection, Mize},
|
||||
item::{IntoItemData, ItemData},
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct MizeMessage {
|
||||
value: CborValue,
|
||||
pub conn_id: u64,
|
||||
}
|
||||
|
||||
// msg items
|
||||
static MSG_CMD: u16 = 1;
|
||||
static MSG_ID: u16 = 2;
|
||||
static MSG_DATA: u16 = 3;
|
||||
|
||||
// cmds
|
||||
static CMD_GET: u16 = 1;
|
||||
static CMD_UPDATE: u16 = 2;
|
||||
static CMD_GIVE: u16 = 3;
|
||||
static CMD_CREATE: u16 = 4;
|
||||
static CMD_CREATE_REPLY: u16 = 5;
|
||||
static CMD_UPDATE_REQUEST: u16 = 6;
|
||||
static CMD_GET_SUB: u16 = 7;
|
||||
static CMD_SUB: u16 = 8;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum MessageCmd {
|
||||
Get,
|
||||
Update,
|
||||
Give,
|
||||
Create,
|
||||
CreateReply,
|
||||
UpdateRequest,
|
||||
GetSub,
|
||||
Sub,
|
||||
}
|
||||
|
||||
impl MizeMessage {
|
||||
pub fn new(value: CborValue, conn_id: u64) -> MizeMessage {
|
||||
MizeMessage { value, conn_id }
|
||||
}
|
||||
|
||||
pub fn new_get(id: MizeId, conn_id: u64) -> MizeMessage {
|
||||
let id_path = id
|
||||
.path()
|
||||
.into_iter()
|
||||
.map(|string| CborValue::Text(string.to_owned()))
|
||||
.collect();
|
||||
|
||||
let cmd = (
|
||||
CborValue::Integer(MSG_CMD.into()),
|
||||
CborValue::Integer(CMD_GET.into()),
|
||||
);
|
||||
let id = (CborValue::Integer(MSG_ID.into()), CborValue::Array(id_path));
|
||||
let value = CborValue::Map(vec![cmd, id]);
|
||||
|
||||
MizeMessage::new(value, conn_id)
|
||||
}
|
||||
|
||||
pub fn new_get_sub(id: MizeId, conn_id: u64) -> MizeMessage {
|
||||
let id_path = id
|
||||
.path()
|
||||
.into_iter()
|
||||
.map(|string| CborValue::Text(string.to_owned()))
|
||||
.collect();
|
||||
|
||||
let cmd = (
|
||||
CborValue::Integer(MSG_CMD.into()),
|
||||
CborValue::Integer(CMD_GET_SUB.into()),
|
||||
);
|
||||
let id = (CborValue::Integer(MSG_ID.into()), CborValue::Array(id_path));
|
||||
let value = CborValue::Map(vec![cmd, id]);
|
||||
|
||||
MizeMessage::new(value, conn_id)
|
||||
}
|
||||
|
||||
pub fn new_sub(id: MizeId, conn_id: u64) -> MizeMessage {
|
||||
let id_path = id
|
||||
.path()
|
||||
.into_iter()
|
||||
.map(|string| CborValue::Text(string.to_owned()))
|
||||
.collect();
|
||||
|
||||
let cmd = (
|
||||
CborValue::Integer(MSG_CMD.into()),
|
||||
CborValue::Integer(CMD_SUB.into()),
|
||||
);
|
||||
let id = (CborValue::Integer(MSG_ID.into()), CborValue::Array(id_path));
|
||||
let value = CborValue::Map(vec![cmd, id]);
|
||||
|
||||
MizeMessage::new(value, conn_id)
|
||||
}
|
||||
|
||||
pub fn new_create(conn_id: u64) -> MizeMessage {
|
||||
let cmd = (
|
||||
CborValue::Integer(MSG_CMD.into()),
|
||||
CborValue::Integer(CMD_CREATE.into()),
|
||||
);
|
||||
let value = CborValue::Map(vec![cmd]);
|
||||
|
||||
MizeMessage::new(value, conn_id)
|
||||
}
|
||||
|
||||
pub fn new_create_reply(id: MizeId, conn_id: u64) -> MizeMessage {
|
||||
let id_path = id
|
||||
.path()
|
||||
.into_iter()
|
||||
.map(|string| CborValue::Text(string.to_owned()))
|
||||
.collect();
|
||||
|
||||
let cmd = (
|
||||
CborValue::Integer(MSG_CMD.into()),
|
||||
CborValue::Integer(CMD_CREATE_REPLY.into()),
|
||||
);
|
||||
let id = (CborValue::Integer(MSG_ID.into()), CborValue::Array(id_path));
|
||||
let value = CborValue::Map(vec![cmd, id]);
|
||||
|
||||
MizeMessage::new(value, conn_id)
|
||||
}
|
||||
|
||||
pub fn new_give(id: MizeId, data: ItemData, conn_id: u64) -> MizeMessage {
|
||||
let id_path = id
|
||||
.path()
|
||||
.into_iter()
|
||||
.map(|string| CborValue::Text(string.to_owned()))
|
||||
.collect();
|
||||
|
||||
let cmd = (
|
||||
CborValue::Integer(MSG_CMD.into()),
|
||||
CborValue::Integer(CMD_GIVE.into()),
|
||||
);
|
||||
let id = (CborValue::Integer(MSG_ID.into()), CborValue::Array(id_path));
|
||||
let data = (CborValue::Integer(MSG_DATA.into()), data.cbor().to_owned());
|
||||
let value = CborValue::Map(vec![cmd, id, data]);
|
||||
|
||||
MizeMessage::new(value, conn_id)
|
||||
}
|
||||
|
||||
pub fn new_update_request(id: MizeId, data: ItemData, conn_id: u64) -> MizeMessage {
|
||||
let id_path = id
|
||||
.path()
|
||||
.into_iter()
|
||||
.map(|string| CborValue::Text(string.to_owned()))
|
||||
.collect();
|
||||
|
||||
let cmd = (
|
||||
CborValue::Integer(MSG_CMD.into()),
|
||||
CborValue::Integer(CMD_UPDATE_REQUEST.into()),
|
||||
);
|
||||
let id = (CborValue::Integer(MSG_ID.into()), CborValue::Array(id_path));
|
||||
let data = (CborValue::Integer(MSG_DATA.into()), data.cbor().to_owned());
|
||||
let value = CborValue::Map(vec![cmd, id, data]);
|
||||
|
||||
MizeMessage::new(value, conn_id)
|
||||
}
|
||||
|
||||
pub fn new_update(id: MizeId, data: ItemData, conn_id: u64) -> MizeMessage {
|
||||
let id_path = id
|
||||
.path()
|
||||
.into_iter()
|
||||
.map(|string| CborValue::Text(string.to_owned()))
|
||||
.collect();
|
||||
|
||||
let cmd = (
|
||||
CborValue::Integer(MSG_CMD.into()),
|
||||
CborValue::Integer(CMD_UPDATE.into()),
|
||||
);
|
||||
let id = (CborValue::Integer(MSG_ID.into()), CborValue::Array(id_path));
|
||||
let data = (CborValue::Integer(MSG_DATA.into()), data.cbor().to_owned());
|
||||
let value = CborValue::Map(vec![cmd, id, data]);
|
||||
|
||||
MizeMessage::new(value, conn_id)
|
||||
}
|
||||
|
||||
pub fn value(self) -> CborValue {
|
||||
self.value
|
||||
}
|
||||
|
||||
pub fn cmd(&self) -> MizeResult<MessageCmd> {
|
||||
// return err, if msg is not a map
|
||||
let msg_as_map = match &self.value {
|
||||
CborValue::Map(val) => val,
|
||||
_ => {
|
||||
return Err(MizeError::new().msg("Message was not a map"));
|
||||
}
|
||||
};
|
||||
|
||||
//check if in this map there is a c, otherwise return err
|
||||
let val_of_c = {
|
||||
let mut tmp_val = 0;
|
||||
for (key, val) in msg_as_map {
|
||||
if let CborValue::Integer(key_int) = key {
|
||||
// number one indicates the cmd field
|
||||
let one: Integer = 1.into();
|
||||
if key_int == &one {
|
||||
if let CborValue::Integer(val_int) = val {
|
||||
tmp_val = val_int.to_owned().into();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if tmp_val == 0 {
|
||||
return Err(MizeError::new().msg("error getting the cmd value form a msg"));
|
||||
}
|
||||
tmp_val
|
||||
};
|
||||
|
||||
// match on value of c
|
||||
let cmd = match val_of_c {
|
||||
1 => MessageCmd::Get,
|
||||
2 => MessageCmd::Update,
|
||||
3 => MessageCmd::Give,
|
||||
4 => MessageCmd::Create,
|
||||
5 => MessageCmd::CreateReply,
|
||||
6 => MessageCmd::UpdateRequest,
|
||||
7 => MessageCmd::GetSub,
|
||||
8 => MessageCmd::Sub,
|
||||
_ => {
|
||||
return Err(MizeError::new().msg("error cmd of msg was not a valid command"));
|
||||
}
|
||||
};
|
||||
|
||||
return Ok(cmd);
|
||||
}
|
||||
|
||||
pub fn id_str(&mut self) -> MizeResult<Vec<String>> {
|
||||
// return err, if msg is not a map
|
||||
let msg_as_map = match &self.value {
|
||||
CborValue::Map(val) => val,
|
||||
_ => {
|
||||
return Err(MizeError::new().msg("Message was not a map"));
|
||||
}
|
||||
};
|
||||
|
||||
let vec_value = {
|
||||
let mut data = &CborValue::Null;
|
||||
for (key, val) in msg_as_map {
|
||||
if let CborValue::Integer(key_int) = key {
|
||||
// number 2 indicates the id field
|
||||
let two: Integer = 2.into();
|
||||
if key_int == &two {
|
||||
data = val;
|
||||
}
|
||||
}
|
||||
}
|
||||
if data == &CborValue::Null {
|
||||
return Err(MizeError::new().msg("error getting the data value form a msg"));
|
||||
}
|
||||
match data {
|
||||
CborValue::Array(inner) => inner,
|
||||
_ => {
|
||||
return Err(MizeError::new().msg("Id is not a vector"));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let mut vec_string: Vec<String> = Vec::new();
|
||||
for val in vec_value {
|
||||
match val {
|
||||
CborValue::Text(text) => vec_string.push(text.to_owned()),
|
||||
_ => {
|
||||
return Err(MizeError::new()
|
||||
.msg("one in the vec of the id in a msg is not of type Text"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(vec_string)
|
||||
}
|
||||
|
||||
pub fn id(&mut self, instance: &Mize) -> MizeResult<MizeId> {
|
||||
let id_str = self.id_str()?;
|
||||
return instance.new_id(id_str);
|
||||
}
|
||||
|
||||
pub fn data(&mut self) -> MizeResult<ItemData> {
|
||||
// return err, if msg is not a map
|
||||
let msg_as_map = match &self.value {
|
||||
CborValue::Map(val) => val,
|
||||
_ => {
|
||||
return Err(MizeError::new().msg("Message was not a map"));
|
||||
}
|
||||
};
|
||||
|
||||
let data = {
|
||||
let mut tmp_val = &CborValue::Null;
|
||||
let mut found = false;
|
||||
for (key, val) in msg_as_map {
|
||||
if let CborValue::Integer(key_int) = key {
|
||||
// number three indicates the data field
|
||||
let three: Integer = 3.into();
|
||||
if key_int == &three {
|
||||
tmp_val = val;
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return Err(MizeError::new().msg("error getting the data value form a msg"));
|
||||
}
|
||||
tmp_val
|
||||
};
|
||||
|
||||
return Ok(data.to_owned().into_item_data());
|
||||
}
|
||||
}
|
||||
|
||||
// thanks to: https://stackoverflow.com/a/61768916
|
||||
struct DisplayWriter<'a, 'b>(&'a mut fmt::Formatter<'b>);
|
||||
|
||||
impl<'a, 'b> io::Write for DisplayWriter<'a, 'b> {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::result::Result<usize, std::io::Error> {
|
||||
self.0
|
||||
.write_str(&String::from_utf8_lossy(bytes))
|
||||
.map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;
|
||||
|
||||
Ok(bytes.len())
|
||||
}
|
||||
fn flush(&mut self) -> std::result::Result<(), std::io::Error> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for MizeMessage {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let mut err = false;
|
||||
|
||||
match self.to_owned().cmd() {
|
||||
Ok(cmd) => {
|
||||
writeln!(f, "MizeMessage with cmd: {:?}", cmd);
|
||||
}
|
||||
Err(e) => {
|
||||
writeln!(f, "MizeMessage with unparsable cmd");
|
||||
err = true;
|
||||
}
|
||||
}
|
||||
|
||||
match self.to_owned().id_str() {
|
||||
Ok(id) => {
|
||||
let id_str = id.join("/");
|
||||
writeln!(f, "\tid: {:?}", id_str);
|
||||
}
|
||||
Err(e) => {
|
||||
writeln!(f, "\t msg has no id");
|
||||
//err = true;
|
||||
}
|
||||
}
|
||||
|
||||
match self.to_owned().data() {
|
||||
Ok(data) => {
|
||||
let value = data.cbor();
|
||||
write!(f, "\tdata: ");
|
||||
let display_writer = DisplayWriter(f);
|
||||
if let Err(e) = value
|
||||
.serialize(&mut serde_json::Serializer::pretty(display_writer))
|
||||
.map_err(|serde_err| std::fmt::Error)
|
||||
{
|
||||
writeln!(f, "serialize err: {:?}", e);
|
||||
err = true;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
writeln!(f, "\t msg has no data");
|
||||
//err = true;
|
||||
}
|
||||
}
|
||||
|
||||
if err {
|
||||
write!(f, "Full msg: ");
|
||||
let display_writer = DisplayWriter(f);
|
||||
self.value
|
||||
.serialize(&mut serde_json::Serializer::pretty(display_writer))
|
||||
.map_err(|serde_err| std::fmt::Error)
|
||||
.mize_result_msg("serialize error")
|
||||
.inspect_err(|e| {
|
||||
e.clone().log();
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for MizeMessage {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "\nMizeMessage: ");
|
||||
let display_writer = DisplayWriter(f);
|
||||
let value = self.to_owned().value();
|
||||
value
|
||||
.serialize(&mut serde_json::Serializer::pretty(display_writer))
|
||||
.map_err(|serde_err| std::fmt::Error)
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
#![allow(warnings)]
|
||||
|
||||
static PROTO_VERSION: u8 = 1;
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! test_println {
|
||||
($($arg:tt)*) => {
|
||||
|
||||
#[cfg(test)]
|
||||
print!("[[ {} ]] ", <&str as colored::Colorize>::blue("TEST"));
|
||||
|
||||
#[cfg(test)]
|
||||
print!($($arg)*);
|
||||
|
||||
#[cfg(test)]
|
||||
print!("\n");
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! test_print {
|
||||
($($arg:tt)*) => {
|
||||
|
||||
#[cfg(test)]
|
||||
print!("[[ {} ]] ", <&str as colored::Colorize>::blue("TEST"));
|
||||
|
||||
#[cfg(test)]
|
||||
print!($($arg)*);
|
||||
};
|
||||
}
|
||||
|
||||
// the core part has the code that can run on any platform
|
||||
mod core {
|
||||
pub mod config;
|
||||
pub mod error;
|
||||
pub mod id;
|
||||
pub mod instance;
|
||||
pub mod item;
|
||||
pub mod macros;
|
||||
pub mod memstore;
|
||||
pub mod proto;
|
||||
pub mod types;
|
||||
}
|
||||
|
||||
pub use async_trait::async_trait;
|
||||
pub use core::error::MizeError;
|
||||
pub use core::error::MizeResult;
|
||||
pub use core::instance::Mize;
|
||||
pub use core::instance::{
|
||||
DynMizePartGuard, MizePart, MizePartCreate, MizePartCreateGenerated, MizePartGenerated,
|
||||
MizePartGuard,
|
||||
};
|
||||
pub use core::*;
|
||||
pub use mize_macros::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
// platform specific stuff
|
||||
pub mod platform {
|
||||
#[cfg(feature = "target-js")]
|
||||
pub mod js;
|
||||
|
||||
#[cfg(feature = "target-os")]
|
||||
pub mod os;
|
||||
|
||||
pub mod any {
|
||||
//////////// instance_init
|
||||
#[cfg(feature = "target-js")]
|
||||
pub use super::js::wasm_instance_init as instance_init;
|
||||
|
||||
#[cfg(feature = "target-os")]
|
||||
pub use super::os::os_instance_init as instance_init;
|
||||
|
||||
#[cfg(not(any(feature = "target-os", feature = "target-js")))]
|
||||
pub use super::super::instance_init;
|
||||
|
||||
//////////// load_part
|
||||
#[cfg(feature = "target-os")]
|
||||
pub use super::os::load_part;
|
||||
|
||||
#[cfg(feature = "target-js")]
|
||||
pub use super::js::load_part;
|
||||
|
||||
#[cfg(not(any(feature = "target-os", feature = "target-js")))]
|
||||
pub use super::super::load_part;
|
||||
|
||||
//////////// fetch_part
|
||||
#[cfg(feature = "target-os")]
|
||||
pub use super::os::fetch_part;
|
||||
|
||||
#[cfg(feature = "target-js")]
|
||||
pub use super::super::fetch_part;
|
||||
|
||||
#[cfg(not(any(feature = "target-os", feature = "target-js")))]
|
||||
pub use super::super::fetch_part;
|
||||
}
|
||||
}
|
||||
|
||||
// platform specific functions
|
||||
pub fn instance_init(instance: &mut core::instance::Mize) -> MizeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn load_part(
|
||||
instance: &mut core::instance::Mize,
|
||||
name: &str,
|
||||
path: Option<String>,
|
||||
) -> MizeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"tasks": {
|
||||
"dev": "deno run --watch main.ts"
|
||||
},
|
||||
"imports": {
|
||||
"@std/assert": "jsr:@std/assert@1"
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
|
||||
|
||||
export async function init_mize(config) {
|
||||
|
||||
if ("mize" in window) {
|
||||
window.mize.set("self/config", config)
|
||||
return window.mize
|
||||
}
|
||||
|
||||
let config_str = "";
|
||||
if (typeof config == "string") {
|
||||
config_str = config
|
||||
|
||||
} else if (typeof config == "object") {
|
||||
config_str = JSON.stringify(config)
|
||||
|
||||
} else {
|
||||
throw "Error: config passed to init_mize() is not of type 'object' or 'string'"
|
||||
}
|
||||
|
||||
const { new_js_instance } = wasm_bindgen;
|
||||
|
||||
await wasm_bindgen(config.module_dir.mize + "/mize_bg.wasm")
|
||||
|
||||
window.mize = await new_js_instance(config_str)
|
||||
window.mize.mod = {}
|
||||
window.mize.init()
|
||||
|
||||
return window.mize
|
||||
}
|
||||
@@ -1,275 +0,0 @@
|
||||
use crate::id::MizeId;
|
||||
use crate::item::{Item, ItemData};
|
||||
use crate::platform::js::js_sys::Function;
|
||||
use core::convert::From;
|
||||
use core::option::Option;
|
||||
use std::panic;
|
||||
use std::ptr::NonNull;
|
||||
use web_sys::js_sys::{self, eval, Promise};
|
||||
use web_sys::Worker;
|
||||
use web_sys::{WorkerOptions, WorkerType};
|
||||
|
||||
use crate::core::item::IntoItemData;
|
||||
use crate::error::MizeResult;
|
||||
use crate::instance::module::EmptyModule;
|
||||
use crate::Mize;
|
||||
use crate::MizeError;
|
||||
use crate::{mize_err, Module};
|
||||
|
||||
// console_log macro
|
||||
// that can be copied into other files for debugging purposes
|
||||
#[cfg(feature = "target-js")]
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
#[cfg(feature = "target-js")]
|
||||
#[wasm_bindgen]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(js_namespace = console)]
|
||||
fn log(s: &str);
|
||||
}
|
||||
|
||||
#[cfg(feature = "target-js")]
|
||||
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())})
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "target-js"))]
|
||||
macro_rules! console_log {
|
||||
// Note that this is using the `log` function imported above during
|
||||
// `bare_bones`
|
||||
($($t:tt)*) => {};
|
||||
}
|
||||
//end of console_log macro
|
||||
|
||||
#[global_allocator]
|
||||
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
|
||||
|
||||
pub fn wasm_instance_init(mize: &mut Mize) -> MizeResult<()> {
|
||||
console_log!("Hello world from wasm_instance_init!!!!!!!!!!");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn load_module(mize: &mut Mize, name: &str, path: Option<String>) -> MizeResult<()> {
|
||||
console_log!("loading module: {}", name);
|
||||
|
||||
wasm_bindgen_futures::spawn_local(load_module_async(mize.clone(), name.to_owned(), path));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn load_module_async(mut mize: Mize, name: String, path: Option<String>) -> () {
|
||||
let name = name.as_str();
|
||||
let module_url = fetch_module(&mut mize, name).unwrap();
|
||||
let memory = wasm_bindgen::memory();
|
||||
|
||||
let mut empty_module: Box<dyn Module + Send + Sync> = Box::new(EmptyModule {});
|
||||
let mut mize = mize.clone();
|
||||
|
||||
let empty_module_ptr = Box::into_raw(Box::new(empty_module));
|
||||
let empty_module_usize = empty_module_ptr as usize;
|
||||
let mize_usize = Box::into_raw(Box::new(mize)) as usize;
|
||||
|
||||
console_log!("testttttttttttttt in load_module_async...");
|
||||
|
||||
let function_str = format!(
|
||||
r#"
|
||||
const promise = new Promise((resolve, reject) => {{
|
||||
import("{module_url}/mize_module_{name}.js").then( module => {{
|
||||
const wasm_bindgen = module.get_wasm_bindgen();
|
||||
|
||||
const {{ wasm_get_mize_module_mme }} = wasm_bindgen;
|
||||
|
||||
wasm_bindgen("{module_url}/mize_module_{name}_bg.wasm", memory).then( () => {{
|
||||
console.log("empty_module_usize:", empty_module_usize)
|
||||
console.log("mize_usize:", mize_usize)
|
||||
//resolve()
|
||||
resolve(wasm_get_mize_module_mme(empty_module_usize, mize_usize))
|
||||
}})
|
||||
}})
|
||||
}})
|
||||
return promise;
|
||||
"#
|
||||
);
|
||||
|
||||
let function = Function::new_with_args("memory, empty_module_usize, mize_usize", &function_str);
|
||||
|
||||
let ret_value: JsValue = match function.call3(
|
||||
&JsValue::null(),
|
||||
&memory,
|
||||
&empty_module_usize.into(),
|
||||
&mize_usize.into(),
|
||||
) {
|
||||
Ok(val) => val,
|
||||
Err(err) => {
|
||||
console_log!("failed to load the wasm mize module....");
|
||||
console_log!("{:?}", err);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
console_log!("got ret_value: {:?}", ret_value);
|
||||
let ret_promise = Promise::from(ret_value);
|
||||
let ret_result = match wasm_bindgen_futures::JsFuture::from(ret_promise).await {
|
||||
Ok(val) => val,
|
||||
Err(err) => {
|
||||
console_log!("err awaiting ret_promise");
|
||||
console_log!("{:?}", err);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let mut filled_module = unsafe { Box::from_raw(empty_module_ptr) };
|
||||
|
||||
console_log!("before....");
|
||||
//let a = mize.get("0/config");
|
||||
console_log!("after....");
|
||||
|
||||
//filled_module.init(&instance);
|
||||
|
||||
/*
|
||||
console_log!("got ret_result: {:?}", ret_result);
|
||||
let ret_f64 = ret_result.as_f64().unwrap();
|
||||
console_log!("got ret_f64: {:?}", ret_f64);
|
||||
|
||||
let ret_usize = ret_f64.floor() as usize;
|
||||
|
||||
let mut module: Box<dyn Module + Send + Sync> = Box::new(EmptyModule {});
|
||||
|
||||
unsafe {
|
||||
let get_mize_module_fn_ptr = ret_usize as *const fn(&mut Box<dyn Module + Send + Sync>, Instance) -> ();
|
||||
let get_mize_module_fn: fn(&mut Box<dyn Module + Send + Sync>, Instance) -> () = unsafe { std::mem::transmute(get_mize_module_fn_ptr) };
|
||||
get_mize_module_fn(&mut module, instance.clone());
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
pub fn fetch_module(mize: &mut Mize, name: &str) -> MizeResult<String> {
|
||||
let module_name_with_slashes = name.replace(".", "/");
|
||||
if let Ok(module_path) = mize
|
||||
.get(format!(
|
||||
"self/config/module_dir/{}",
|
||||
module_name_with_slashes
|
||||
))?
|
||||
.value_string()
|
||||
{
|
||||
return Ok(module_path);
|
||||
} else {
|
||||
let module_url = mize.get("self/config/module_url")?.value_string()?;
|
||||
return Ok(format!("{}/{}", module_url, module_name_with_slashes));
|
||||
}
|
||||
}
|
||||
|
||||
async fn download_module(mize: &mut Mize, name: &str) -> MizeResult<js_sys::ArrayBuffer> {
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
use web_sys::{Request, RequestInit, RequestMode, Response};
|
||||
|
||||
let opts = RequestInit::new();
|
||||
opts.set_method("GET");
|
||||
opts.set_mode(RequestMode::Cors);
|
||||
|
||||
let url = format!("{}/mize_module_{}_bg.wasm", fetch_module(mize, name)?, name);
|
||||
|
||||
let request = Request::new_with_str_and_init(&url, &opts).unwrap();
|
||||
|
||||
let window = web_sys::window().unwrap();
|
||||
let resp_value = JsFuture::from(window.fetch_with_request(&request))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let resp: Response = resp_value.dyn_into().unwrap();
|
||||
|
||||
let wasm_bytes: js_sys::ArrayBuffer = JsFuture::from(resp.array_buffer().unwrap())
|
||||
.await
|
||||
.unwrap()
|
||||
.dyn_into()
|
||||
.unwrap();
|
||||
|
||||
Ok(wasm_bytes)
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub struct JsMize {
|
||||
inner: NonNull<Mize>,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub struct JsItem {
|
||||
mize: NonNull<Mize>,
|
||||
id: MizeId,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub async fn new_js_instance(config_json_str: String) -> JsMize {
|
||||
panic::set_hook(Box::new(console_error_panic_hook::hook));
|
||||
|
||||
let config = ItemData::from_json(config_json_str).expect("parsing of json config failed");
|
||||
|
||||
let mut mize = Mize::empty().expect("Mize::empty() failed");
|
||||
|
||||
mize.set_blocking("0/config", config)
|
||||
.expect("Failed to set the config at item 0");
|
||||
|
||||
let mut js_instance = JsMize {
|
||||
inner: NonNull::from(Box::leak(Box::new(mize))),
|
||||
};
|
||||
|
||||
return js_instance;
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl JsMize {
|
||||
#[wasm_bindgen]
|
||||
pub unsafe fn init(&mut self) -> MizeResult<()> {
|
||||
self.inner.as_mut().init()
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub unsafe fn set(&mut self, id: String, value: String) -> () {
|
||||
let data = value.into_item_data();
|
||||
console_log!("data in set: {}", data);
|
||||
self.inner.as_mut().set(id, data);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub unsafe fn get_handle(&mut self, id: String) -> MizeResult<JsItem> {
|
||||
let item = self.inner.as_mut().get(id)?;
|
||||
Ok(JsItem {
|
||||
mize: self.inner,
|
||||
id: item.id(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl JsMize {
|
||||
pub fn inner(&mut self) -> &mut Mize {
|
||||
unsafe { self.inner.as_mut() }
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl JsItem {
|
||||
#[wasm_bindgen]
|
||||
pub unsafe fn value_string(&mut self) -> MizeResult<String> {
|
||||
let item = self.mize.as_mut().get(self.id.clone())?;
|
||||
let string = item.value_string()?;
|
||||
Ok(string)
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub unsafe fn as_data_full(&mut self) -> MizeResult<JsValue> {
|
||||
let item = self.mize.as_mut().get(self.id.clone())?;
|
||||
let data_raw = item.as_data_full()?;
|
||||
let jsvalue = serde_wasm_bindgen::to_value(data_raw.cbor())?;
|
||||
Ok(jsvalue)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<MizeError> for JsValue {
|
||||
fn from(value: MizeError) -> Self {
|
||||
let string = format!("{:?}", value);
|
||||
string.into()
|
||||
}
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
use clap::ArgMatches;
|
||||
use core::result::Result::Err;
|
||||
use core::unimplemented;
|
||||
use flume::bounded;
|
||||
use home::home_dir;
|
||||
use mize::mize_err;
|
||||
use std::ffi::OsString;
|
||||
use std::io::Read;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
use tracing::debug;
|
||||
|
||||
use mize::error::{IntoMizeResult, MizeError, MizeResult, MizeResultTrait};
|
||||
use mize::instance::subscription::Subscription;
|
||||
use mize::instance::subscription::Update;
|
||||
use mize::instance::Mize;
|
||||
use mize::item::{IntoItemData, ItemData};
|
||||
use mize::platform::os::config_from_cli_args;
|
||||
use mize::platform::os::fsstore::FileStore;
|
||||
|
||||
pub fn get(sub_matches: &ArgMatches) -> MizeResult<()> {
|
||||
let instance = Mize::with_config(config_from_cli_args(sub_matches)?)?;
|
||||
|
||||
let id = sub_matches
|
||||
.get_one::<String>("id")
|
||||
.ok_or(MizeError::new().msg("No id Argument specified"))?;
|
||||
|
||||
let item = instance.get(id)?;
|
||||
|
||||
let recurse_count = sub_matches.get_count("recurse");
|
||||
|
||||
println!("{}", item.as_data_full()?);
|
||||
return Ok(());
|
||||
|
||||
if recurse_count > 0 {
|
||||
println!("{}", item.id());
|
||||
println!("{}", item.as_data_full()?);
|
||||
} else {
|
||||
println!("{}", item);
|
||||
};
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
pub fn call(sub_matches: &ArgMatches) -> MizeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn create(sub_matches: &ArgMatches) -> MizeResult<()> {
|
||||
let mut instance = Mize::with_config(config_from_cli_args(sub_matches)?)?;
|
||||
|
||||
let item = instance.new_item()?;
|
||||
|
||||
println!("id: {}", item.id());
|
||||
println!("with namespace: {}", item.id().namespace().as_real_string());
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
pub fn is_running(sub_matches: &ArgMatches) -> MizeResult<()> {
|
||||
println!("not implemented");
|
||||
Err(mize_err!("not implemented"))
|
||||
}
|
||||
|
||||
pub fn mount(sub_matches: &ArgMatches) -> MizeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn daemon(sub_matches: &ArgMatches) -> MizeResult<()> {
|
||||
let instance = Mize::with_config(config_from_cli_args(sub_matches)?)?;
|
||||
|
||||
instance.wait();
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
pub fn set(sub_matches: &ArgMatches) -> MizeResult<()> {
|
||||
let instance = Mize::with_config(config_from_cli_args(sub_matches)?)?;
|
||||
|
||||
let id = sub_matches
|
||||
.get_one::<String>("id")
|
||||
.ok_or(MizeError::new().msg("No id Argument specified"))?;
|
||||
|
||||
let value = sub_matches
|
||||
.get_one::<String>("value")
|
||||
.ok_or(MizeError::new().msg("No value Argument specified"))?;
|
||||
|
||||
instance.set_blocking(id, value.into_item_data())?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn show(sub_matches: &ArgMatches) -> MizeResult<()> {
|
||||
let instance = Mize::with_config(config_from_cli_args(sub_matches)?)?;
|
||||
|
||||
let id = sub_matches
|
||||
.get_one::<String>("id")
|
||||
.ok_or(MizeError::new().msg("No id Argument specified"))?;
|
||||
|
||||
let item = instance.get(id)?;
|
||||
|
||||
let (tx, rx) = bounded::<Update>(4);
|
||||
let sub = Subscription::from_sender(tx);
|
||||
instance.sub(id, sub)?;
|
||||
|
||||
println!("item: {}", item.as_data_full()?);
|
||||
|
||||
for update in rx {
|
||||
println!("####### GOT UPDATE #######");
|
||||
println!("item: {}", update.new_item()?.as_data_full()?);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn stop(sub_matches: &ArgMatches) -> MizeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn gui(sub_matches: &ArgMatches) -> MizeResult<()> {
|
||||
let mut instance = Mize::with_config(config_from_cli_args(sub_matches)?)?;
|
||||
|
||||
instance.load_part("mme")?;
|
||||
|
||||
instance.wait();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn format_cbor(sub_matches: &ArgMatches) -> MizeResult<()> {
|
||||
let mut input: Vec<u8> = Vec::new();
|
||||
let stdin = std::io::stdin();
|
||||
let mut handle = stdin.lock();
|
||||
//handle.read_to_end(&mut input);
|
||||
|
||||
let cbor_data = ciborium::from_reader(handle)?;
|
||||
let item_data = ItemData::from_cbor(cbor_data);
|
||||
|
||||
println!("{}", item_data);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn run_from_module(cmd: &str, sub_matches: &ArgMatches) -> MizeResult<()> {
|
||||
let default = OsString::default();
|
||||
let mut sub_cmd_line: Vec<OsString> = sub_matches
|
||||
.get_many::<OsString>("")
|
||||
.unwrap()
|
||||
.map(|e| e.to_owned())
|
||||
.collect();
|
||||
sub_cmd_line.insert(0, OsString::from_str(cmd)?);
|
||||
|
||||
let mut instance = Mize::with_config(config_from_cli_args(sub_matches)?)?;
|
||||
|
||||
debug!("loading module '{}'", cmd);
|
||||
instance.load_part(cmd)?;
|
||||
|
||||
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(())
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
use ciborium::Value as CborValue;
|
||||
use std::fs;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use sysinfo::{Pid, ProcessRefreshKind, RefreshKind, System};
|
||||
use tracing::debug;
|
||||
|
||||
use crate::core::id::MizeId;
|
||||
use crate::core::item::{Item, ItemData};
|
||||
use crate::error::{IntoMizeResult, MizeError, MizeResult};
|
||||
use crate::instance::store::IdIter;
|
||||
use crate::instance::{self, Mize};
|
||||
use crate::item::get_raw_from_cbor;
|
||||
use crate::item::IntoItemData;
|
||||
use crate::memstore::MemStore;
|
||||
use crate::{core::instance::store::Store, mize_err};
|
||||
use tokio::net::UnixStream;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FileStore {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl FileStore {
|
||||
pub fn new(path_str: &str) -> MizeResult<FileStore> {
|
||||
let path = Path::new(path_str);
|
||||
|
||||
// create that path if it does not exist
|
||||
fs::create_dir_all(Path::new(&path).join("store"))?;
|
||||
|
||||
// check for valid pid file
|
||||
/*
|
||||
if let Some(pid) = valid_pid_file(path)? {
|
||||
// store already opened
|
||||
return Err(mize_err!("MizeStore at path {} is already opened by process with pid {}", path.display(), pid));
|
||||
|
||||
} else {
|
||||
// write our own pid file
|
||||
fs::remove_file(path.join("pid"));
|
||||
let pid = std::process::id();
|
||||
let mut file = OpenOptions::new().write(true).create(true).open(path.join("pid"))?;
|
||||
write!(file, "{}", pid)?;
|
||||
}
|
||||
*/
|
||||
|
||||
// init the store
|
||||
if !path.join("next_id").exists() {
|
||||
fs::write(path.join("next_id"), "1");
|
||||
}
|
||||
|
||||
Ok(FileStore {
|
||||
path: Path::new(&path).to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn store_is_opened(store_path: String, instance: &mut Mize) -> MizeResult<bool> {
|
||||
// this was the old method....
|
||||
//let valid_pid_file = valid_pid_file(Path::new(&store_path))?.is_some();
|
||||
|
||||
let can_connect_to_sock = match instance
|
||||
.spawn_async_blocking("con_test_thread", try_connect_to_sock(store_path.clone()))
|
||||
{
|
||||
Ok(_) => true,
|
||||
Err(_) => false,
|
||||
};
|
||||
debug!(
|
||||
"MiZe Store at {} opened: {}",
|
||||
store_path, can_connect_to_sock
|
||||
);
|
||||
Ok(can_connect_to_sock)
|
||||
}
|
||||
}
|
||||
|
||||
async fn try_connect_to_sock(store_path: String) -> MizeResult<()> {
|
||||
match UnixStream::connect(PathBuf::from(store_path).join("sock")).await {
|
||||
Err(_) => Err(mize_err!("")),
|
||||
Ok(_) => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
impl Store for FileStore {
|
||||
fn new_id(&self) -> MizeResult<String> {
|
||||
let mut next_id: u64 =
|
||||
String::from_utf8(fs::read(self.path.join("next_id")).mize_result_msg(format!(
|
||||
"could not read next_id at '{}'",
|
||||
self.path.display()
|
||||
))?)?
|
||||
.parse()
|
||||
.mize_result_msg(format!(
|
||||
"could not parse next_id at '{}' to u64",
|
||||
self.path.display()
|
||||
))?;
|
||||
|
||||
let id_string = format!("{}", next_id);
|
||||
|
||||
next_id += 1;
|
||||
|
||||
fs::write(self.path.join("next_id"), format!("{}", next_id))?;
|
||||
|
||||
return Ok(id_string);
|
||||
}
|
||||
|
||||
fn set(&self, id: MizeId, data: ItemData) -> MizeResult<()> {
|
||||
let path = self
|
||||
.path
|
||||
.join("store")
|
||||
.join(id.namespace_str())
|
||||
.join(id.store_part());
|
||||
fs::create_dir_all(self.path.join("store").join(id.namespace_str()))?;
|
||||
|
||||
let file = OpenOptions::new().write(true).create(true).open(path)?;
|
||||
|
||||
ciborium::into_writer(data.cbor(), file)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_links(&self, item: Item) -> MizeResult<Vec<MizeId>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
fn get_backlinks(&self, item: Item) -> MizeResult<Vec<MizeId>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
fn get_value_raw(&self, id: MizeId) -> MizeResult<Vec<u8>> {
|
||||
let path = self
|
||||
.path
|
||||
.join("store")
|
||||
.join(id.namespace_str())
|
||||
.join(id.store_part());
|
||||
|
||||
let file = OpenOptions::new().read(true).create(true).open(path)?;
|
||||
|
||||
let cbor_val: CborValue = ciborium::from_reader(file).mize_result_msg(format!(
|
||||
"could not read file '{}' from FileStore",
|
||||
self.path.join("store").join(id.store_part()).display()
|
||||
))?;
|
||||
|
||||
let path = id.path();
|
||||
let mut id_iter = path.iter();
|
||||
id_iter.next();
|
||||
let id_without_first = id_iter.collect();
|
||||
|
||||
Ok(get_raw_from_cbor(&cbor_val, id_without_first)?.to_owned())
|
||||
}
|
||||
|
||||
fn get_value_data_full(&self, id: MizeId) -> MizeResult<ItemData> {
|
||||
let file_path = self
|
||||
.path
|
||||
.join("store")
|
||||
.join(id.namespace_str())
|
||||
.join(id.store_part());
|
||||
if !file_path.exists() {}
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.open(file_path.clone())
|
||||
.map_err(|e| {
|
||||
mize_err!(
|
||||
"fsstoree: Unable to open '{}', err: {}",
|
||||
file_path.display(),
|
||||
e
|
||||
)
|
||||
})?;
|
||||
|
||||
let cbor_value: CborValue = ciborium::from_reader(file).mize_result_msg(format!(
|
||||
"could not read file '{}' from FileStore",
|
||||
self.path.join("store").join(id.store_part()).display()
|
||||
))?;
|
||||
let data: ItemData = cbor_value.into_item_data();
|
||||
|
||||
let tmp = id.path();
|
||||
let mut path_iter = tmp.into_iter();
|
||||
path_iter.next();
|
||||
let new_path: Vec<String> = path_iter.map(|v| v.to_owned()).collect();
|
||||
//println!("data: {}", data);
|
||||
//println!("new_path: {:?}", new_path);
|
||||
let ret_data = data.get_path(new_path)?;
|
||||
//println!("ret_data: {}", ret_data);
|
||||
|
||||
return Ok(ret_data);
|
||||
}
|
||||
fn id_iter(&self) -> MizeResult<IdIter> {
|
||||
todo!()
|
||||
}
|
||||
fn next_id(&self, prev_id: &str) -> MizeResult<Option<String>> {
|
||||
todo!()
|
||||
}
|
||||
fn first_id(&self) -> MizeResult<String> {
|
||||
Ok("0".to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_pid_file(path: &Path) -> MizeResult<Option<u32>> {
|
||||
let pid_file_path = path.join("pid");
|
||||
|
||||
// if the pid file does not exist, there is no pid...
|
||||
if !pid_file_path.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// read pid file
|
||||
let pid: u32 = String::from_utf8(fs::read(&pid_file_path).mize_result_msg(format!(
|
||||
"Could not read contents of pid file at '{}'",
|
||||
pid_file_path.display()
|
||||
))?)?
|
||||
.parse()
|
||||
.mize_result_msg(format!(
|
||||
"Could not parse contents of pid file at '{}' to u32",
|
||||
pid_file_path.display()
|
||||
))?;
|
||||
|
||||
if Path::new("/proc").join(format!("{}", pid)).exists() {
|
||||
return Ok(Some(pid));
|
||||
} else {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
@@ -1,363 +0,0 @@
|
||||
use clap::{crate_version, Arg, Command};
|
||||
use clap::{ArgAction, ArgMatches};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use colored::Colorize;
|
||||
use core::fmt;
|
||||
use std::env;
|
||||
use std::fmt::Write;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::level_filters::LevelFilter;
|
||||
use tracing::Event;
|
||||
use tracing::{debug, error, info, trace, warn};
|
||||
use tracing::{field::Visit, Id, Subscriber};
|
||||
use tracing::{span_enabled, Instrument, Level};
|
||||
use tracing_core::Field;
|
||||
use tracing_subscriber::filter::EnvFilter;
|
||||
use tracing_subscriber::fmt::format;
|
||||
use tracing_subscriber::fmt::FmtContext;
|
||||
use tracing_subscriber::fmt::FormatEvent;
|
||||
use tracing_subscriber::fmt::FormatFields;
|
||||
use tracing_subscriber::fmt::FormattedFields;
|
||||
use tracing_subscriber::registry::LookupSpan;
|
||||
|
||||
use crate::id::MizeId;
|
||||
use crate::item::ItemData;
|
||||
use crate::MizeError;
|
||||
use crate::MizeResult;
|
||||
|
||||
static DEFAULT_LOG_LEVEL: LevelFilter = LevelFilter::WARN;
|
||||
|
||||
pub fn init_logger(cli_matches: &ArgMatches) {
|
||||
println!("init_logger called");
|
||||
// to save log messages, before the logger is setup
|
||||
let mut log_messages: Vec<(Level, String)> = Vec::new();
|
||||
|
||||
log_messages.push((Level::INFO, "Starting Mize".to_owned()));
|
||||
|
||||
// builder with DEFAULT_LOG_LEVEL
|
||||
let mut builder = tracing_subscriber::fmt::Subscriber::builder();
|
||||
|
||||
// set loglevel
|
||||
let mut log_level = DEFAULT_LOG_LEVEL;
|
||||
log_messages.push((
|
||||
Level::TRACE,
|
||||
format!(
|
||||
"set log level from DEFAULT_LOG_LEVEL to {}",
|
||||
DEFAULT_LOG_LEVEL
|
||||
),
|
||||
));
|
||||
|
||||
// check env RUST_LOG
|
||||
let mut val_rust_log = level_from_env("RUST_LOG", log_level);
|
||||
if let Some(level_rust_log) = val_rust_log.0 {
|
||||
log_level = level_rust_log;
|
||||
log_messages.push((
|
||||
Level::TRACE,
|
||||
format!(
|
||||
"set log level from the Variable RUST_LOG to {}",
|
||||
level_rust_log
|
||||
),
|
||||
));
|
||||
}
|
||||
log_messages.append(&mut val_rust_log.1);
|
||||
|
||||
// check env LOG
|
||||
let mut val_mize_log = level_from_env("LOG", log_level);
|
||||
if let Some(level_mize_log) = val_mize_log.0 {
|
||||
println!("set log level from the Variable LOG to {}", level_mize_log);
|
||||
log_level = level_mize_log;
|
||||
log_messages.push((
|
||||
Level::TRACE,
|
||||
format!(
|
||||
"set log level from the Variable MIZE_LOG to {}",
|
||||
level_mize_log
|
||||
),
|
||||
));
|
||||
}
|
||||
log_messages.append(&mut val_mize_log.1);
|
||||
|
||||
// check env MIZE_LOG
|
||||
let mut val_mize_log = level_from_env("MIZE_LOG", log_level);
|
||||
if let Some(level_mize_log) = val_mize_log.0 {
|
||||
log_level = level_mize_log;
|
||||
log_messages.push((
|
||||
Level::TRACE,
|
||||
format!(
|
||||
"set log level from the Variable MIZE_LOG to {}",
|
||||
level_mize_log
|
||||
),
|
||||
));
|
||||
}
|
||||
log_messages.append(&mut val_mize_log.1);
|
||||
|
||||
// check -vvvvv flags
|
||||
let v_flag_count = cli_matches.get_count("verbose");
|
||||
if v_flag_count > 0 {
|
||||
let default_log_level_as_num = match DEFAULT_LOG_LEVEL {
|
||||
LevelFilter::OFF => 0,
|
||||
LevelFilter::ERROR => 1,
|
||||
LevelFilter::WARN => 2,
|
||||
LevelFilter::INFO => 3,
|
||||
LevelFilter::DEBUG => 4,
|
||||
LevelFilter::TRACE => 5,
|
||||
};
|
||||
let new_log_level_num = default_log_level_as_num + v_flag_count;
|
||||
log_level = match new_log_level_num {
|
||||
0 => LevelFilter::OFF,
|
||||
1 => LevelFilter::ERROR,
|
||||
2 => LevelFilter::WARN,
|
||||
3 => LevelFilter::INFO,
|
||||
4 => LevelFilter::DEBUG,
|
||||
5 => LevelFilter::TRACE,
|
||||
_ => {
|
||||
log_messages.push((
|
||||
Level::TRACE,
|
||||
format!(
|
||||
"the number of verbose (-v) flags passed ({}) exeeds the maximumg log_level",
|
||||
v_flag_count
|
||||
),
|
||||
));
|
||||
LevelFilter::TRACE
|
||||
}
|
||||
};
|
||||
log_messages.push((
|
||||
Level::TRACE,
|
||||
format!("set log level from the verbose flags to {}", log_level),
|
||||
));
|
||||
}
|
||||
|
||||
// check --log-level arg
|
||||
if let Some(log_level_arg_string) = cli_matches.get_one::<String>("log-level") {
|
||||
let log_level_from_arg = match log_level_arg_string.to_owned().to_lowercase().as_str() {
|
||||
"none" => LevelFilter::OFF,
|
||||
"trace" => LevelFilter::TRACE,
|
||||
"debug" => LevelFilter::DEBUG,
|
||||
"info" => LevelFilter::INFO,
|
||||
"warn" => LevelFilter::WARN,
|
||||
"error" => LevelFilter::ERROR,
|
||||
_ => {
|
||||
log_messages.push((Level::WARN, format!(
|
||||
"The argument to --log-level \"{}\" is not a valid log-level. loglevel stays at: {}"
|
||||
, log_level_arg_string
|
||||
, log_level
|
||||
)));
|
||||
log_level
|
||||
}
|
||||
};
|
||||
log_level = log_level_from_arg;
|
||||
log_messages.push((
|
||||
Level::TRACE,
|
||||
format!(
|
||||
"set log level from the --log-level arg to {}",
|
||||
log_level_from_arg
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
// check --silent flag
|
||||
if cli_matches.get_flag("silent") {
|
||||
if log_level != DEFAULT_LOG_LEVEL {
|
||||
log_messages.push((Level::WARN, format!(
|
||||
"The loglevel was set by some method (it's not the DEFAULT_LOG_LEVEL) and is now overwritten by the --siltne to be OFF"
|
||||
)))
|
||||
}
|
||||
log_level = LevelFilter::OFF;
|
||||
}
|
||||
|
||||
// actually set the log_level on the builder
|
||||
log_messages.push((Level::INFO, format!("loglevel is now {}", log_level)));
|
||||
|
||||
// filter loging
|
||||
//let mut my_env_filter = tracing_subscriber::filter::EnvFilter::new("")
|
||||
//.add_directive("[get_raw_from_cbor]=debug".parse().expect("error parsing log directive"))
|
||||
//.add_directive("[MemStore::get_value_raw]=trace".parse().expect("error parsing log directive"))
|
||||
//.add_directive("trace".parse().unwrap())
|
||||
//.add_directive("[get_raw_from_cbor]=debug".parse().expect("error parsing log directive"))
|
||||
//;
|
||||
|
||||
//MinimalTracer::register();
|
||||
|
||||
println!("log_level: {}", log_level);
|
||||
let field_formatter = tracing_subscriber::fmt::format::debug_fn(|writer, field, value| {
|
||||
if field.name() == "message" {
|
||||
write!(writer, "{:?}", value)?;
|
||||
} else {
|
||||
write!(writer, "{}={:?}", field, value)?;
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
builder
|
||||
//.with_env_filter(my_env_filter)
|
||||
.without_time()
|
||||
.event_format(MyFormatter)
|
||||
.fmt_fields(field_formatter)
|
||||
.with_max_level(log_level)
|
||||
.init();
|
||||
|
||||
// write out all log messages from log_messages
|
||||
for (level, msg) in log_messages {
|
||||
match level {
|
||||
Level::ERROR => error!("{}", msg),
|
||||
Level::WARN => warn!("{}", msg),
|
||||
Level::INFO => info!("{}", msg),
|
||||
Level::DEBUG => debug!("{}", msg),
|
||||
Level::TRACE => trace!("{}", msg),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn level_from_env(
|
||||
var_name: &str,
|
||||
log_level: LevelFilter,
|
||||
) -> (Option<LevelFilter>, Vec<(Level, String)>) {
|
||||
let mut log_messages: Vec<(Level, String)> = Vec::new();
|
||||
let var_value = env::var(var_name);
|
||||
println!("checking env var: {}={:?}", var_name, var_value);
|
||||
|
||||
match var_value {
|
||||
Ok(val) => {
|
||||
// set loglevel acording to RUST_LOG
|
||||
let level = match val.to_lowercase().as_str() {
|
||||
"none" => LevelFilter::OFF,
|
||||
"trace" => LevelFilter::TRACE,
|
||||
"debug" => LevelFilter::DEBUG,
|
||||
"info" => LevelFilter::INFO,
|
||||
"warn" => LevelFilter::WARN,
|
||||
"error" => LevelFilter::ERROR,
|
||||
_ => {
|
||||
log_messages.push((Level::WARN, format!(
|
||||
"The value of Environment Variable {}: \"{}\" is not a valid log-level. loglevel stays at: {}"
|
||||
, var_name
|
||||
, val
|
||||
, log_level
|
||||
)));
|
||||
log_level
|
||||
}
|
||||
};
|
||||
return (Some(level), log_messages);
|
||||
}
|
||||
Err(env::VarError::NotPresent) => {}
|
||||
Err(env::VarError::NotUnicode(os_string)) => {
|
||||
let os_string_as_hex: String = os_string
|
||||
.clone()
|
||||
.into_encoded_bytes()
|
||||
.iter()
|
||||
.map(|b| format!("{:02x}", b).to_string())
|
||||
.collect::<Vec<String>>()
|
||||
.join("");
|
||||
log_messages.push((Level::DEBUG, format!(
|
||||
"value of Environment Variable {} was not a unicode valid string. Therefore ignoring it.
|
||||
\n value with replacement char U+FFFD: {}
|
||||
\n the WTF-8 raw bytes as hex: {}"
|
||||
, var_name
|
||||
, os_string.to_string_lossy(), os_string_as_hex
|
||||
)));
|
||||
}
|
||||
};
|
||||
return (None, log_messages);
|
||||
}
|
||||
|
||||
struct MyFormatter;
|
||||
|
||||
impl<S, N> FormatEvent<S, N> for MyFormatter
|
||||
where
|
||||
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
|
||||
N: for<'a> FormatFields<'a> + 'static,
|
||||
{
|
||||
fn format_event(
|
||||
&self,
|
||||
ctx: &FmtContext<'_, S, N>,
|
||||
mut writer: format::Writer<'_>,
|
||||
event: &Event<'_>,
|
||||
) -> fmt::Result {
|
||||
// Format values from the event's's metadata:
|
||||
|
||||
let metadata = event.metadata();
|
||||
|
||||
// set format
|
||||
//builder.format(|buf, record| match record.level() {});
|
||||
|
||||
let level_str = match metadata.level() {
|
||||
&Level::TRACE => format!("[ {} ]", "TRACE".yellow()),
|
||||
&Level::DEBUG => format!("[ {} ]", "DEBUG".green()),
|
||||
&Level::INFO => format!("[ {} ]", "INFO".blue()),
|
||||
&Level::WARN => format!("[ {} ]", "WARN".truecolor(245, 164, 66)),
|
||||
&Level::ERROR => format!("[ {} ]", "ERROR".red()),
|
||||
};
|
||||
|
||||
// with target
|
||||
// write!(&mut writer, "{} {}: ", level_str, metadata.target())?;
|
||||
|
||||
write!(&mut writer, "{} ", level_str)?;
|
||||
|
||||
// Format all the spans in the event's span context.
|
||||
if let Some(scope) = ctx.event_scope() {
|
||||
for span in scope.from_root() {
|
||||
write!(writer, "{}", span.name())?;
|
||||
|
||||
// `FormattedFields` is a formatted representation of the span's
|
||||
// fields, which is stored in its extensions by the `fmt` layer's
|
||||
// `new_span` method. The fields will have been formatted
|
||||
// by the same field formatter that's provided to the event
|
||||
// formatter in the `FmtContext`.
|
||||
let ext = span.extensions();
|
||||
let fields = &ext
|
||||
.get::<FormattedFields<N>>()
|
||||
.expect("will never be `None`");
|
||||
|
||||
// Skip formatting the fields if the span had no fields.
|
||||
if !fields.is_empty() {
|
||||
//write!(writer, "{{{}}}", fields)?;
|
||||
}
|
||||
write!(writer, ": ")?;
|
||||
}
|
||||
}
|
||||
|
||||
// Write fields on the event
|
||||
ctx.field_format().format_fields(writer.by_ref(), event)?;
|
||||
|
||||
writeln!(writer);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// thanks: https://stackoverflow.com/a/75546824
|
||||
pub struct StringVisitor<'a> {
|
||||
string: &'a mut String,
|
||||
}
|
||||
impl<'a> StringVisitor<'a> {
|
||||
pub(crate) fn new(string: &'a mut String) -> Self {
|
||||
StringVisitor { string }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Visit for StringVisitor<'a> {
|
||||
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
|
||||
if field.name() == "message" {
|
||||
write!(self.string, "{value:?} ").unwrap();
|
||||
} else {
|
||||
write!(self.string, "{} = {:?}; ", field.name(), value).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct LogFilter {
|
||||
target: Option<String>,
|
||||
level: Option<Level>,
|
||||
}
|
||||
|
||||
fn string_to_level(string: &str) -> Option<Level> {
|
||||
match string.to_lowercase().as_str() {
|
||||
"info" => Some(Level::INFO),
|
||||
"debug" => Some(Level::DEBUG),
|
||||
"warn" | "warning" => Some(Level::WARN),
|
||||
"trace" => Some(Level::TRACE),
|
||||
"error" => Some(Level::ERROR),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
#![allow(warnings)]
|
||||
|
||||
use clap::builder::OsStr;
|
||||
use clap::{crate_version, Arg, Command};
|
||||
use clap::{ArgAction, ArgMatches};
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
use std::process::exit;
|
||||
|
||||
use colored::Colorize;
|
||||
use mize::error::{MizeError, MizeResult};
|
||||
use mize::item::ItemData;
|
||||
use mize::platform::os::logging::init_logger;
|
||||
use mize::{instance, Mize};
|
||||
use std::env;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{mpsc, Mutex};
|
||||
use tracing::level_filters::LevelFilter;
|
||||
use tracing::Level;
|
||||
use tracing_subscriber::filter::EnvFilter;
|
||||
use tracing_subscriber::fmt::Subscriber;
|
||||
|
||||
use tracing::{debug, error, info, trace, warn};
|
||||
|
||||
mod cli;
|
||||
|
||||
static APPNAME: &str = "mize";
|
||||
|
||||
fn main() {
|
||||
// welcome to the mize source code
|
||||
// this is the main entry point for platforms with an os (eg: Linux, MacOS, Windows, BSD, ...)
|
||||
// Also let's try to make the most best documented code ever. (eventually) so it's fun to work on
|
||||
|
||||
let cli_matches = cli_matches();
|
||||
|
||||
init_logger(&cli_matches);
|
||||
|
||||
// match command
|
||||
let result = match cli_matches.subcommand() {
|
||||
// mi daemon
|
||||
Some(("daemon", sub_matches)) => cli::daemon(sub_matches),
|
||||
|
||||
Some(("is-running", sub_matches)) => cli::is_running(sub_matches),
|
||||
|
||||
// mi serve
|
||||
Some(("serve", sub_matches)) => cli::stop(sub_matches),
|
||||
|
||||
// mi mount
|
||||
Some(("mount", sub_matches)) => cli::mount(sub_matches),
|
||||
|
||||
// mi get
|
||||
Some(("get", sub_matches)) => cli::get(sub_matches),
|
||||
|
||||
// mi set
|
||||
Some(("set", sub_matches)) => cli::set(sub_matches),
|
||||
|
||||
// mi show
|
||||
Some(("show", sub_matches)) => cli::show(sub_matches),
|
||||
|
||||
// mi call
|
||||
Some(("call", sub_matches)) => cli::call(sub_matches),
|
||||
|
||||
// mi create
|
||||
Some(("create", sub_matches)) => cli::create(sub_matches),
|
||||
|
||||
// mi gui
|
||||
Some(("gui", sub_matches)) => cli::gui(sub_matches),
|
||||
|
||||
// mi format-cbor
|
||||
Some(("format-cbor", sub_matches)) => cli::format_cbor(sub_matches),
|
||||
|
||||
// some unknown command passed
|
||||
Some((cmd, sub_matches)) => cli::run_from_module(cmd, sub_matches),
|
||||
|
||||
None => Err(MizeError::new()
|
||||
.msg("No subcommand was passed. use --help to list availavle comamnds.")),
|
||||
};
|
||||
|
||||
if let Err(err) = result {
|
||||
err.log();
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn cli_matches() -> clap::ArgMatches {
|
||||
let main = Command::new(APPNAME)
|
||||
.version(crate_version!())
|
||||
.author("Sebastian Moser")
|
||||
.about("The MiZe Command line tool")
|
||||
.allow_external_subcommands(true)
|
||||
.arg(
|
||||
Arg::new("verbose")
|
||||
.long("verbose")
|
||||
.short('v')
|
||||
.action(ArgAction::Count)
|
||||
.global(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("log-level")
|
||||
.long("log-level")
|
||||
.value_name("LOGLEVEL")
|
||||
.help("set the log-level to one of OFF, ERROR, WARN, INFO, DEBUG, TRACE")
|
||||
.global(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("silent")
|
||||
.long("silent")
|
||||
.action(ArgAction::SetTrue)
|
||||
.help("set the log-level to OFF")
|
||||
.global(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("folder")
|
||||
.short('f')
|
||||
.long("folder")
|
||||
.help("The folder the Instance stores all it's data and the socket for connections")
|
||||
.global(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("config")
|
||||
.short('c')
|
||||
.long("config")
|
||||
.help("overwrite config options")
|
||||
.global(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("config-file")
|
||||
.long("config-file")
|
||||
.help("specify a config file")
|
||||
.global(true),
|
||||
)
|
||||
.subcommand(Command::new("daemon").about("Run a MiZe Instance as a daemon"))
|
||||
.subcommand(Command::new("stop").about("Stop a MiZe Instance"))
|
||||
.subcommand(Command::new("mount").aliases(["m"]))
|
||||
.subcommand(
|
||||
Command::new("get")
|
||||
.aliases(["g"])
|
||||
.arg(Arg::new("id").help("The id or path to get"))
|
||||
.arg(Arg::new("recurse").short('r').action(ArgAction::Count)),
|
||||
)
|
||||
.subcommand(
|
||||
Command::new("set")
|
||||
.aliases(["s"])
|
||||
.arg(Arg::new("id").help("The id or path to set"))
|
||||
.arg(Arg::new("value").help("The value to set the path to")),
|
||||
)
|
||||
.subcommand(
|
||||
Command::new("show")
|
||||
.aliases(["so"])
|
||||
.arg(Arg::new("id").help("The id or path to sub to and show")),
|
||||
)
|
||||
.subcommand(Command::new("call").aliases(["c"]))
|
||||
.subcommand(Command::new("create").aliases(["cr"]))
|
||||
.subcommand(Command::new("is-running").aliases(["isr"]))
|
||||
.subcommand(Command::new("gui"))
|
||||
.subcommand(Command::new("format-cbor"))
|
||||
.arg_required_else_help(true);
|
||||
|
||||
return main.get_matches();
|
||||
}
|
||||
@@ -1,369 +0,0 @@
|
||||
use ciborium::Value as CborValue;
|
||||
use clap::ArgMatches;
|
||||
use flate2::bufread::GzDecoder;
|
||||
use serde::Deserialize;
|
||||
use sha2::{Digest, Sha256, Sha512};
|
||||
use std::env::VarError;
|
||||
use std::fs;
|
||||
use std::fs::File;
|
||||
use std::io::copy;
|
||||
use std::path::{Path, PathBuf};
|
||||
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::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, MizePart};
|
||||
|
||||
use self::fsstore::FileStore;
|
||||
|
||||
pub mod fsstore;
|
||||
pub mod logging;
|
||||
|
||||
#[cfg(target_family = "unix")]
|
||||
mod unix_socket;
|
||||
|
||||
#[cfg(target_family = "unix")]
|
||||
use crate::platform::os::unix_socket::UnixListener;
|
||||
//mod web;
|
||||
|
||||
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.
|
||||
|
||||
////// 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 data = data_from_string(config_string)?;
|
||||
set_config_from_data(mize, data)?;
|
||||
}
|
||||
Err(var_err) => match var_err {
|
||||
VarError::NotPresent => {
|
||||
debug!("env var MIZE_CONFIG NOT present")
|
||||
}
|
||||
VarError::NotUnicode(_) => {
|
||||
warn!("env var MIZE_CONFIG is not Unicode, so not reading it")
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
////// if a config.store_path is set, upgrade to the filestore there
|
||||
let mut test = mize.get("0")?.as_data_full()?;
|
||||
let mut store_path = match mize.get("self/config/store")?.value_string() {
|
||||
Ok(path) => path,
|
||||
Err(e) => {
|
||||
// the default store_path: $HOME/.mize
|
||||
let home_dir = if let Some(dir) = std::env::home_dir() {
|
||||
dir
|
||||
} else {
|
||||
return Err(mize_err!(
|
||||
"could not get home_dir and store_path is not set in the config"
|
||||
));
|
||||
};
|
||||
|
||||
let store_path_buff = home_dir.join(".mize");
|
||||
let store_path = store_path_buff.display().to_string();
|
||||
|
||||
mize.set_blocking(
|
||||
"self/config/store_path",
|
||||
store_path.clone().into_item_data(),
|
||||
)?;
|
||||
|
||||
let store_path = mize.get("self/config/store_path")?.value_string()?;
|
||||
|
||||
println!("store_path: {}", store_path);
|
||||
|
||||
store_path
|
||||
}
|
||||
};
|
||||
|
||||
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
|
||||
|
||||
#[cfg(target_family = "unix")]
|
||||
{
|
||||
info!("CONNECTING");
|
||||
use crate::platform::os::unix_socket;
|
||||
unix_socket::connect(mize, store_path.into())?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
#[cfg(target_family = "windows")]
|
||||
{
|
||||
error!("CONNECTING... would connect, but that is not implemented on windows yet");
|
||||
}
|
||||
} else {
|
||||
// else open it ourselves
|
||||
let file_store = FileStore::new(store_path.as_str())?;
|
||||
mize.migrate_to_store(Box::new(file_store))?;
|
||||
|
||||
let path = Path::new(&store_path).to_owned();
|
||||
|
||||
#[cfg(target_family = "unix")]
|
||||
{
|
||||
mize.add_listener(UnixListener::new(path)?)?;
|
||||
}
|
||||
|
||||
#[cfg(target_family = "windows")]
|
||||
{
|
||||
warn!("would add a Listener on a local socket, but that is not yet implemented for windows");
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
let metadata = fs::metadata(path)?;
|
||||
|
||||
let modified = metadata.modified()?;
|
||||
|
||||
let duration = modified.duration_since(UNIX_EPOCH)?;
|
||||
|
||||
Ok(duration.as_secs())
|
||||
}
|
||||
|
||||
pub fn get_part_hash(
|
||||
mize: &mut Mize,
|
||||
name: &str,
|
||||
mut options: ItemData,
|
||||
) -> MizeResult<(String, String)> {
|
||||
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);
|
||||
let mut name_parts = name.split(".");
|
||||
if name_parts
|
||||
.next()
|
||||
.ok_or(mize_err!("no 0th element in the modName"))?
|
||||
== "cross"
|
||||
{
|
||||
let system = name_parts
|
||||
.next()
|
||||
.ok_or(mize_err!("no 1th element in the modName"))?;
|
||||
let mod_name: String = name_parts.collect();
|
||||
println!("get_module_hash: mod_name: {}", mod_name);
|
||||
if mod_name == "" {
|
||||
return Err(mize_err!("no 2nd element in the modName"));
|
||||
}
|
||||
|
||||
selector_data.set_path("system", system)?;
|
||||
selector_data.set_path("modName", mod_name)?;
|
||||
} else {
|
||||
selector_data.set_path("modName", name)?;
|
||||
}
|
||||
|
||||
selector_data.merge(options);
|
||||
|
||||
// important to produce the same hash for the sama selector data
|
||||
selector_data.sort_keys();
|
||||
|
||||
let selector_str = selector_data.to_json()?;
|
||||
|
||||
let mut hasher = Sha256::new();
|
||||
|
||||
hasher.update(selector_str.clone().as_bytes());
|
||||
|
||||
let result = hasher.finalize();
|
||||
|
||||
let mut hex: String = result
|
||||
.iter()
|
||||
.map(|b| format!("{:02x}", b).to_string())
|
||||
.collect::<Vec<String>>()
|
||||
.join("");
|
||||
|
||||
hex.truncate(32);
|
||||
|
||||
return Ok((hex, selector_str));
|
||||
}
|
||||
|
||||
fn download_part(
|
||||
mize: &mut Mize,
|
||||
store_path: &str,
|
||||
part_url: &str,
|
||||
part_hash: &str,
|
||||
part_name: &str,
|
||||
part_selector: &str,
|
||||
) -> MizeResult<()> {
|
||||
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 part '{}' with hash: {}", part_name, part_hash);
|
||||
|
||||
let response = http_req::request::get(
|
||||
format!(
|
||||
"http://{}/mize/dist/{}-{}.tar.gz",
|
||||
part_url, part_hash, part_name
|
||||
),
|
||||
&mut tmp_gz_file,
|
||||
)?;
|
||||
|
||||
let code = response.status_code();
|
||||
if code != 200.into() {
|
||||
return Err(mize_err!(
|
||||
"failed to get part '{}' with hash '{}' and selector: {}",
|
||||
part_name,
|
||||
part_hash,
|
||||
part_selector
|
||||
)
|
||||
.msg(format!(
|
||||
"the http request to fetch the part returned a status code of: {}",
|
||||
code
|
||||
)));
|
||||
}
|
||||
|
||||
tmp_gz_file
|
||||
} else {
|
||||
std::fs::File::open(tmp_file_path_gz.clone())?
|
||||
};
|
||||
|
||||
let tar = GzDecoder::new(std::io::BufReader::new(tmp_gz_file));
|
||||
let mut archive = Archive::new(tar);
|
||||
|
||||
//archive.set_mask(umask::Mode::parse("rwxrwxrwx")?.into());
|
||||
|
||||
let target_dir = format!("{}/parts/{}", store_path, part_hash);
|
||||
|
||||
std::fs::create_dir_all(target_dir.as_str())?;
|
||||
|
||||
archive.unpack(target_dir.as_str())?;
|
||||
|
||||
fs::remove_file(&tmp_file_path_gz)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn fetch_part(mize: &mut Mize, part_name: &str) -> MizeResult<String> {
|
||||
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 parts output
|
||||
return Ok(part_path);
|
||||
} else {
|
||||
// if null, load it from the url
|
||||
let part_url = mize.get("self/config/part_url")?.value_string()?;
|
||||
|
||||
let store_path = mize.get("self/config/store_path")?.value_string()?;
|
||||
|
||||
let (part_hash, part_selector) = get_part_hash(mize, part_name, ItemData::new())?;
|
||||
|
||||
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(),
|
||||
part_url.as_str(),
|
||||
part_hash.as_str(),
|
||||
part_name,
|
||||
part_selector.as_str(),
|
||||
)?;
|
||||
}
|
||||
|
||||
return Ok(format!("{}/parts/{}", store_path, part_hash.as_str()));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load_part(mize: &mut Mize, part_name: &str, path: Option<String>) -> MizeResult<()> {
|
||||
let part_path = if path.is_some() {
|
||||
format!("{}/lib/lib{}_part.so", path.unwrap(), part_name)
|
||||
} else {
|
||||
format!(
|
||||
"{}/lib/lib{}_part.so",
|
||||
fetch_part(mize, part_name)?,
|
||||
part_name
|
||||
)
|
||||
};
|
||||
|
||||
let lib = unsafe { libloading::Library::new(part_path)? };
|
||||
|
||||
let func: libloading::Symbol<
|
||||
unsafe extern "C" fn(&mut Box<dyn MizePart + Send + Sync>, Mize) -> (),
|
||||
> = unsafe { lib.get(format!("make_mize_part_{}", part_name).as_bytes())? };
|
||||
|
||||
let mut part: Box<dyn MizePart + Send + Sync> = Box::new(EmptyPart { mize: mize.clone() });
|
||||
|
||||
unsafe { func(&mut part, mize.clone()) };
|
||||
|
||||
part.init(mize)?;
|
||||
|
||||
mize.add_part(part)?;
|
||||
|
||||
unsafe {
|
||||
// dropping the lib, would (i suspect) free all memory, of the library's code, which would
|
||||
// make the part's vtable point into empty memory
|
||||
std::mem::forget(lib);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn config_from_cli_args(matches: &ArgMatches) -> MizeResult<ItemData> {
|
||||
let mut config = ItemData::new();
|
||||
|
||||
if let Some(config_file_path) = matches.get_one::<String>("config-file") {
|
||||
config.merge(config_from_file(config_file_path.to_string())?);
|
||||
trace!("config after --config-file arg: {}", config);
|
||||
}
|
||||
|
||||
if let Some(config_string) = matches.get_one::<String>("config") {
|
||||
config.merge(data_from_string(config_string.to_string())?);
|
||||
trace!("config after --config arg: {}", config);
|
||||
}
|
||||
|
||||
return Ok(config);
|
||||
}
|
||||
|
||||
pub fn config_from_file(file_path: String) -> MizeResult<ItemData> {
|
||||
let toml_string = fs::read_to_string(&file_path)
|
||||
.mize_result_msg(format!("Could not read file {} as mize config", &file_path))?;
|
||||
|
||||
let item_data = ItemData::from_toml(toml_string.as_str())?;
|
||||
|
||||
return Ok(item_data);
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
use ciborium::Value as CborValue;
|
||||
use flume::{unbounded, Receiver, Sender};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt, Interest};
|
||||
use tokio::net::unix::{OwnedReadHalf, OwnedWriteHalf};
|
||||
use tokio::net::{UnixListener as TokioUnixListener, UnixStream};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use crate::error::{IntoMizeResult, MizeError, MizeResult};
|
||||
use crate::instance::connection::{ConnListener, Connection};
|
||||
use crate::instance::{self, Mize};
|
||||
use crate::proto::{self, MizeMessage};
|
||||
|
||||
pub struct UnixListener {
|
||||
sock_path: PathBuf,
|
||||
}
|
||||
|
||||
impl UnixListener {
|
||||
pub fn new(store_path: PathBuf) -> MizeResult<UnixListener> {
|
||||
Ok(UnixListener {
|
||||
sock_path: store_path.join("sock").to_owned(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn connect(instance: &mut Mize, store_path: PathBuf) -> MizeResult<()> {
|
||||
let conn_id = instance.spawn_async_blocking(
|
||||
"unix_connection",
|
||||
connect_async(instance.clone(), store_path),
|
||||
)?;
|
||||
|
||||
let ns_of_peer_str = instance
|
||||
.get(format!(
|
||||
"inst/con_by_id/{}/peer/self/config/namespace",
|
||||
conn_id
|
||||
))?
|
||||
.value_string()?;
|
||||
let ns_of_peer = instance.namespace_from_string(ns_of_peer_str)?;
|
||||
|
||||
info!(
|
||||
"connect_async ... ns_of_peer: {}",
|
||||
ns_of_peer.clone().as_string()
|
||||
);
|
||||
|
||||
instance.connection_set_namespace(conn_id, ns_of_peer.clone());
|
||||
instance.set_namespace(ns_of_peer);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn connect_async(mut instance: Mize, store_path: PathBuf) -> MizeResult<u64> {
|
||||
let mut stream = UnixStream::connect(store_path.join("sock")).await?;
|
||||
let (unix_read, unix_write) = stream.into_split();
|
||||
|
||||
let (send_tx, send_rx) = unbounded::<MizeMessage>();
|
||||
|
||||
let conn_id = instance.new_connection(send_tx)?;
|
||||
|
||||
let cloned_instance = instance.clone();
|
||||
instance.spawn_background("incomming", move || {
|
||||
let result = unix_incomming(unix_read, cloned_instance, conn_id);
|
||||
// if unix incomming fails, close the connection
|
||||
if let Err(err) = result {
|
||||
warn!("Connection closing because of EOF");
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
let outgoing_cloned_instance = instance.clone();
|
||||
instance.spawn_background("outgoing", move || {
|
||||
let result = unix_outgoing(unix_write, send_rx, outgoing_cloned_instance, conn_id);
|
||||
// if writing fails, close this connection
|
||||
if let Err(err) = result {
|
||||
warn!("Connection closing because of EOF");
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
return Ok(conn_id);
|
||||
}
|
||||
|
||||
impl ConnListener for UnixListener {
|
||||
fn listen(self, mut instance: Mize) -> MizeResult<()> {
|
||||
instance.spawn_async("unix listen async", unix_listen(self, instance.clone()));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn unix_listen(listener: UnixListener, mut instance: Mize) -> MizeResult<()> {
|
||||
// remove the file at sock_path if it already exists
|
||||
fs::remove_file(&listener.sock_path);
|
||||
|
||||
let listener = TokioUnixListener::bind(&listener.sock_path).mize_result_msg(format!(
|
||||
"Could not bind to unix socket at '{}'",
|
||||
listener.sock_path.display()
|
||||
))?;
|
||||
|
||||
loop {
|
||||
let (mut unix_sock, addr) = listener
|
||||
.accept()
|
||||
.await
|
||||
.mize_result_msg("Error while accepting Unix sock connection")?;
|
||||
info!("new connection");
|
||||
|
||||
let (send_tx, send_rx) = unbounded::<MizeMessage>();
|
||||
let (unix_read, unix_write) = unix_sock.into_split();
|
||||
|
||||
let conn_id = instance.new_connection(send_tx)?;
|
||||
let cloned_instance = instance.clone();
|
||||
instance.spawn_background("incomming", move || {
|
||||
let result = unix_incomming(unix_read, cloned_instance, conn_id);
|
||||
// if unix incomming fails, close the connection
|
||||
if let Err(err) = result {
|
||||
warn!("Connection closing because of EOF");
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
let outgoing_cloned_instance = instance.clone();
|
||||
instance.spawn_background("outgoing", move || {
|
||||
let result = unix_outgoing(unix_write, send_rx, outgoing_cloned_instance, conn_id);
|
||||
// if writing fails, close this connection
|
||||
if let Err(err) = result {
|
||||
warn!("Connection closing because of EOF");
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn unix_outgoing(
|
||||
mut unix_write: OwnedWriteHalf,
|
||||
send_rx: Receiver<MizeMessage>,
|
||||
mut instance: Mize,
|
||||
conn_id: u64,
|
||||
) -> MizeResult<()> {
|
||||
for msg in send_rx {
|
||||
debug!("unix outgoing got msg: {}", msg);
|
||||
let adapter = MyCiboriumWriter {
|
||||
inner: &mut unix_write,
|
||||
instance: &mut instance,
|
||||
};
|
||||
let value = msg.value();
|
||||
ciborium::into_writer(&value, adapter)?
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unix_incomming(
|
||||
mut unix_read: OwnedReadHalf,
|
||||
mut instance: Mize,
|
||||
conn_id: u64,
|
||||
) -> MizeResult<()> {
|
||||
loop {
|
||||
//println!("unix incoming loop...");
|
||||
let adapter = MyCiboriumReader {
|
||||
inner: &mut unix_read,
|
||||
instance: &mut instance,
|
||||
};
|
||||
let value: CborValue = ciborium::from_reader(adapter)?;
|
||||
if let CborValue::Integer(_) = value {
|
||||
break;
|
||||
}
|
||||
let msg = MizeMessage::new(value, conn_id);
|
||||
debug!("unix incoming got msg: {}", msg);
|
||||
instance.got_msg(msg);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct MyCiboriumWriter<'a> {
|
||||
inner: &'a mut OwnedWriteHalf,
|
||||
instance: &'a mut Mize,
|
||||
}
|
||||
|
||||
impl<'a> ciborium_io::Write for MyCiboriumWriter<'a> {
|
||||
type Error = MizeError;
|
||||
fn write_all(&mut self, data: &[u8]) -> Result<(), Self::Error> {
|
||||
//println!("CALL: write_all");
|
||||
let runtime = self.instance.runtime.lock()?;
|
||||
//println!("after runtime");
|
||||
let num_read = runtime.block_on(self.inner.write_all(data))?;
|
||||
Ok(())
|
||||
}
|
||||
fn flush(&mut self) -> Result<(), Self::Error> {
|
||||
//println!("CALL flush");
|
||||
let handle = self.instance.async_get_handle();
|
||||
let result = handle.block_on(self.inner.flush());
|
||||
//println!("flush result: {:?}", result);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct MyCiboriumReader<'a> {
|
||||
inner: &'a mut OwnedReadHalf,
|
||||
instance: &'a mut Mize,
|
||||
}
|
||||
|
||||
async fn test(test: &mut OwnedReadHalf, buf: &mut [u8]) {
|
||||
//println!("hello from async...");
|
||||
//println!("len: {}", buf.len());
|
||||
let num_read = test.read_u8().await;
|
||||
//println!("num_read: {:?}", num_read);
|
||||
//test.read_exact(buf).await;
|
||||
//println!("hello from async... twoooooooooooooo");
|
||||
}
|
||||
|
||||
impl<'a> ciborium_io::Read for MyCiboriumReader<'a> {
|
||||
type Error = MizeError;
|
||||
fn read_exact(&mut self, data: &mut [u8]) -> Result<(), Self::Error> {
|
||||
//println!("data before: {:?}", data);
|
||||
//let runtime = self.instance.runtime.lock()?;
|
||||
//println!("are we here after runtime lock()");
|
||||
//runtime.block_on(test(self.inner, data));
|
||||
//println!("are we hereeeeeeeeeeeeeeeeeeee");
|
||||
|
||||
//return Ok(());
|
||||
|
||||
//println!("incoming before block_on");
|
||||
let handle = self.instance.async_get_handle();
|
||||
let num_read = handle.block_on(self.inner.read_exact(data))?;
|
||||
//println!("incoming num_read: {:?}", num_read);
|
||||
//println!("data after: {:?}", data);
|
||||
|
||||
// if we read 0 bytes, that means the reader stream closed and we should terminate the
|
||||
// connection
|
||||
//if num_read == 0 {
|
||||
//return Err(MizeError::new().msg("ReceiverStream closed"));
|
||||
//}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,239 +0,0 @@
|
||||
|
||||
static SERVER_PORT: u16 = 3000;
|
||||
static API_ENDPOINT: &str = "@mize";
|
||||
|
||||
|
||||
pub fn run() -> Result<Web, MizeError> {
|
||||
/*
|
||||
* - Run a Webserver
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
// I will deal with renders later. cli only for now
|
||||
// let renders =
|
||||
|
||||
// for render in &*renders {
|
||||
// match render.render_type {
|
||||
// RenderType::JsonUi => {},
|
||||
// RenderType::WebComponent => {
|
||||
// let url_path = String::from("/api/render/") + &render.name + "/webroot";
|
||||
// let file_path = mutexes.mize_folder.clone() + "/mr/" + &render.folder[..] + "/" + &render.webroot.clone()[..];
|
||||
// let serve_dir = get_service(ServeDir::new(&file_path)).handle_error(handle_error);
|
||||
|
||||
// app = app.nest_service(&url_path, serve_dir);
|
||||
// },
|
||||
// }
|
||||
// }
|
||||
|
||||
|
||||
// let serve_client = get_service(ServeDir::new("js-client/src")).handle_error(handle_error);
|
||||
|
||||
let mut app = Router::new()
|
||||
.route(format!("/{}/socket", API_ENDPOINT), get(websocket_handler))
|
||||
// .route(format!("/{}/render/:id", API_ENDPOINT), get(get_render_main))
|
||||
// .route(format!("/{}/file", API_ENDPOINT), get(get_file_handler))
|
||||
// .merge(SpaRouter::new(format!("/{}/client", API_ENDPOINT), "js-client/src").index_file("main.html"))
|
||||
// .nest_service(format!("/{}/client", API_ENDPOINT), serve_client)
|
||||
.with_state(main)
|
||||
.fallback(render_item);
|
||||
|
||||
let addr = SocketAddr::from(([0, 0, 0, 0], SERVER_PORT));
|
||||
// tracing::debug!("listening on {}", addr);
|
||||
|
||||
axum::Server::bind(&addr)
|
||||
.serve(app.into_make_service())
|
||||
.await
|
||||
.expect(format!("Unable to bind axum::Server to {}", addr));
|
||||
}
|
||||
|
||||
pub struct Web {
|
||||
}
|
||||
|
||||
impl Web {
|
||||
|
||||
}
|
||||
|
||||
|
||||
async fn handle_error(_err: std::io::Error) -> impl IntoResponse {
|
||||
MizeError::new(0).msg("internal server error").handle()
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong...")
|
||||
}
|
||||
|
||||
async fn render_item(uri: Uri) -> impl IntoResponse {
|
||||
Html(fs::read_to_string("js-client/src/main.html").unwrap())
|
||||
}
|
||||
|
||||
//#[axum_macros::debug_handler]
|
||||
//async fn get_render_main(extract::Path(id): extract::Path<String>, State(mutexes): State<Mutexes>) -> http::Response<String> {
|
||||
// let renders = &*mutexes.renders.lock().await;
|
||||
|
||||
// let render = renders.iter().filter(|&render| render.name == id).nth(0)
|
||||
// .unwrap_or(renders.iter().filter(|&render| render.name == "mize-mmejs").nth(0).expect("mize-mmejs"));
|
||||
|
||||
// let file_path = mutexes.mize_folder.clone() + "/mr/" + &render.folder + "/" + &render.main;
|
||||
|
||||
// match render.render_type {
|
||||
// RenderType::JsonUi => {
|
||||
// return Response::builder()
|
||||
// .header("content-type", "application/json")
|
||||
// .status(StatusCode::OK)
|
||||
// .body(fs::read_to_string(file_path).unwrap()).unwrap();
|
||||
// },
|
||||
// RenderType::WebComponent => {
|
||||
// return Response::builder()
|
||||
// .header("content-type", "application/javascript")
|
||||
// .status(StatusCode::OK)
|
||||
// .body(fs::read_to_string(file_path).unwrap()).unwrap();
|
||||
// },
|
||||
// }
|
||||
//}
|
||||
|
||||
async fn websocket_handler(
|
||||
ws: WebSocketUpgrade,
|
||||
State(main): State<&Main>,
|
||||
headers: HeaderMap,
|
||||
) -> impl IntoResponse {
|
||||
ws.on_upgrade(|socket| handle_websocket_connection(socket, main, headers))
|
||||
}
|
||||
|
||||
async fn handle_websocket_connection(
|
||||
socket: WebSocket,
|
||||
main: &Main,
|
||||
headers: HeaderMap,
|
||||
){
|
||||
//TODO: auth
|
||||
|
||||
//socket_tx.send() ... send out the socket
|
||||
//socket_rx.read() ... read a message from the socket
|
||||
let (mut socket_tx, mut socket_rx) = socket.split();
|
||||
|
||||
// msg_tx.send() ... send a MizeMessage to a Peer. should be in a Peer struct
|
||||
// msg_rx.read() ... read MizeMessages that should be sent to the Peer that this ws connection is to
|
||||
let (msg_tx, msg_rx): (Sender<proto::MizeMessage>, Receiver<proto::MizeMessage>) = mpsc::channel(SOCKET_CHANNEL_SIZE);
|
||||
|
||||
// why is this actually
|
||||
let mut msg_rx = ReceiverStream::new(msg_rx);
|
||||
|
||||
// check if mize-module header exists
|
||||
// let origin = if let Some(mod_header_val) = headers.get("mize-module"){
|
||||
|
||||
// let mut mods = mutexes.modules.lock().await;
|
||||
// let mut client_id = mutexes.next_free_client_id.lock().await;
|
||||
// let mut module = Module{
|
||||
// tx: msg_tx.clone(),
|
||||
// client_id: *client_id,
|
||||
// name: String::from("tmp"),
|
||||
// kind: ModuleKind::Extern(),
|
||||
// registered_types: Vec::new(),
|
||||
// };
|
||||
|
||||
// *client_id += 1;
|
||||
|
||||
// if let Ok(name) = mod_header_val.to_str() {
|
||||
// module.name = name.to_string();
|
||||
// } else {
|
||||
// let err = MizeError::new(113)
|
||||
// .extra_msg("The mize-module Header could not be decoded into a String.");
|
||||
|
||||
// msg_tx.send(proto::MizeMessage::Json(err.to_json_message())).await;
|
||||
// return;
|
||||
// };
|
||||
// println!("module {} connected", module.name);
|
||||
// mods.push(module.clone());
|
||||
// drop(mods);
|
||||
// Peer::Module(module)
|
||||
|
||||
// } else {
|
||||
// };
|
||||
|
||||
// Forwarding messages
|
||||
tokio::spawn(async move {
|
||||
while let Some(msg) = msg_rx.next().await {
|
||||
match msg {
|
||||
proto::MizeMessage::Json(json_msg) => {
|
||||
if let Ok(msg) = serde_json::to_string(&json_msg) {
|
||||
let result = socket_tx.send(Message::Text(msg.clone())).await;
|
||||
if let Err(e) = result {
|
||||
println!("Client no longer Connected: {:?}", e);
|
||||
remove_peer(myorigin.clone(), mymutexes.clone()).await;
|
||||
} else {
|
||||
println!("SENDING: {}", msg);
|
||||
}
|
||||
} else {
|
||||
let err: MizeError = MizeError::new(11).extra_msg("error while serializing a json message").handle();
|
||||
if let Ok(text) = serde_json::to_string(&err.to_json()){
|
||||
socket_tx.send(Message::Text(text));
|
||||
} else {
|
||||
MizeError::new(11).extra_msg("not even being able to serialize an error, while failing to serializing a message").handle();
|
||||
}
|
||||
}
|
||||
}
|
||||
proto::MizeMessage::Bin(bin_msg) => {
|
||||
socket_tx.send(Message::Binary(bin_msg.raw)).await;
|
||||
}
|
||||
proto::MizeMessage::Pong() => {
|
||||
socket_tx.send(Message::Pong(Vec::new())).await;
|
||||
}
|
||||
proto::MizeMessage::Close((num, reason)) => {
|
||||
println!("SENDING Close message");
|
||||
socket_tx.send(Message::Close(Some(CloseFrame{code: num, reason: Cow::Owned(reason)}))).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Reading messages
|
||||
while let Some(result) = socket_rx.next().await {
|
||||
let msg = if let Ok(msg) = result {msg} else {
|
||||
let err = MizeError::new(115).extra_msg("TCP Connection Closed");
|
||||
remove_peer(origin.clone(), mutexes.clone());
|
||||
return;
|
||||
};
|
||||
match msg {
|
||||
Message::Binary(b) => {
|
||||
println!("Recieved a Binary Message. Those are not implemented yet.")
|
||||
},
|
||||
|
||||
|
||||
Message::Text(text) => {
|
||||
println!("GOT: {}", text);
|
||||
let json_msg: proto::JsonMessage = serde_json::from_str(&text).expect("error parsing json");
|
||||
if let Err(err) = proto::handle_json_msg(json_msg, origin.clone(), mutexes.clone()).await {
|
||||
let err_msg: MizeMessage = err.handle().into();
|
||||
origin.send(err_msg).await;
|
||||
};
|
||||
},
|
||||
|
||||
Message::Close(inner) => {
|
||||
match inner {
|
||||
Some(CloseFrame{code, reason}) => {
|
||||
origin.send(MizeMessage::Close((code, reason.into_owned()))).await;
|
||||
},
|
||||
None => {
|
||||
origin.send(MizeMessage::Close((1000, "You didn't send a Close Reason".to_owned()))).await;
|
||||
}
|
||||
};
|
||||
|
||||
println!("Close from Client");
|
||||
remove_peer(origin.clone(), mutexes.clone()).await;
|
||||
}
|
||||
|
||||
|
||||
Message::Ping(_) => {
|
||||
msg_tx.send(MizeMessage::Pong());
|
||||
},
|
||||
|
||||
|
||||
Message::Pong(_) => {
|
||||
let err = MizeError::new(11)
|
||||
.extra_msg("unhandeld WebSocket-Message type: Pong")
|
||||
.handle();
|
||||
msg_tx.send(proto::MizeMessage::Json(err.to_json_message())).await;
|
||||
},
|
||||
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
|
||||
use crate::instance::MizeInstance;
|
||||
|
||||
#[test]
|
||||
fn most_minimal_instance_usage() {
|
||||
// so I'm actually starting the effort for a better code base here in the tests
|
||||
// i want to write down how you would use the very important instance type
|
||||
// and then implement it to make it usable in this way
|
||||
|
||||
// how every mize based program to run on an os should create a mize instance
|
||||
// opens the instance the way the user has configured (with env vars, build args, or config
|
||||
// files)
|
||||
// and we just call it "new()" and not "default_system()" so that it is clear that this is the
|
||||
// method that should be used
|
||||
let mize = MizeInstance::new();
|
||||
|
||||
// then the most important things you do with your mize instance is to get/set stuff
|
||||
let name: MizeItem = mize.get("1/namespace");
|
||||
let id = mize.new_item();
|
||||
mize.set(id.join("name"), "test-item");
|
||||
|
||||
// or register update callbacks and update
|
||||
//mize.on_update("5/name", |delta| println!(delta.new_value()));
|
||||
//mize.update("5/name", "other-item")
|
||||
|
||||
// the goal is that also most things about the MizeInstance itself is controlled by
|
||||
// get/set/update -ing values at the 0/ paths
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
|
||||
[config]
|
||||
namespace = "test.c2vi.dev"
|
||||
test = "hello from test item"
|
||||
|
||||
[config.module_dir]
|
||||
8841
packages/mme/Cargo.lock
generated
8841
packages/mme/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,76 +0,0 @@
|
||||
[package]
|
||||
name = "mme"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
|
||||
[package.metadata.wasm-pack.profile.dev]
|
||||
wasm-opt = false
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[features]
|
||||
default = [ "target-os" ]
|
||||
qt = [ "slint", "cpp", "qt_core", "qt_gui", "qt_widgets", "comandr/qt" ]
|
||||
slint = [ "i-slint-backend-qt", "dep:slint", "slint-interpreter", "spin_on", "qt" ]
|
||||
target-os= [ "tao", "wry", "tracing-subscriber", "clap", "webkit2gtk", "mize/target-os", "glib" ]
|
||||
#target-os= [ "tao", "wry", "tracing-subscriber", "clap" ]
|
||||
target-wasm = [ "wasm-bindgen", "console_error_panic_hook", "wasm-bindgen-cli", "web-sys", "comandr/target-wasm ", "mize/wasm-target" ]
|
||||
console_error_panic_hook = ["dep:console_error_panic_hook"]
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
webkit2gtk = { version = "2.0.1", optional = true }
|
||||
|
||||
[dependencies]
|
||||
# core deps
|
||||
colored = "2.1.0"
|
||||
enum_dispatch = "0.3.13"
|
||||
comandr = { git = "https://github.com/c2vi/comandr", default-features = false }
|
||||
#comandr = { path = "../../../dr-comandr" }
|
||||
mize = { git = "https://github.com/c2vi/mize", default-features = false }
|
||||
tracing = "0.1.40"
|
||||
base64 = "0.22.1"
|
||||
|
||||
# wasm dependencies
|
||||
wasm-bindgen = { version = "0.2.84", optional = true }
|
||||
console_error_panic_hook = { version = "0.1.7", optional = true }
|
||||
wasm-bindgen-cli = { version = "0.2.92", optional = true }
|
||||
web-sys = { version = "0.3.70", optional = true, features = ['console'] }
|
||||
|
||||
# os deps
|
||||
tao = { version = "0.28.1", optional = true }
|
||||
wry = { version = "0.41.0", optional = true, features = [ "devtools" ] }
|
||||
tracing-subscriber = { version = "0.3.18", features = ["env-filter"], optional = true }
|
||||
clap = { version = "4.5.8", features = ["cargo"], optional = true }
|
||||
glib = { version = "0.15.12", optional = true }
|
||||
|
||||
# qt deps
|
||||
#qt_gui = "0.5.0"
|
||||
cpp = { version = "0.5.9", optional = true }
|
||||
qt_gui = { version = "0.5.0", optional = true }
|
||||
qt_core = { version = "0.5.0", optional = true }
|
||||
qt_widgets = { version = "0.5.0", optional = true }
|
||||
|
||||
#slint deps
|
||||
i-slint-backend-qt = { version = "1.7.1", optional = true }
|
||||
slint = { version = "1.7.1", optional = true }
|
||||
slint-interpreter = { version = "1.7.1", optional = true }
|
||||
spin_on = { version = "0.1.1", optional = true }
|
||||
custom-print = "1.0.0"
|
||||
flume = "0.11.1"
|
||||
ciborium = "0.2.2"
|
||||
ciborium-io = { version = "0.2.2", features = ["std", "alloc"] }
|
||||
wasm-bindgen-futures = "0.4.49"
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1.1.5"
|
||||
cpp_build = "0.5"
|
||||
|
||||
[lib]
|
||||
name = "mize_module_mme"
|
||||
crate-type =["cdylib", "rlib"]
|
||||
|
||||
[target.wasm32-unknown-unknown]
|
||||
rustflags = [
|
||||
"-C", "link-args=--import-memory",
|
||||
]
|
||||
@@ -1,8 +0,0 @@
|
||||
|
||||
set -e
|
||||
|
||||
wasm-pack build --features wasm-target --no-default-features
|
||||
|
||||
cd /home/me/work/mme-presenters/presenters/mme-js/
|
||||
|
||||
npm run build -- --mode development
|
||||
@@ -1,29 +0,0 @@
|
||||
|
||||
fn main() {
|
||||
|
||||
#[cfg(feature = "qt")]
|
||||
{
|
||||
let qt_lib_path = env!("MME_QT_LIB");
|
||||
cc::Build::new()
|
||||
.cpp(true)
|
||||
.file("src/main.cpp")
|
||||
.flag("-w")
|
||||
.compile("mme");
|
||||
println!("cargo:rustc-link-search={}", qt_lib_path);
|
||||
println!("cargo:rustc-link-lib=Qt5Quick");
|
||||
println!("cargo:rustc-link-lib=Qt5PrintSupport ");
|
||||
println!("cargo:rustc-link-lib=Qt5Qml ");
|
||||
println!("cargo:rustc-link-lib=Qt5Network ");
|
||||
println!("cargo:rustc-link-lib=Qt5Widgets ");
|
||||
println!("cargo:rustc-link-lib=Qt5Gui ");
|
||||
println!("cargo:rustc-link-lib=Qt5Core");
|
||||
println!("cargo:rustc-link-lib=Qt5WebEngine");
|
||||
println!("cargo:rustc-link-lib=Qt5WebEngineCore");
|
||||
println!("cargo:rustc-link-lib=Qt5WebEngineWidgets");
|
||||
|
||||
println!("cargo:rerun-if-changed=src/main.cpp");
|
||||
|
||||
cpp_build::build("src/implementors/qt_widget/mod.rs");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
|
||||
|
||||
export MIZE_MODULE_PATH=/home/me/work/mme:/home/me/work/modules:/home/me/work/mesenters
|
||||
export MIZE_MODULE_NO_REPO=1
|
||||
export MIZE_MODULE_NO_EXTERNALS=1
|
||||
export MIZE_CONFIG=$MIZE_CONFIG:module_dir.mme=/home/me/work/mme/dist:module_dir.String=/home/me/work/modules/modules/String/dist
|
||||
|
||||
function dev() {
|
||||
|
||||
#nix develop /home/me/work/mize#modules.mme --override-input nixpkgs github:nixos/nixpkgs/ea6033ce4ddf2c0ede2ea147a450d4f880796128 --impure
|
||||
nix develop /home/me/work/mize#modules.mme --override-input nixpkgs github:nixos/nixpkgs/10e687235226880ed5e9f33f1ffa71fe60f2638a --impure
|
||||
#nix develop /home/me/work/mize#modules.mme --impure
|
||||
|
||||
}
|
||||
|
||||
if [[ "$1" != "no" ]]
|
||||
then
|
||||
dev
|
||||
fi
|
||||
@@ -1,171 +0,0 @@
|
||||
{
|
||||
|
||||
|
||||
module = { buildMizeForSystem, mizeBuildConfig, mkMizeRustModule, hostSystem, pkgsCross, mkMizeRustShell, pkgs, pkgsNative, buildNpmPackage, mkSelString, mizeBuildConfigStr, fenix, ... }: let
|
||||
|
||||
selector_string = mkSelString {
|
||||
modName = "mme";
|
||||
};
|
||||
hash = builtins.substring 0 32 (builtins.hashString "sha256" selector_string);
|
||||
url = "file:///home/me/work/mme/dist/mize.js";
|
||||
html = ''
|
||||
<html>
|
||||
<head>
|
||||
<!-- script src="https://c2vi.dev/mize/wasm32-none-unknown/mize.js"></script --!>
|
||||
<!-- script src="${url}"></script --!>
|
||||
<script>
|
||||
console.log("from script")
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
hello world...............
|
||||
</body>
|
||||
</html>
|
||||
'';
|
||||
|
||||
in mkMizeRustModule ({
|
||||
modName = "mme";
|
||||
src = ./.;
|
||||
cargoExtraArgs = "--no-default-features --lib";
|
||||
|
||||
## add the index.html
|
||||
postInstall = ''
|
||||
echo -n '${html}' > $out/index.html
|
||||
'';
|
||||
|
||||
}
|
||||
|
||||
|
||||
// (if hostSystem.name == "wasm32-none-unknown" then {
|
||||
mizeBuildPhase = ''
|
||||
cd $build_dir
|
||||
RUSTFLAGS="-C link-args=--import-memory" RUST_LOG=off wasm-pack build --target no-modules --dev --out-dir $out -- --features wasm-target --no-default-features
|
||||
echo -n 'export function get_wasm_bindgen() { return wasm_bindgen }' >> $out/mize_module_mme.js
|
||||
echo -n '${html}' > $out/index.html
|
||||
'';
|
||||
mizeInstallPhase = "";
|
||||
} else {})
|
||||
|
||||
// (if hostSystem.kernel.name == "linux" then builtins.trace "adding linux stuff" {
|
||||
nativeBuildInputs = with pkgsCross.buildPackages; [
|
||||
pkg-config
|
||||
];
|
||||
buildInputs = with pkgsNative; [
|
||||
webkitgtk_4_1
|
||||
];
|
||||
} else {})
|
||||
|
||||
|
||||
# add the devShell
|
||||
// {
|
||||
devShell = pkgs.mkShell {
|
||||
nativeBuildInputs = with pkgs; [
|
||||
#emscripten
|
||||
wasm-pack
|
||||
pkg-config
|
||||
webkitgtk_4_1
|
||||
libsForQt5.full
|
||||
cmake
|
||||
nasm
|
||||
pkg-config
|
||||
nodejs
|
||||
|
||||
(fenix.packages.${system}.combine [
|
||||
fenix.packages.${system}.targets.wasm32-unknown-unknown.latest.toolchain
|
||||
fenix.packages.${system}.latest.toolchain
|
||||
fenix.packages.${system}.latest.rust-src
|
||||
])
|
||||
|
||||
];
|
||||
|
||||
MIZE_BUILD_CONFIG = mizeBuildConfigStr;
|
||||
|
||||
buildInputs = with pkgs; [
|
||||
openssl
|
||||
#pango
|
||||
#libsoup_3
|
||||
webkitgtk_4_1
|
||||
# gobject-introspection gtk4 atkmm
|
||||
];
|
||||
|
||||
shellHook = ''
|
||||
echo hiiiiiiiiiiiiii
|
||||
export LD_LIBRARY_PATH=${pkgs.webkitgtk_4_1}/lib:${pkgs.libsoup_3}/lib:${pkgs.glib.out}/lib:${pkgs.gtk3}/lib:${pkgs.cairo}/lib:${pkgs.gdk-pixbuf}/lib:${pkgs.libxkbcommon}/lib:${pkgs.fontconfig.lib}/lib:${pkgs.libsForQt5.full}/lib:${pkgs.stdenv.cc.cc.lib}/lib:${pkgs.libsForQt5.qt5.qtwebengine}/lib
|
||||
|
||||
export CPLUS_INCLUDE_PATH=${pkgs.libsForQt5.full}/include:${pkgs.libsForQt5.qt5.qtwebengine}/include
|
||||
|
||||
export MME_QT_LIB=${pkgs.libsForQt5.full}/lib
|
||||
|
||||
# i found that this is the env war to set where QT looks for platform plugins
|
||||
# at: https://forums.fedoraforum.org/showthread.php?326508-How-to-set-QT_QPA_PLATFORM_PLUGIN_PATH
|
||||
export QT_QPA_PLATFORM_PLUGIN_PATH=${pkgs.libsForQt5.full}/lib/qt-5.15.14/plugins/platforms/
|
||||
|
||||
alias run="${./.}/run.sh"
|
||||
'';
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
);
|
||||
|
||||
|
||||
|
||||
lib = { mkMizeModule, buildNpmPackage, pkgsCross, pkgsNative, ... }: rec {
|
||||
mkMmePresenter = attrs: mkMizeModule (attrs // {
|
||||
src = attrs.src;
|
||||
modName = attrs.name;
|
||||
select = {
|
||||
mme_presenter = true;
|
||||
};
|
||||
});
|
||||
|
||||
mkMmeNpmPresenter = attrs: mkMizeModule (attrs // {
|
||||
drvFunc = buildNpmPackage;
|
||||
mizeBuildPhase = ''
|
||||
cd $build_dir
|
||||
npm i
|
||||
npm run build
|
||||
mv dist tmp
|
||||
mkdir -p $out
|
||||
mv tmp/* $out
|
||||
rm -rf tmp
|
||||
'';
|
||||
mizeInstallPhase = "";
|
||||
select = {
|
||||
mme_presenter = true;
|
||||
};
|
||||
|
||||
devShell = pkgsNative.mkShell {
|
||||
buildInputs = with pkgsNative; [ nodejs_20 ];
|
||||
};
|
||||
|
||||
});
|
||||
|
||||
mkMmeHtmlPresenter = attrs: mkMmePresenter ({
|
||||
dontUnpack = true;
|
||||
dontPath = true;
|
||||
buildPhase = "";
|
||||
installPhase = ''
|
||||
mkdir -p $out
|
||||
cp -r ${attrs.src}/* $out
|
||||
'';
|
||||
} // attrs);
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
externals = { fetchFromGitHub, ... }: [
|
||||
|
||||
(fetchFromGitHub {
|
||||
owner = "c2vi";
|
||||
repo = "mme-presenters";
|
||||
rev = "master";
|
||||
hash = "sha256-FeMBDCJBkw9XOLXC1rfedNk71uyg4OTCHaaO1jAAGto=";
|
||||
})
|
||||
|
||||
];
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
|
||||
set -e
|
||||
|
||||
# override, where mize loads the mme module from
|
||||
export MIZE_MODULE_PATH=/home/me/work/mme:/home/me/work/modules:/home/me/work/presenters
|
||||
export MIZE_MODULE_NO_REPO=1
|
||||
export MIZE_MODULE_NO_EXTERNALS=1
|
||||
export MIZE_CONFIG=$MIZE_CONFIG:module_dir.mme=/home/me/work/mme/dist:module_dir.String=/home/me/work/modules/modules/String/dist:module_dir.mme_presenter.mme_js=/home/me/work/presenters/presenters/mme_js/dist
|
||||
#export MIZE_CONFIG=$MIZE_CONFIG:module_dir.mme=/home/me/work/mize/result
|
||||
|
||||
|
||||
# build mme for the browser
|
||||
echo '############################# MME for Browser #############################'
|
||||
RUST_LOG=off wasm-pack build --target no-modules --dev --out-dir ./dist -- --features wasm-target --no-default-features
|
||||
|
||||
|
||||
# build mize for the browser
|
||||
echo '############################# mize for Browser #############################'
|
||||
cd /home/me/work/mize
|
||||
RUST_LOG=off wasm-pack build --target no-modules --dev -- --features wasm-target --no-default-features
|
||||
cat /home/me/work/mize/src/platform/wasm/init.js >> /home/me/work/mize/pkg/mize.js
|
||||
|
||||
#--out-dir ~/work/mize/src/platform/wasm/npm_pkg/generated
|
||||
|
||||
#export CARGO_BUILD_RUSTFLAGS='-C target-feature=+atomics,+bulk-memory,+mutable-globals'
|
||||
#wasm-pack build --target no-modules --dev . -Z build-std=panic_abort,std --features wasm-target --no-default-features --config 'build.rustflags = "-C target-feature=+atomics,+bulk-memory,+mutable-globals"'
|
||||
#cp -r ~/work/mize/pkg/* ~/work/mize/src/platform/wasm/npm_pkg/generated
|
||||
#RUSTFLAGS='-C target-feature=+atomics,+bulk-memory,+mutable-globals' cargo build --target wasm32-unknown-unknown -Z build-std=panic_abort,std --lib --no-default-features
|
||||
#cp ~/work/mize/target/wasm32-unknown-unknown/debug/mize.wasm ~/work/mize/src/platform/wasm/npm_pkg/generated/mize_bg.wasm
|
||||
|
||||
|
||||
# build the mme-js presenter
|
||||
echo '############################# mme-js presenter #############################'
|
||||
cd /home/me/work/presenters/presenters/mme_js/
|
||||
npm run build -- --mode development
|
||||
|
||||
|
||||
# build the mme module
|
||||
echo '############################# mme module for os #############################'
|
||||
cd /home/me/work/mme
|
||||
cargo build --lib
|
||||
mkdir -p /home/me/work/mme/dist/lib
|
||||
cp /home/me/work/mme/target/debug/libmize_module_mme.so /home/me/work/mme/dist/lib
|
||||
nix eval --expr 'import /home/me/work/mme/src/implementors/html/index.nix { mize_url = "file:///home/me/work/mize/pkg/mize.js"; }' --impure --raw > /home/me/work/mme/dist/index.html
|
||||
|
||||
|
||||
# build the String module
|
||||
echo '############################# string module for os #############################'
|
||||
cargo build --manifest-path ~/work/modules/modules/String/Cargo.toml --lib
|
||||
mkdir -p /home/me/work/modules/modules/String/dist/lib
|
||||
cp /home/me/work/modules/modules/String/target/debug/libmize_module_String.so /home/me/work/modules/modules/String/dist/lib
|
||||
|
||||
|
||||
# run mize with gui
|
||||
echo '############################# run mize for os #############################'
|
||||
cargo run --manifest-path ~/work/mize/Cargo.toml -- gui
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
use crate::slot::Slot;
|
||||
|
||||
use mize::MizeResult;
|
||||
|
||||
// A Presenter, that takes not data and produces only one output Space
|
||||
// with that space being of a different type.
|
||||
// In order to put Presenters of different types into one another.
|
||||
// eg a QT-Webview is put into a qt-space ... in order to get a web-space....
|
||||
pub struct Adapter {
|
||||
}
|
||||
|
||||
pub trait AdapterTrait {
|
||||
fn sub_slot() -> MizeResult<Slot>;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
|
||||
|
||||
// A Presenter, that takes no data. Just provides sub spaces.
|
||||
pub struct Layout {
|
||||
}
|
||||
@@ -1,557 +0,0 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{implementors::{html::HtmlPresenter}, presenter};
|
||||
use crate::slot::{Slot, SlotTrait};
|
||||
use crate::presenter::Presenter;
|
||||
use tracing::info;
|
||||
use comandr::Comandr;
|
||||
use flume::{ Receiver, Sender };
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use base64::Engine;
|
||||
use core::ptr::NonNull;
|
||||
|
||||
|
||||
#[cfg(feature = "wasm-target")]
|
||||
use wasm_bindgen::JsValue;
|
||||
#[cfg(feature = "wasm-target")]
|
||||
use web_sys::js_sys::Function;
|
||||
|
||||
//#[cfg(feature = "target-os")]
|
||||
//use crate::implementors::qt_widget::QtWidgetSlot;
|
||||
#[cfg(feature = "qt")]
|
||||
use qt_core::{qs, QString, QTimer, SlotNoArgs};
|
||||
#[cfg(feature = "qt")]
|
||||
use qt_widgets::{QApplication, QGridLayout, QWidget};
|
||||
#[cfg(feature = "qt")]
|
||||
use qt_gui::{cpp_core::CppBox};
|
||||
|
||||
|
||||
use mize::Module;
|
||||
use mize::MizeResult;
|
||||
use mize::error::MizeResultTrait;
|
||||
use mize::Instance;
|
||||
use mize::mize_err;
|
||||
use mize::MizeError;
|
||||
use mize::proto::MizeMessage;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Mme {
|
||||
pub comandr: Arc<Mutex<Comandr>>,
|
||||
pub mize: Instance,
|
||||
}
|
||||
|
||||
|
||||
|
||||
// console_log macro
|
||||
// that can be copied into other files for debugging purposes
|
||||
#[cfg(feature = "wasm-target")]
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
#[cfg(feature = "wasm-target")]
|
||||
#[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())})
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#[no_mangle]
|
||||
extern "C" fn get_mize_module_mme(empty_module: &mut Box<dyn Module + Send + Sync>, mize: Instance) -> () {
|
||||
#[cfg(feature = "wasm-target")]
|
||||
console_log!("hiiiiiiiiiiiiiiii from inside get_mize_module_mme!!!!!!!!!");
|
||||
let comandr = Comandr::new();
|
||||
let new_box: Box<dyn Module + Send + Sync> = Box::new( Mme { comandr: Arc::new(Mutex::new(comandr)), mize, } );
|
||||
|
||||
*empty_module = new_box
|
||||
}
|
||||
|
||||
#[cfg(feature = "wasm-target")]
|
||||
use mize::platform::wasm::JsInstance;
|
||||
|
||||
#[cfg(feature = "wasm-target")]
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
#[cfg(feature = "wasm-target")]
|
||||
#[wasm_bindgen]
|
||||
pub unsafe fn wasm_get_mize_module_mme(mut empty_module_ptr: usize, mut mize_ptr: usize) -> () {
|
||||
|
||||
console_log!("hiiiiiiiiiiiiiiiiiiiiiii form wasm_get_mize_module_mme");
|
||||
let empty_module = empty_module_ptr as * mut Box<dyn Module + Send + Sync>;
|
||||
console_log!("here");
|
||||
|
||||
let mize = (*(mize_ptr as * mut Instance)).clone();
|
||||
|
||||
console_log!("here2");
|
||||
|
||||
//(*empty_module).init(&mize);
|
||||
|
||||
console_log!("here3");
|
||||
|
||||
let comandr = Comandr::new();
|
||||
let mut new_box: Box<dyn Module + Send + Sync> = Box::new( Mme { comandr: Arc::new(Mutex::new(comandr)), mize: mize.clone(), } );
|
||||
|
||||
console_log!("before new_box.init()");
|
||||
new_box.init(&mize);
|
||||
|
||||
console_log!("before assignment");
|
||||
|
||||
*empty_module = new_box
|
||||
}
|
||||
/*
|
||||
pub fn wasm_get_mize_module_mme(empty_module_ptr: usize, mize: JsInstance) -> usize {
|
||||
let mut empty_module: Box<dyn Module + Send + Sync> = *(empty_module_ptr as Box<Box<dyn Module + Send + Sync>>);
|
||||
let mize = mize.inner().clone();
|
||||
let comandr = Comandr::new();
|
||||
let new_box: Box<dyn Module + Send + Sync> = Box::new( Mme { comandr: Arc::new(Mutex::new(comandr)), mize, } );
|
||||
|
||||
*empty_module = new_box
|
||||
}
|
||||
*/
|
||||
|
||||
impl Module for Mme {
|
||||
fn init(&mut self, _instance: &Instance) -> MizeResult<()> {
|
||||
|
||||
|
||||
#[cfg(feature = "wasm-target")]
|
||||
{
|
||||
// console log
|
||||
use wasm_bindgen::prelude::*;
|
||||
#[wasm_bindgen]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(js_namespace = console)]
|
||||
fn log(s: &str);
|
||||
}
|
||||
macro_rules! console_log {
|
||||
// Note that this is using the `log` function imported above during
|
||||
// `bare_bones`
|
||||
($($t:tt)*) => (log(&format_args!($($t)*).to_string()))
|
||||
}
|
||||
console_log!("mme module inittttttttttttttttttttttt");
|
||||
}
|
||||
|
||||
println!("MmeModule init");
|
||||
|
||||
#[cfg(feature = "target-os")]
|
||||
{
|
||||
//self.mize.spawn("mme-main", || self.create_x_window());
|
||||
let mut cloned_self = self.clone();
|
||||
// "significant cross-platform compatibility hazard." xD
|
||||
//self.mize.spawn("mme-main", move || cloned_self.create_x_window());
|
||||
|
||||
self.create_x_window();
|
||||
|
||||
}
|
||||
|
||||
#[cfg(feature = "wasm-target")]
|
||||
{
|
||||
use web_sys::js_sys::eval;
|
||||
use crate::implementors::html::wasm::MmeJs;
|
||||
use std::ptr::NonNull;
|
||||
|
||||
// create mme module object
|
||||
let mut mme_js = MmeJs {
|
||||
inner: NonNull::from(Box::leak(Box::new(self.clone()))),
|
||||
webview_con_id: 0,
|
||||
};
|
||||
|
||||
let func = Function::new_with_args("mme_js", r#"
|
||||
window.mize.mod.mme = mme_js;
|
||||
"#);
|
||||
func.call1(&JsValue::null(), &JsValue::from(mme_js)).map_err(|e| mize_err!("from js error: {:?}", e));
|
||||
|
||||
//
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn exit(&mut self, _instance: &Instance) -> MizeResult<()> {
|
||||
info!("mme module exit");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clone_module(&self) -> Box<dyn Module + Send + Sync> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#[cfg(feature = "qt")]
|
||||
unsafe fn qstring_to_rust(q_string: CppBox<QString>) -> String {
|
||||
let mut rust_string = String::new();
|
||||
let q_string_size = q_string.size();
|
||||
|
||||
for j in 0..q_string_size {
|
||||
let q_char = q_string.index_int(j);
|
||||
let rust_char = char::from_u32(q_char.unicode() as u32);
|
||||
rust_string.push(rust_char.unwrap());
|
||||
}
|
||||
return rust_string;
|
||||
}
|
||||
|
||||
impl Mme {
|
||||
pub fn new(mize: Instance) -> MizeResult<Mme> {
|
||||
let comandr = Comandr::new();
|
||||
Ok(Mme { comandr: Arc::new(Mutex::new(comandr)), mize, })
|
||||
}
|
||||
|
||||
#[cfg(feature = "wasm-target")]
|
||||
pub fn create_html_slot() -> MizeResult<()> {
|
||||
println!("hi wasm");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "target-os")]
|
||||
pub fn create_x_window(&mut self) -> MizeResult<()> {
|
||||
use std::fs;
|
||||
|
||||
use tao::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::{self, ControlFlow, EventLoop, EventLoopBuilder, EventLoopProxy},
|
||||
window::WindowBuilder,
|
||||
};
|
||||
use wry::{http::{Method, Request, Response}, WebViewBuilder};
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
use wry::WebViewExtUnix;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
use webkit2gtk::{Settings, WebInspectorExt};
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
use webkit2gtk::WebViewExt;
|
||||
|
||||
use crate::implementors::html::webview_con::{msg_from_string, msg_to_string};
|
||||
|
||||
let event_loop = EventLoopBuilder::with_user_event().build();
|
||||
let event_loop_proxy: EventLoopProxy<MizeMessage> = event_loop.create_proxy();
|
||||
let window = WindowBuilder::new().build(&event_loop).unwrap();
|
||||
|
||||
#[cfg(any(
|
||||
target_os = "windows",
|
||||
target_os = "macos",
|
||||
target_os = "ios",
|
||||
target_os = "android"
|
||||
))]
|
||||
let builder = WebViewBuilder::new(&window);
|
||||
|
||||
#[cfg(not(any(
|
||||
target_os = "windows",
|
||||
target_os = "macos",
|
||||
target_os = "ios",
|
||||
target_os = "android"
|
||||
)))]
|
||||
let builder = {
|
||||
use tao::platform::unix::WindowExtUnix;
|
||||
use wry::WebViewBuilderExtUnix;
|
||||
let vbox = window.default_vbox().unwrap();
|
||||
WebViewBuilder::new_gtk(vbox)
|
||||
};
|
||||
|
||||
//let html_str = fs::read_to_string(format!("{}/../implementors/html/js-runtime/dist/index.html", file!()))?;
|
||||
//println!("html_str: {}", html_str);
|
||||
|
||||
// get the path of the index.html
|
||||
let test = self.mize.fetch_module("mme")?;
|
||||
let mme_module_path = self.mize.fetch_module("cross.wasm32-none-unknown.mme")?;
|
||||
|
||||
let mize_module_path = self.mize.fetch_module("cross.wasm32-none-unknown.mize")?;
|
||||
|
||||
let init_script = format!(r#"
|
||||
import("{mize_module_path}/mize.js").then( module => module.init_mize({{module_dir: {{mize: "{mize_module_path}"}}}}))
|
||||
"#);
|
||||
|
||||
|
||||
// add the mize connection to the instance inside the webview
|
||||
let (tx, rx): (Sender<MizeMessage>, Receiver<MizeMessage>) = flume::unbounded();
|
||||
let conn_id = self.mize.new_connection(tx)?;
|
||||
|
||||
|
||||
let mut self_clone = self.clone();
|
||||
let mut self_clone_two = self.clone();
|
||||
let webview = builder
|
||||
//.with_url("http://localhost:8000/index.html")
|
||||
//.with_url("file:/
|
||||
//home/me/tmp/rd/test.html")
|
||||
//.with_url(format!("file://{}/index.html", mme_module_path))
|
||||
//.with_html("hello worldddddddddddddddddddddddddddddddddd".to_owned())
|
||||
//.with_initialization_script(init_script.as_str())
|
||||
.with_custom_protocol(
|
||||
"wry".into(),
|
||||
move | request| {
|
||||
|
||||
// the body will be a mize message as a string
|
||||
if request.method() == &Method::POST {
|
||||
let msg_str = request.headers().get("MizeMsg").unwrap().to_str().unwrap();
|
||||
|
||||
println!("webview_con incoming got msg: {}", msg_str);
|
||||
|
||||
let msg = match msg_from_string(msg_str.to_owned(), conn_id) {
|
||||
Ok(val) => val,
|
||||
Err(err) => {
|
||||
self_clone_two.mize.report_err(err.into());
|
||||
return http::Response::builder()
|
||||
.header(CONTENT_TYPE, "text/plain")
|
||||
.status(500)
|
||||
.body("".to_string().as_bytes().to_vec())
|
||||
.unwrap()
|
||||
.map(Into::into);
|
||||
},
|
||||
};
|
||||
|
||||
self_clone_two.mize.got_msg(msg);
|
||||
|
||||
|
||||
return http::Response::builder()
|
||||
.header(CONTENT_TYPE, "text/plain")
|
||||
.status(http::StatusCode::OK)
|
||||
.body("".to_string().as_bytes().to_vec())
|
||||
.unwrap()
|
||||
.map(Into::into);
|
||||
}
|
||||
|
||||
match get_wry_response(request, self_clone_two.clone()) {
|
||||
Ok(r) => r.map(Into::into),
|
||||
Err(e) => {
|
||||
println!("get_wry_response error: {}", e);
|
||||
http::Response::builder()
|
||||
.header(CONTENT_TYPE, "text/plain")
|
||||
.status(500)
|
||||
.body(e.to_string().as_bytes().to_vec())
|
||||
.unwrap()
|
||||
.map(Into::into)
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
// tell the webview to load the custom protocol
|
||||
.with_url("wry://localhost")
|
||||
//.with_ipc_handler(move | res: Request<String> | {
|
||||
//crate::implementors::html::webview_con::ipc_handler(res, self_clone.clone(), conn_id)
|
||||
//})
|
||||
//.with_html(html_str)
|
||||
/*
|
||||
.with_drag_drop_handler(|e| {
|
||||
match e {
|
||||
wry::DragDropEvent::Enter { paths, position } => {
|
||||
println!("DragEnter: {position:?} {paths:?} ")
|
||||
}
|
||||
wry::DragDropEvent::Over { position } => println!("DragOver: {position:?} "),
|
||||
wry::DragDropEvent::Drop { paths, position } => {
|
||||
println!("DragDrop: {position:?} {paths:?} ")
|
||||
}
|
||||
wry::DragDropEvent::Leave => println!("DragLeave"),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
true
|
||||
})
|
||||
*/
|
||||
.build()?;
|
||||
//_webview.open_devtools();
|
||||
println!("{}", webview.url().unwrap());
|
||||
let req = Request::builder()
|
||||
.uri(webview.url().unwrap().to_string())
|
||||
.body("hooooooooooooo")
|
||||
.unwrap();
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let settings = Settings::builder()
|
||||
.allow_file_access_from_file_urls(true)
|
||||
.enable_developer_extras(true)
|
||||
.build();
|
||||
let __webview = webview.webview();
|
||||
__webview.set_settings(&settings);
|
||||
|
||||
let inspector = __webview.inspector().expect("no inspector");
|
||||
inspector.show();
|
||||
}
|
||||
|
||||
|
||||
crate::implementors::html::webview_con::mme_setup_weview_con_host(self, rx, event_loop_proxy)?;
|
||||
let cloned_self = self.clone();
|
||||
|
||||
|
||||
// this is where we block the main thread....
|
||||
event_loop.run(move |event, _, control_flow| {
|
||||
*control_flow = ControlFlow::Wait;
|
||||
|
||||
match event {
|
||||
Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => {
|
||||
*control_flow = ControlFlow::Exit
|
||||
},
|
||||
|
||||
Event::UserEvent::<MizeMessage>(msg) => {
|
||||
match msg_to_string(msg) {
|
||||
Ok(msg_string) => {
|
||||
webview.evaluate_script(format!("mize.mod.mme.webview_msg_recv_fn({})", msg_string).as_str());
|
||||
},
|
||||
Err(err) => {
|
||||
cloned_self.mize.report_err(err.into());
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
_ => {},
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
#[cfg(features = "qt")]
|
||||
pub fn create_qt_slot(&self) -> MizeResult<()> {
|
||||
unsafe {
|
||||
|
||||
let backend = i_slint_backend_qt::Backend::new();
|
||||
|
||||
|
||||
let main_widget = qt_widgets::QWidget::new_0a();
|
||||
main_widget.show();
|
||||
main_widget.set_window_title(&qs("mme_main"));
|
||||
|
||||
|
||||
|
||||
comandr::platform::qt::init(main_widget.as_ptr());
|
||||
|
||||
//let other_window = OtherWindow::new().unwrap();
|
||||
//other_window.show();
|
||||
|
||||
let presenter: Presenter = Presenter::HtmlPresenter(HtmlPresenter::from_folder(Path::new("/home/me/work/mme-presenters/presenters/hello-world").to_owned())?);
|
||||
|
||||
let mut slot: Slot = Slot::QtWidgetSlot(QtWidgetSlot::from_widget(main_widget)?);
|
||||
|
||||
slot.load(presenter);
|
||||
|
||||
|
||||
println!("run_event_loop");
|
||||
unsafe {
|
||||
qt_core::QCoreApplication::exec();
|
||||
}
|
||||
//backend.run_event_loop();
|
||||
//unsafe {
|
||||
//run_my_event_loop(my_app);
|
||||
//}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(feature = "target-os")]
|
||||
use tao::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
window::WindowBuilder,
|
||||
};
|
||||
#[cfg(feature = "target-os")]
|
||||
use wry::{
|
||||
http::{self, header::CONTENT_TYPE, Request, Response},
|
||||
WebViewBuilder,
|
||||
};
|
||||
|
||||
#[cfg(feature = "target-os")]
|
||||
fn get_wry_response(request: Request<Vec<u8>>, mut mme: Mme) -> Result<http::Response<Vec<u8>>, Box<dyn std::error::Error>> {
|
||||
use comandr::core::module;
|
||||
use mize::item::ItemData;
|
||||
use mize::error::MizeResultTrait;
|
||||
|
||||
|
||||
|
||||
|
||||
let mut path = PathBuf::from(request.uri().path());
|
||||
|
||||
let root = if path.starts_with("/modules") {
|
||||
let mod_name = path.iter().nth(2).unwrap().to_str().unwrap();
|
||||
println!("get_wry_response: modname: {}", mod_name);
|
||||
let mod_dir = PathBuf::from(mme.mize.fetch_module(format!("cross.wasm32-none-unknown.{}", mod_name).as_str()).unwrap());
|
||||
mod_dir
|
||||
} else {
|
||||
PathBuf::from(mme.mize.fetch_module("cross.wasm32-none-unknown.mme").unwrap())
|
||||
};
|
||||
|
||||
let mut module_dir_conf: ItemData = mme.mize.get("self/config/module_dir/cross/wasm32-none-unknown").as_std()?.as_data_full().as_std()?;
|
||||
let mut module_dir_str = String::new();
|
||||
if !module_dir_conf.cbor().is_null() {
|
||||
let map = module_dir_conf.cbor().as_map().ok_or(mize_err!("self/config/module_dir was not a map")).as_std()?;
|
||||
for (mod_name, module_dir) in map {
|
||||
let mod_name_str = mod_name.as_text().ok_or(mize_err!("mod_name was not a string")).as_std()?;
|
||||
module_dir_str += format!(r#" "{mod_name_str}": "wry://localhost/modules/{mod_name_str}", "#).as_str();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
let index_html = format!(r#"
|
||||
<html>
|
||||
<head>
|
||||
<script>
|
||||
import("/modules/mize/mize.js").then( module => module.init_mize({{
|
||||
module_dir: {{ {module_dir_str} }},
|
||||
load_modules: "mme",
|
||||
module_url: "wry://localhost/modules"
|
||||
}}))
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
MME loading...
|
||||
</body>
|
||||
</html>
|
||||
"#);
|
||||
|
||||
let path = if path == PathBuf::from("/") {
|
||||
// return the index.html
|
||||
return Response::builder()
|
||||
.header(CONTENT_TYPE, "text/html")
|
||||
.body(index_html.into_bytes())
|
||||
.map_err(Into::into);
|
||||
|
||||
} else if path.starts_with("/modules") {
|
||||
path.iter().skip(3).collect()
|
||||
} else {
|
||||
// removing leading slash
|
||||
let mut string = path.into_os_string().into_string().unwrap();
|
||||
string.remove(0);
|
||||
PathBuf::from(string)
|
||||
};
|
||||
|
||||
println!("root: {}", root.display());
|
||||
println!("path: {}", path.display());
|
||||
let content = std::fs::read(std::fs::canonicalize(root.join(path.as_path()))?)?;
|
||||
let path_str = path.as_os_str().to_str().unwrap();
|
||||
|
||||
// Return asset contents and mime types based on file extentions
|
||||
// If you don't want to do this manually, there are some crates for you.
|
||||
// Such as `infer` and `mime_guess`.
|
||||
let mimetype = if path_str.ends_with(".html") || path == PathBuf::from("/") {
|
||||
"text/html"
|
||||
} else if path_str.ends_with(".js") {
|
||||
"text/javascript"
|
||||
} else if path_str.ends_with(".png") {
|
||||
"image/png"
|
||||
} else if path_str.ends_with(".wasm") {
|
||||
"application/wasm"
|
||||
} else {
|
||||
"text/html"
|
||||
};
|
||||
println!("mimetype: {}", mimetype);
|
||||
|
||||
Response::builder()
|
||||
.header(CONTENT_TYPE, mimetype)
|
||||
.body(content)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
use enum_dispatch::enum_dispatch;
|
||||
|
||||
use crate::implementors::html::HtmlPresenter;
|
||||
|
||||
|
||||
// A Presenter takes data (in the form of MiZe Items) and presents them in the form of a gui.
|
||||
// It can be put into a Space and provide sub Spaces, where other Presenters can be put into.
|
||||
// It can provide different implementations for the different types of spaces
|
||||
#[enum_dispatch]
|
||||
pub trait PresenterTrait {
|
||||
}
|
||||
|
||||
#[enum_dispatch(PresenterTrait)]
|
||||
pub enum Presenter {
|
||||
HtmlPresenter,
|
||||
}
|
||||
|
||||
impl Presenter {
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
use enum_dispatch::enum_dispatch;
|
||||
|
||||
#[cfg(features = "slint")]
|
||||
use crate::implementors::slint_widget::SlintWidget;
|
||||
|
||||
#[cfg(features = "qt")]
|
||||
use crate::implementors::qt_widget::QtWidgetSlot;
|
||||
|
||||
use crate::implementors::html::HtmlSlot;
|
||||
|
||||
use crate::presenter::Presenter;
|
||||
use mize::MizeResult;
|
||||
|
||||
// common behaviour for all SlotTypes
|
||||
#[enum_dispatch]
|
||||
pub trait SlotTrait {
|
||||
fn load(&mut self, presenter: Presenter) -> MizeResult<()>;
|
||||
|
||||
//pub fn load_html(pressenter: HtmlPresenter) -> MizeResult<()> {}
|
||||
}
|
||||
|
||||
// this is the main type of this project
|
||||
// a Widget represents any kind of "screen realestate"
|
||||
// be it a Webview, slint widget, Xwindow, ...
|
||||
|
||||
// an enum over all of what types such "screen realestate" could have
|
||||
#[enum_dispatch(SlotTrait)]
|
||||
pub enum Slot {
|
||||
//Xwindow {},
|
||||
//WaylandWindow {},
|
||||
//SlintWidget,
|
||||
#[cfg(features = "qt")]
|
||||
QtWidgetSlot,
|
||||
//GtkWidget {},
|
||||
HtmlSlot,
|
||||
//QuarzWindow {},
|
||||
//NtWindow {},
|
||||
//Activity {},
|
||||
}
|
||||
|
||||
|
||||
pub struct Position {
|
||||
x: u32,
|
||||
y: u32,
|
||||
z: u32,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
<html>
|
||||
<head>
|
||||
<!-- script src="https://c2vi.dev/mize/wasm32-none-unknown/mize.js"></script --!>
|
||||
<script src="file:///home/me/work/mize/pkg/mize.js"></script>
|
||||
<script>
|
||||
console.log("from script")
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
hello world...............
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,20 +0,0 @@
|
||||
{ mize_url, ... }: ''
|
||||
<html>
|
||||
<head>
|
||||
<script src="${mize_url}"></script>
|
||||
<script>
|
||||
init_mize({
|
||||
load_modules: "mme",
|
||||
mod: {
|
||||
mme: {
|
||||
webview_con: true
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
hello world...............
|
||||
</body>
|
||||
</html>
|
||||
''
|
||||
@@ -1,162 +0,0 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
use comandr::Comandr;
|
||||
|
||||
use crate::slot::SlotTrait;
|
||||
use crate::mme::Mme;
|
||||
use mize::MizeResult;
|
||||
|
||||
pub mod webview_con;
|
||||
|
||||
|
||||
pub struct HtmlPresenter {
|
||||
pub path: PathBuf,
|
||||
}
|
||||
|
||||
impl HtmlPresenter {
|
||||
pub fn from_folder(path: PathBuf) -> MizeResult<HtmlPresenter> {
|
||||
Ok(HtmlPresenter { path })
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
pub struct HtmlSlot {
|
||||
}
|
||||
|
||||
impl SlotTrait for HtmlSlot {
|
||||
fn load(&mut self,presenter:crate::presenter::Presenter) -> MizeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(feature = "wasm-target")]
|
||||
pub mod wasm {
|
||||
|
||||
use comandr::Comandr;
|
||||
use comandr::Command;
|
||||
use web_sys::console;
|
||||
use web_sys::EventTarget;
|
||||
use web_sys::js_sys::Function;
|
||||
use std::panic;
|
||||
use std::ptr::NonNull;
|
||||
use std::slice::Iter;
|
||||
use comandr::Module;
|
||||
use comandr::ComandrResult;
|
||||
|
||||
use crate::mme::Mme;
|
||||
|
||||
// console log
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
use super::webview_con::msg_from_string;
|
||||
#[wasm_bindgen]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(js_namespace = console)]
|
||||
fn log(s: &str);
|
||||
}
|
||||
macro_rules! console_log {
|
||||
// Note that this is using the `log` function imported above during
|
||||
// `bare_bones`
|
||||
($($t:tt)*) => (log(&format_args!($($t)*).to_string()))
|
||||
}
|
||||
// end of console log
|
||||
|
||||
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
|
||||
// allocator.
|
||||
#[cfg(feature = "wee_alloc")]
|
||||
#[global_allocator]
|
||||
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub struct MmeJs {
|
||||
pub inner: NonNull<Mme>,
|
||||
pub webview_con_id: u64,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl MmeJs {
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub unsafe fn webview_msg_recv_fn(&mut self, msg_string: String) -> () {
|
||||
|
||||
let mize = &self.inner.as_mut().mize;
|
||||
|
||||
let msg = match msg_from_string(msg_string, self.webview_con_id) {
|
||||
Ok(val) => val,
|
||||
Err(err) => {
|
||||
mize.report_err(err.into());
|
||||
return;
|
||||
},
|
||||
};
|
||||
|
||||
mize.got_msg(msg);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub unsafe fn comandr_search(&mut self, string: String) -> Vec<String> {
|
||||
//self.inner.as_mut().comandr.search(string)
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
pub unsafe fn comandr_list(&mut self) -> Vec<String> {
|
||||
//self.inner.as_mut().comandr.list_commands()
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub unsafe fn comandr_run(&mut self, name: String, args: Vec<String>) -> () {
|
||||
//self.inner.as_mut().comandr.execute(name, args)
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
pub struct MmeComandrModule {
|
||||
commands: Vec<Command>
|
||||
}
|
||||
|
||||
fn reload_page() -> ComandrResult<()>{
|
||||
let js_fn_str = r#"
|
||||
window.location.reload()
|
||||
"#;
|
||||
let js_fn = Function::new_no_args(js_fn_str);
|
||||
|
||||
js_fn.call0(&web_sys::wasm_bindgen::JsValue::NULL);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl MmeComandrModule {
|
||||
pub fn new() -> MmeComandrModule {
|
||||
let commands = vec![
|
||||
Command { name: "reload".to_owned(), closure: Box::new(reload_page) },
|
||||
];
|
||||
MmeComandrModule { commands }
|
||||
}
|
||||
}
|
||||
|
||||
impl Module for MmeComandrModule {
|
||||
fn name(&self) -> String {
|
||||
"mme".to_owned()
|
||||
}
|
||||
|
||||
fn commands(&self) -> Iter<'_, Command> {
|
||||
self.commands.iter()
|
||||
}
|
||||
|
||||
fn get_command(&mut self, name: String) -> Option<&mut Command> {
|
||||
for command in self.commands.iter_mut() {
|
||||
if command.name == name {
|
||||
return Some(command);
|
||||
}
|
||||
}
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
use base64::Engine;
|
||||
use mize::{mize_err, MizeResult};
|
||||
use mize::proto::MizeMessage;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use tracing::trace;
|
||||
use ciborium::Value as CborValue;
|
||||
use flume::{ Receiver, Sender };
|
||||
use ciborium_io::Read;
|
||||
|
||||
#[cfg(feature = "target-os")]
|
||||
use wry::http::Request;
|
||||
|
||||
#[cfg(feature = "target-os")]
|
||||
use wry::WebView;
|
||||
|
||||
#[cfg(feature = "target-os")]
|
||||
use tao::event_loop::EventLoopProxy;
|
||||
|
||||
#[cfg(feature = "wasm-target")]
|
||||
use crate::implementors::html::wasm::MmeJs;
|
||||
|
||||
#[cfg(feature = "wasm-target")]
|
||||
use web_sys::js_sys::Function;
|
||||
|
||||
#[cfg(feature = "wasm-target")]
|
||||
use wasm_bindgen::JsValue;
|
||||
|
||||
|
||||
|
||||
// console_log macro
|
||||
// that can be copied into other files for debugging purposes
|
||||
#[cfg(feature = "wasm-target")]
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
#[cfg(feature = "wasm-target")]
|
||||
#[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())})
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
use crate::mme::Mme;
|
||||
use mize::MizeError;
|
||||
|
||||
|
||||
|
||||
#[cfg(feature = "target-os")]
|
||||
pub fn mme_setup_weview_con_host(mme: &mut Mme, rx: Receiver<MizeMessage>, event_loop_proxy: EventLoopProxy<MizeMessage>) -> MizeResult<()> {
|
||||
|
||||
let mize_clone = mme.mize.clone();
|
||||
mme.mize.spawn("webview-con-outgoing", move || {
|
||||
for msg in rx {
|
||||
event_loop_proxy.send_event(msg);
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
|
||||
#[cfg(feature = "wasm-target")]
|
||||
pub fn mme_setup_webiew_con_js(mme: &mut Mme) -> MizeResult<Sender<MizeMessage>> {
|
||||
let (tx, rx): (Sender<MizeMessage>, Receiver<MizeMessage>) = flume::unbounded();
|
||||
|
||||
// send things from rx out by calling window.ipc.postMessage("msg here as string")
|
||||
wasm_bindgen_futures::spawn_local(webview_con_js_send_out(mme.clone(), rx));
|
||||
|
||||
let conn_id = mme.mize.new_connection_join_namespace(tx.clone())?;
|
||||
|
||||
return Ok(tx);
|
||||
}
|
||||
|
||||
|
||||
#[cfg(feature = "wasm-target")]
|
||||
pub async fn webview_con_js_send_out(mme: Mme, rx: Receiver<MizeMessage>) {
|
||||
let func = Function::new_with_args("msg_string", r#"
|
||||
fetch("/msg", { method: "POST", headers: { MizeMsg: msg_string}})
|
||||
"#);
|
||||
|
||||
loop {
|
||||
let msg = match rx.recv_async().await {
|
||||
Ok(val) => val,
|
||||
Err(err) => { mme.mize.report_err(err.into()); continue; },
|
||||
};
|
||||
console_log!("webview_con_js_send_out: got_msg: {:?}", msg);
|
||||
|
||||
let msg_string = match msg_to_string(msg) {
|
||||
Ok(val) => val,
|
||||
Err(err) => { mme.mize.report_err(err.into()); continue; },
|
||||
};
|
||||
|
||||
func.call1(&JsValue::null(), &JsValue::from_str(msg_string.as_str()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub fn msg_to_string(msg: MizeMessage) -> MizeResult<String> {
|
||||
|
||||
let mut msg_bytes = Vec::new();
|
||||
|
||||
ciborium::into_writer(&msg.value(), &mut msg_bytes)?;
|
||||
|
||||
let msg_string = STANDARD.encode(msg_bytes);
|
||||
|
||||
return Ok(msg_string)
|
||||
}
|
||||
|
||||
|
||||
pub fn msg_from_string(msg_string: String, conn_id: u64) -> MizeResult<MizeMessage> {
|
||||
|
||||
let msg_bytes = STANDARD.decode(msg_string)?;
|
||||
|
||||
let value: CborValue = ciborium::from_reader(msg_bytes.as_slice())?;
|
||||
|
||||
let msg = MizeMessage::new(value, conn_id);
|
||||
|
||||
return Ok(msg);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
use qt_gui::cpp_core::Ptr;
|
||||
use tracing::{error, debug};
|
||||
use qt_core::{qs, QBox, QPointerOfQObject};
|
||||
use qt_widgets::QWidget;
|
||||
use qt_widgets::cpp_core::CppBox;
|
||||
use cpp::cpp;
|
||||
use std::ffi::{CStr, CString};
|
||||
|
||||
use crate::presenter::Presenter;
|
||||
use crate::slot::{Slot, SlotTrait};
|
||||
use mize::MizeResult;
|
||||
|
||||
|
||||
pub struct HtmlAdapter {
|
||||
}
|
||||
|
||||
impl HtmlAdapter {
|
||||
pub fn sub_slot(&self) -> MizeResult<Slot> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct QtWidgetSlot {
|
||||
widget: QBox<QWidget>,
|
||||
}
|
||||
|
||||
impl QtWidgetSlot {
|
||||
pub fn from_widget(widget: QBox<QWidget>) -> MizeResult<QtWidgetSlot> {
|
||||
Ok(QtWidgetSlot { widget })
|
||||
}
|
||||
}
|
||||
|
||||
cpp! {{
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <cstdio>
|
||||
#include <QtWidgets/QApplication>
|
||||
#include <QtWidgets/QMainWindow>
|
||||
#include <QtWidgets/QPushButton>
|
||||
#include <QtWidgets/QGridLayout>
|
||||
#include <QtCore/QPointer>
|
||||
#include <QtCore/QDebug>
|
||||
#include <QtCore/QTimer>
|
||||
|
||||
//#include <QtWebEngine/QtWebEngine>
|
||||
#include <QtWebEngineWidgets/QWebEngineView>
|
||||
#include <QtCore/QUrl>
|
||||
|
||||
}}
|
||||
|
||||
impl SlotTrait for QtWidgetSlot {
|
||||
fn load(&mut self, presenter: Presenter) -> MizeResult<()> {
|
||||
match presenter {
|
||||
Presenter::HtmlPresenter(html) => {
|
||||
// here would go the code, to load the index.html of the HtmlPresenter's path into
|
||||
// the self.widget....
|
||||
println!("loading html into widget....");
|
||||
let url = format!("file://{}/index.html", html.path.display());
|
||||
|
||||
let c_string: CString = CString::new(url.as_str()).unwrap();
|
||||
let c_str: &CStr = c_string.as_c_str();
|
||||
|
||||
unsafe {
|
||||
create_webview(self.widget.as_ptr(), c_str.as_ptr());
|
||||
|
||||
self.widget.set_style_sheet(&qs("border: 2px solid blue;"));
|
||||
|
||||
|
||||
//let widget_full = QWidget::new_0a();
|
||||
//let widget = widget_full.as_raw_ptr();
|
||||
//
|
||||
//widget_fill(&mut self.widget);
|
||||
|
||||
//cpp_widget_fill(&mut self.widget);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" { fn create_webview(widget: Ptr<QWidget>, url: * const i8); }
|
||||
|
||||
pub unsafe fn widget_fill(widget: &mut QBox<QWidget>) {
|
||||
let grid_layout = unsafe { qt_widgets::QGridLayout::new_0a() };
|
||||
widget.set_layout(&grid_layout);
|
||||
|
||||
let button = unsafe { qt_widgets::QPushButton::new() };
|
||||
button.set_text(&qs("hello from rust button"));
|
||||
|
||||
let button2 = unsafe { qt_widgets::QPushButton::new() };
|
||||
button2.set_text(&qs("hello from another button"));
|
||||
|
||||
grid_layout.add_widget_3a(&button, 0, 1);
|
||||
grid_layout.add_widget_3a(&button2, 1, 0);
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
pub unsafe fn cpp_widget_fill(widget: &mut QBox<QWidget>) {
|
||||
let a: i32 = 5;
|
||||
let widget = widget.as_raw_ptr();
|
||||
|
||||
let x: i32 = cpp!(unsafe [widget as "QWidget*", a as "int32_t"] -> i32 as "int32_t" {
|
||||
|
||||
printf("hello from macro\n");
|
||||
|
||||
//QWidget * mywidget = new QWidget();
|
||||
|
||||
//QUrl url;
|
||||
//url.setScheme("http");
|
||||
//url.setHost("www.orf.at");
|
||||
|
||||
//QWebEngineView view = QWebEngineView(widget);
|
||||
//view.setUrl(url);
|
||||
//view.resize(1024, 750);
|
||||
//view.show();
|
||||
|
||||
/*
|
||||
QGridLayout *layout = new QGridLayout(widget);
|
||||
widget->setLayout(layout);
|
||||
|
||||
QPushButton * button = new QPushButton(widget);
|
||||
button->setText("My text");
|
||||
button->setToolTip("A tooltip");
|
||||
|
||||
QPushButton * button2 = new QPushButton(widget);
|
||||
button2->setText("My text 2");
|
||||
button2->setToolTip("A tooltip 2");
|
||||
|
||||
QPushButton * button3 = new QPushButton(widget);
|
||||
button3->setText("My text 3");
|
||||
button3->setToolTip("A tooltip 3");
|
||||
|
||||
layout->addWidget (button, 0, 0);
|
||||
layout->addWidget (button2, 0, 1);
|
||||
layout->addWidget (button3, 1, 1);
|
||||
*/
|
||||
|
||||
widget->show();
|
||||
|
||||
return a;
|
||||
});
|
||||
}
|
||||
*/
|
||||
|
||||
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user