basic get command works with items from 0/config defined in test-config.toml

This commit is contained in:
Sebastian Moser
2024-05-30 14:59:47 +02:00
parent 557ac09bc7
commit 38f967db76
23 changed files with 402 additions and 120 deletions

View File

@@ -103,7 +103,13 @@ impl MizeError {
}
pub fn log(self) -> MizeError {
error!("MizeError encountered: {}", self.messages.join("\n"));
error!("MizeError envountered!");
if let Some(ref location) = self.code_location {
error!("[ {} ] {}", "LOCATION".yellow(), location);
};
for msg in &self.messages {
error!("[ {} ] {}", "MSG".yellow(), msg);
}
self
}
@@ -209,7 +215,9 @@ impl<T, E, S> IntoMizeResult<T, S> for Result<T, E> where E: std::fmt::Display {
match self {
Ok(val) => MizeResult::Ok(val),
Err(err) => MizeResult::Err(MizeError::new().category("misc").msg(format!("From any Error: {}", err))),
Err(err) => MizeResult::Err(MizeError::new()
.category("misc")
.msg(format!("From {}: {}", std::any::type_name_of_val(&err), err))),
}
}
#[track_caller]
@@ -217,7 +225,10 @@ impl<T, E, S> IntoMizeResult<T, S> for Result<T, E> where E: 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 any Error: {}", err))),
Err(err) => MizeResult::Err(MizeError::new()
.category("misc")
.msg(format!("{}", msg))
.msg(format!("From {}: {}", std::any::type_name_of_val(&err), err))),
}
}
}

View File

@@ -1,13 +1,34 @@
use std::hash::Hash;
use core::fmt;
use std::{fmt::write, hash::Hash};
#[derive(Hash, Eq, PartialEq)]
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct MizeId {
path: Vec<String>
}
impl From<String> for MizeId {
fn from(value: String) -> Self {
MizeId{path: vec![value]}
impl MizeId {
pub fn store_part(&self) -> &str {
self.path.first()
.expect("an empty MizeId found, that should absolutely not be possible!!!!").as_str()
}
pub fn as_vec(self) -> Vec<String> {
self.path
}
}
impl fmt::Display for MizeId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.path.join("/"))
}
}
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 { path }
}
}

View File

@@ -1,5 +1,7 @@
use core::fmt;
use std::collections::HashMap;
use std::fs::create_dir;
use std::sync::{Arc, Mutex};
use log::{trace, debug, info, warn, error};
use uuid::Uuid;
use std::fs::File;
@@ -21,15 +23,17 @@ pub mod subscription;
static MSG_CHANNEL_SIZE: usize = 200;
/// The Instance type is the heart of the mize system
#[derive(Clone)]
pub struct Instance<S: Store> {
// question vec of stores???
// would mean replication logic and such things is handeled by the instance
// i think it would be better thogh to then implement a ReplicatedStore
store: S,
peers: Vec<Box<dyn Connection>>,
subs: HashMap<MizeId, Subscription>
pub store: S,
peers: Arc<Mutex<Vec<Box<dyn Connection>>>>,
subs: Arc<Mutex<HashMap<MizeId, Subscription>>>,
}
/*
pub enum RealmId {
Uuid(Uuid),
@@ -38,21 +42,27 @@ pub enum RealmId {
}
*/
impl<S: Store> Instance<S> {
// new() opens a
pub async fn new() -> MizeResult<Instance<MemStore>> {
impl Instance<MemStore> {
pub fn new() -> MizeResult<Instance<MemStore>> {
trace!("[ {} ] Instance::new()", "CALL".yellow());
let memstore = MemStore::new();
let instance = Instance {store: memstore, peers: Vec::new(), subs: HashMap::new()};
let instance = Instance {store: memstore, peers: Arc::new(Mutex::new(Vec::new())), subs: Arc::new(Mutex::new(HashMap::new())) };
// platform specific init code
// TODO
if cfg!(feature = "os-target") { // on os platforms
crate::platform::os::os_instance_init(instance.clone())?
}
// end of platform specific init code
return Ok(instance);
}
}
impl<S: Store> Instance<S> {
pub fn new_item(self) -> MizeResult<Item<S>> {
let id = self.store.new_id()?;
return Ok(Item {id, instance: self});
@@ -63,9 +73,14 @@ impl<S: Store> Instance<S> {
}
pub fn set<I: Into<MizeId>, V: Into<ItemData>>(self, id: I, value: V) -> MizeResult<()> {
self.store.set(id.into(), value)
self.store.set(&id.into(), value)
}
}
impl<S: Store> fmt::Debug for Instance<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Mize Instance with subs: {:?}", self.subs,)
}
}

View File

@@ -9,7 +9,7 @@ pub trait Store {
// is implemented, so that there can be a multithreaded implementation
//fn get(self, id: MizeId) -> MizeResult<Item<Self>> where Self: Sized;
fn set<T: Into<ItemData>>(self, id: MizeId, data: T) -> MizeResult<()>;
fn set<T: Into<ItemData>>(self, id: &MizeId, data: T) -> MizeResult<()>;
// in the future should implement transactions, ....
@@ -19,6 +19,8 @@ pub trait Store {
fn get_backlinks(self, item: Item<Self>) -> MizeResult<Vec<MizeId>> where Self: Sized;
fn new_id(&self) -> MizeResult<MizeId>;
fn get_value_raw(&self, id: &MizeId) -> MizeResult<Vec<u8>>;
}
/// references an item that is stored in a store

View File

@@ -1,3 +1,4 @@
#[derive(Debug)]
pub struct Subscription;

View File

@@ -8,10 +8,11 @@ use crate::error::{MizeError, MizeResult, IntoMizeResult};
use crate::instance::Instance;
use crate::instance::store::Store;
use crate::id::MizeId;
use cbor::Cbor as CborValue;
use ciborium::Value as CborValue;
// a item always has to do with a Instance, which takes care of how it is updated
#[derive(Debug)]
pub struct Item<S: Store + Sized> {
pub id: MizeId,
pub instance: Instance<S>
@@ -22,16 +23,31 @@ pub struct Item<S: Store + Sized> {
pub type ItemData = CborValue;
impl<S: Store> Item<S> {
pub fn id(self) -> MizeId {
self.id
pub fn id(&self) -> &MizeId {
&self.id
}
pub fn value_raw(self) -> MizeResult<Vec<u8>> {
pub fn value_raw(&self) -> MizeResult<Vec<u8>> {
// this will call from the instance which gets the value from the store
Ok(Vec::new())
self.instance.store.get_value_raw(&self.id())
}
}
impl<S: Store> Display for Item<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.value_raw() {
Ok(value) => match String::from_utf8(value) {
Ok(string) => write!(f, "{}", string),
Err(_) => write!(f, "{:?}", self.value_raw()),
}
Err(err) => {err.log(); Ok(())},
};
return Ok(());
}
}
/*
#[derive(Debug)]

View File

@@ -1,35 +1,101 @@
use std::collections::HashMap;
use cbor::Cbor as CborValue;
use std::iter::Map;
use std::sync::{Arc, Mutex};
use ciborium::Value as CborValue;
use log::trace;
use crate::id::MizeId;
use crate::instance::store::Store;
use crate::error::MizeResult;
use crate::error::{MizeError, MizeResult, IntoMizeResult};
use crate::item::{Item, ItemData};
#[derive(Clone, Debug)]
pub struct MemStore {
map: HashMap<MizeId, CborValue>,
inner: Arc<Mutex<MemStoreInner>>,
}
#[derive(Debug)]
struct MemStoreInner {
map: HashMap<u64, CborValue>,
next_id: u64,
}
impl Store for MemStore {
fn set<T: Into<ItemData>>(mut self, id: MizeId, data: T) -> MizeResult<()> {
self.map.insert(id, data.into());
fn set<T: Into<ItemData>>(mut self, id: &MizeId, data: T) -> MizeResult<()> {
let mut inner = self.inner.lock()?;
inner.map.insert(id_to_u64(id)?, data.into());
return Ok(())
}
fn get_links(self, item: Item<Self>) -> MizeResult<Vec<MizeId>> {
let inner = self.inner.lock()?;
Ok(Vec::new())
}
fn get_backlinks(self, item: Item<Self>) -> MizeResult<Vec<MizeId>> {
let inner = self.inner.lock()?;
Ok(Vec::new())
}
fn new_id(&self) -> MizeResult<MizeId> {
let id_string = format!("{}", self.next_id);
let inner = self.inner.lock()?;
let id_string = format!("{}", inner.next_id);
return Ok(id_string.into());
}
fn get_value_raw(&self, id: &MizeId) -> MizeResult<Vec<u8>> {
let inner = self.inner.lock()?;
let cbor_val = inner.map.get(&id_to_u64(id)?)
.ok_or(MizeError::new()
.msg(format!("Item with store_part: {}, id: {} does not exist in MemStore", id_to_u64(id)?, id)))?;
let mut id_without_first = id.clone().as_vec();
id_without_first.remove(0);
get_raw_from_cbor(cbor_val.to_owned(), id_without_first)
}
}
impl MemStore {
pub fn new() -> MemStore {
return MemStore { map: HashMap::new(), next_id: 0 };
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> {
id.store_part()
.parse()
.mize_result_msg(format!("Could not parse the store_part of mizeid {} into a u64 for the MemStore", id))
}
fn get_raw_from_cbor(value: CborValue, mut path: Vec<String>) -> MizeResult<Vec<u8>> {
match value {
CborValue::Bytes(vec) => Ok(vec),
CborValue::Text(string) => Ok(string.into_bytes()),
CborValue::Map(map) => {
let mut inner_val: CborValue = CborValue::Null;
trace!("map: {:?}", map);
for (key, val) in map.into_iter() {
let first_path_string = path.first()
.ok_or(MizeError::new().msg("get_raw_from_cbor: path is empty"))?;
if let CborValue::Text(key_text) = key {
if key_text == *first_path_string {
inner_val = val
}
}
}
if inner_val == CborValue::Null {
return Err(MizeError::new().msg(format!("get_raw_from_cbor: Path {} not Found", path.join("/"))))
}
path.remove(0);
get_raw_from_cbor(inner_val, path)
},
_ => Err(MizeError::new().msg("get_raw_from_cbor: value is not Bytes, Text or Map")),
}
}

View File

@@ -1,4 +1,4 @@
use cbor::Cbor as CborValue;
use ciborium::Value as CborValue;
#[derive(Debug, Clone)]
pub struct MizeMessage {