From d3ecfcabf4c8335a0085c65be314799c5ce3f87c Mon Sep 17 00:00:00 2001 From: Sebastian Moser Date: Tue, 31 Jan 2023 23:52:41 +0100 Subject: [PATCH] all MizeError's are now constructed with the new() function instead of with directly with {} --- Cargo.lock | 1 + Cargo.toml | 1 + errorcodes.yml | 68 ---------------------- errors.toml | 86 +++++++++++++++++++++++++++ src/error.rs | 70 +++++++++++++++------- src/server.rs | 28 +++++---- src/server/itemstore.rs | 30 +++------- src/server/proto.rs | 125 +++++++++++++--------------------------- 8 files changed, 203 insertions(+), 206 deletions(-) delete mode 100644 errorcodes.yml create mode 100644 errors.toml diff --git a/Cargo.lock b/Cargo.lock index 18aed31..174250b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1806,6 +1806,7 @@ dependencies = [ "futures-util", "itertools", "json", + "lazy_static", "surrealdb", "tokio", "tokio-stream", diff --git a/Cargo.toml b/Cargo.toml index 96bdbaf..93eb04f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ axum-macros = "0.3.0" futures-util = "0.3.24" itertools = "0.10.5" json = "0.12.4" +lazy_static = "1.4.0" surrealdb = "1.0.0-beta.7" tokio = {version = "1.21.0", features = ["full"]} tokio-stream = "0.1.9" diff --git a/errorcodes.yml b/errorcodes.yml deleted file mode 100644 index 73adefd..0000000 --- a/errorcodes.yml +++ /dev/null @@ -1,68 +0,0 @@ -Not sure yet: - code: 11 - category: "don't know yet" - -Can't delete item 0: - code: 100 - category: "don't know yet" - message: "You can't delete item number 0. This item contains mandatory Config for the Server." - -Error with Surrealdb: - code: 128 - category: "data_storage" - -num_of_items missing in item0: - code: 101 - category: "key_missing::item0::num_of_items" - -next_free_id missing in item0: - code: 102 - category: "key_missing::item0::next_free_id" - -_commit missing in item0: - code: 103 - category: "key_missing::item0::_commit" - -_commit missing: - code: 103 - category: "key_missing::_commit" - -could not read index of item: - code: 104 - category: "data_storage::index_not_found" - -_commit not 8 bytes long: - code: 105 - category: "don't know yet" - -error while parsing int: - code: 106 - category: "parse_error" - -error with message sent to the server: - code: 107 - category: "faulty_message" - -missing metadata: - code: 108 - category: "faulty_message" - -something that should be utf8 valid was not: - code: 109 - category: "faulty_message" - -ParseIntError: - code: 110 - category: "faulty_message" - -_commit can't be updated: - code: 111 - category: "faulty_update" - -no / on the end of id: - code: 112 - category: "faulty_message" - -module header not a String: - code: 113 - category: "don't know yet" diff --git a/errors.toml b/errors.toml new file mode 100644 index 0000000..ed54f65 --- /dev/null +++ b/errors.toml @@ -0,0 +1,86 @@ + +[[error]] +code = 11 +category = "don't know yet" +message = "Something went wrong. Someone was too lazy to define an exact error for that." + +[[error]] +code = 100 +category = "don't know yet" +message = "You can't delete item number 0. This item contains mandatory Config for the Server." + +[[error]] +category = "data_storage" +code = 128 +message = "Something went wrong in the data storage." + +[[error]] +code = 129 +category = "data_storage:surrealdb_error" +message = "Something went wrong internally with the data-storage (surrealdb): {}" + +[[error]] +code = 101 +category = "key_missing::item0::num_of_items" +messate = "num_of_items missing in item0" + +[[error]] +code = 102 +category = "key_missing::item0::next_free_id" +message = "next_free_id missing in item0" + +[[error]] +_commit missing in item0: +code = 103 +category = "key_missing::item0::_commit" + +[[error]] +_commit missing: +code = 103 +category = "key_missing::_commit" + +[[error]] +code = 104 +category = "data_storage::index_not_found" +message = "could not read index of item" + +[[error]] +code = 105 +category = "don't know yet" +message = "_commit not 8 bytes long" + +[[error]] +code = 106 +category = "parse_error" +message = "error while parsing to an int" + +[[error]] +code = 107 +category = "faulty_message" +message = "some error with message sent to the server" + +[[error]] +code = 108 +category = "faulty_message" +message = "There was not metadata in a message, that should have some." + +[[error]] +code = 109 +category = "faulty_message" +message = "something that should be utf8 valid was not" + +[[error]] +code = 111 +category = "faulty_update" +message = "mize-commit can't be updated manually" + +[[error]] +code = 113 +category = "don't know yet" +message = "module header not a String" + +[[error]] +code 114 +category = "error with error system" +message = "the error with code {} was not found in the errors.toml file" + diff --git a/src/error.rs b/src/error.rs index ffe74f2..61a99d2 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,24 +1,63 @@ +use std::collections::HashMap; use std::string::FromUtf8Error; +lazy_static::lazy_static! { + static ref ERRORS: HashMap = parse_errors(); +} + +fn parse_errors() -> HashMap{ + let toml_string = include_str!("../errors.toml"); +} + use json; +use toml; use crate::server::proto; + #[derive(Debug, Clone)] pub struct MizeError { - pub kind: String, + pub category: String, pub code: u32, pub message: String, + pub extra_msg: Option, } impl MizeError { + pub fn new(code: u32) -> MizeError { + //let error = ERRORS. + + MizeError { + category: "error with error system".to_string(), + code: 114, + message: "The error with code {} was not found in the errors.toml file".to_string(), + extra_msg: None + } + } + +// pub fn format(&self, values: [str]){ +// } + + pub fn extra_msg(mut self, msg: &str) -> MizeError{ + self.extra_msg = Some(msg.to_string()); + return self; + } + pub fn to_json(self: MizeError) -> json::JsonValue{ - let data = json::object!{ - kind: self.kind, - code: self.code, - message: self.message, - }; - return data; + if let Some(extra_msg) = self.extra_msg { + json::object!{ + category: self.category, + code: self.code, + message: self.message, + extra_msg: extra_msg, + } + } else { + json::object!{ + category: self.category, + code: self.code, + message: self.message, + } + } } pub fn to_message(self: MizeError, origin: proto::Origin) -> proto::Message { @@ -27,28 +66,17 @@ impl MizeError { msg.extend(json::stringify(data).into_bytes()); return proto::Message::from_bytes(msg, origin); } + } impl From for MizeError { fn from(utf_err: FromUtf8Error) -> MizeError{ - let err = MizeError { - code: 109, - kind: "faulty_message".to_string(), - message: "std::string::FromUtf8Error while parsing something from the message".to_string(), - }; - return err; + MizeError::new(109).extra_msg("std::string::FromUtf8Error while parsing something from the message") } } impl From for MizeError { fn from(sur_err: surrealdb::Error) -> MizeError{ - let cat = format!("data-storage:surrealdb:{:?}", sur_err); - let msg = format!("Something went wrong internally with the data-storage:surrealdb: {}", sur_err); - let err = MizeError { - code: 128, - kind: cat, - message: msg, - }; - return err; + MizeError::new(129) } } diff --git a/src/server.rs b/src/server.rs index a6d29d7..1c632e3 100644 --- a/src/server.rs +++ b/src/server.rs @@ -9,6 +9,7 @@ use futures_util::{FutureExt, StreamExt, SinkExt}; use std::collections::HashMap; use std::boxed::Box; use std::path::Path; +use crate::error; use crate::error::MizeError; use tokio::sync::mpsc::{Sender, channel, Receiver}; @@ -133,6 +134,10 @@ impl Mutexes { } } +fn test(){ + println!("test func"); +} + #[tokio::main] pub async fn run_server(args: Vec) { /* @@ -152,6 +157,13 @@ pub async fn run_server(args: Vec) { } } + //load the errors.toml file and init the error system + //let error_toml_file = include_str!("../errors.toml"); + //println!("ERRORS: {:?}", crate::error::ERRORS); + error::init(); + println!("hello in run_server"); + test(); + //create the itemstore let itemstore = crate::server::itemstore::Itemstore::new(mize_folder.clone() + "/db").await.expect("error creating itemstore"); @@ -335,11 +347,9 @@ async fn handle_websocket_connection( if let Ok(name) = mod_header_val.to_str() { module.name = name.to_string(); } else { - let err = MizeError{ - code: 113, - kind: "don't know yet".to_string(), - message: "The mize-module Header could not be decoded into a String.".to_string(), - }; + let err = MizeError::new(113) + .extra_msg("The mize-module Header could not be decoded into a String."); + msg_tx.send(err.to_message(proto::Origin::Module(module.clone()))).await; return; }; @@ -389,11 +399,9 @@ async fn handle_websocket_connection( } } _ => { - let err = MizeError{ - code: 11, - kind: "don't know yet".to_string(), - message: "the message type was not Binary".to_string(), - }; + let err = MizeError::new(11) + .extra_msg("the message type was not Binary"); + msg_tx.send(err.to_message(origin.clone())).await; vec![0] }, diff --git a/src/server/itemstore.rs b/src/server/itemstore.rs index 4f433a0..66b5923 100644 --- a/src/server/itemstore.rs +++ b/src/server/itemstore.rs @@ -94,11 +94,8 @@ impl Itemstore { let mut old_keys = match tr.get(format!("{}", update.id).into_bytes()).await? { Some(keys) => decode(keys), None => { - return Err(MizeError{ - code: 104, - kind: "data_storage::index_not_found".to_string(), - message: "Internal Datastorage Error: the Index of the Item was not found".to_string(), - }); + return Err(MizeError::new(104) + .extra_msg("Internal Datastorage Error: the Index of the Item was not found")); }, }; @@ -146,12 +143,8 @@ impl Itemstore { let id_u64: u64 = match id_str.parse() { Ok(id) => id, Err(err) => { - return Err(MizeError { - code: 110, - kind: "faulty_message".to_string(), - message: format!("std::num::ParseIntError while parsing id \"{}\" into an Integer", id_str), - - }); + return Err(MizeError::new(110) + .extra_msg("std::num::ParseIntError while parsing id \"{}\" into an Integer")); } }; let mut tr = self.db.transaction(true, true).await?; @@ -162,11 +155,9 @@ impl Itemstore { tr.del(key).await?; } } else { - return Err(MizeError{ - code: 104, - kind: "data_storage::index_not_found".to_string(), - message: "Internal Datastorage Error: the Index of the Item was not found, This means most likely that this item does not exist.".to_string(), - }); + return Err(MizeError::new(104) + .extra_msg("Internal Datastorage Error: the Index of the Item was not found, \ + This means most likely that this item does not exist.")); } tr.del(id_str.into_bytes()).await?; @@ -197,11 +188,8 @@ impl Itemstore { }; return Ok(item); } else { - return Err(MizeError{ - code: 104, - kind: "data_storage::index_not_found".to_string(), - message: "Internal Datastorage Error: the Index of the Item was not found".to_string(), - }); + return Err(MizeError::new(104) + .extra_msg("Internal Datastorage Error: the Index of the Item was not found")); } return Ok(item); } diff --git a/src/server/proto.rs b/src/server/proto.rs index 4947afe..7de692c 100644 --- a/src/server/proto.rs +++ b/src/server/proto.rs @@ -126,11 +126,7 @@ pub enum DeltaCmd { impl Delta { pub fn from_bytes(bytes: Vec) -> Result { - let out_of_bytes = Err(MizeError{ - code: 107, - kind: "faulty_message".to_string(), - message: "There were not eneough Bytes in the message to complete a Delta.".to_string() - }); + let out_of_bytes = Err(MizeError::new(107).extra_msg("There were not eneough Bytes in the message to complete a Delta.")); let mut bytes = bytes.iter(); let mut delta = Delta{raw: Vec::new()}; @@ -183,11 +179,9 @@ impl Delta { delta.raw.push(DeltaCmd::Delete(start, stop)); }, _ => { - return Err(MizeError{ - code: 107, - kind: "faulty_message".to_string(), - message: format!("The update message included a DeltaCmd of {}, only 0,1,2 (for: replace, insert, delete) are allowed.",cmd) - }); + return Err(MizeError::new(107) + .extra_msg(&format!("The update message included a DeltaCmd of {}.\ + Only 0,1,2 (for: replace, insert, delete) are allowed.", cmd))); }, } }; @@ -203,11 +197,9 @@ impl Update { let id_u64 = match id.parse::(){ Ok(id) => id, Err(err) => { - return Err(MizeError{ - code: 11, - kind: "don't know yet".to_string(), - message: "Error while parsing id to u64 (std::num::ParseIntError) in order to get it from the itemstore. (get or get_sub message)".to_string(), - }); + return Err(MizeError::new(11) + .extra_msg("Error while parsing id to u64 (std::num::ParseIntError) in order to get it from the itemstore.\ + (get or get_sub message)")); } }; @@ -393,18 +385,10 @@ impl Message { pub fn get_metadata(&mut self) -> Result, MizeError> { if !self.has_meta { - return Err(MizeError { - code: 108, - kind: "faulty_message".to_string(), - message: "The message should have medatata, but it hasn't. (cmd <= 128)".to_string(), - }) + return Err(MizeError::new(108).extra_msg("The message should have medatata, but it hasn't. (cmd <= 128)")) }; - let meta_err = MizeError { - code: 107, - kind: "faulty_message".to_string(), - message: "Error while parsing the metadata of a message.".to_string(), - }; + let meta_err = MizeError::new(107).extra_msg("Error while parsing the metadata of a message."); let mut meta_vec:Vec = Vec::new(); let mut msg_iter = self.raw[self.index..].iter(); @@ -433,11 +417,7 @@ impl Message { meta_vec.push(*ch); }; - return Err(MizeError { - code: 107, - kind: "faulty_message".to_string(), - message: "Error while parsing the metadata of a message.".to_string(), - }) + return Err(MizeError::new(107).extra_msg("Error while parsing the metadata of a message.")) } @@ -463,11 +443,7 @@ impl Message { } } - return Err(MizeError { - code: 112, - kind: "faulty_message".to_string(), - message: "There is no / to indicate where the id ends".to_string(), - }); + return Err(MizeError::new(112).extra_msg("There is no / to indicate where the id ends")); // let len = self.raw.len(); // while self.index < 10000 { @@ -548,11 +524,8 @@ pub async fn handle_mize_message( //forward to module in case the item is from a Module //append medatata - let first_char = id.chars().nth(0).ok_or(MizeError{ - code: 11, - kind: "don't know yet".to_string(), - message: "Somehow the id is empty. while handling a get or get_sub message.".to_string(), - })?; + let first_char = id.chars().nth(0) + .ok_or(MizeError::new(11).extra_msg("Somehow the id is empty. while handling a get or get_sub message."))?; if (first_char == '!'){ message.clone().forward_module(id.clone(), mutexes.clone()).await; @@ -583,11 +556,9 @@ pub async fn handle_mize_message( let id_u64 = match id.parse::(){ Ok(id) => id, Err(err) => { - return Err(MizeError{ - code: 11, - kind: "don't know yet".to_string(), - message: "Error while parsing id to u64 in order to get it from the itemstore. (get or get_sub message)".to_string(), - }); + return Err(MizeError::new(11) + .extra_msg("Error while parsing id to u64 in order to get it from the itemstore.\ + (get or get_sub message)")); } }; @@ -620,18 +591,14 @@ pub async fn handle_mize_message( if (message.cmd == MSG_GIVE && matches!(&message.origin, Origin::Module(_))){ let meta = message.get_metadata()?; let id: String = message.get_id()?; - let client_id_str = meta.get("c").ok_or(MizeError{ - code: 11, - kind: "don't know yet".to_string(), - message: "there is no \"c\" key in the metadata of a message gotten from a module".to_string(), - })?; - - let client_id: u64 = client_id_str.parse().map_err(|_| MizeError{ - code: 11, - kind: "don't know yet".to_string(), - message: "Error (std::num::ParseIntError) while parsing the \"c\" key in the Message metadata from a give Message from a Module".to_string() - })?; + let client_id_str = meta.get("c") + .ok_or(MizeError::new(11) + .extra_msg("there is no \"c\" key in the metadata of a message gotten from a module"))?; + let client_id: u64 = client_id_str.parse() + .map_err(|_| MizeError::new(11) + .extra_msg("Error (std::num::ParseIntError) while parsing the \"c\" key \ + in the Message metadata from a give Message from a Module"))?; let clients = mutexes.clients.lock().await; let modules = mutexes.modules.lock().await; @@ -646,11 +613,7 @@ pub async fn handle_mize_message( } else if (client.len() == 1) { Origin::Client(client[0].to_owned()) } else { - return Err(MizeError{ - code: 11, - kind: "don't know yet".to_string(), - message: "".to_string() - }) + return Err(MizeError::new(11)) }; drop(clients); @@ -694,11 +657,9 @@ pub async fn handle_mize_message( if (message.cmd == MSG_UPDATE_REQUEST && (matches!(&message.origin, Origin::Module(_)) || matches!(&message.origin, Origin::Client(_)))){ let id: String = message.get_id()?; - let first_char = id.chars().nth(0).ok_or(MizeError{ - code: 11, - kind: "don't know yet".to_string(), - message: "Somehow the id is empty. while handling a get or get_sub message.".to_string(), - })?; + let first_char = id.chars().nth(0) + .ok_or(MizeError::new(11) + .extra_msg("Somehow the id is empty. while handling a get or get_sub message."))?; if (first_char == '!'){ message.clone().forward_module(id, mutexes.clone()).await; @@ -715,11 +676,7 @@ pub async fn handle_mize_message( if (message.cmd == MSG_DELETE && (matches!(&message.origin, Origin::Module(_)) || matches!(&message.origin, Origin::Client(_)))){ let id: String = message.get_id()?; if id == "0".to_string() { - let err = error::MizeError { - kind: "don't know yet".to_string(), - code: 100, - message: "You can't delete item number 0. This item contains mandatory Config for the Server.".to_string(), - }; + let err = MizeError::new(100); return Err(err); } return Ok(()); @@ -814,24 +771,20 @@ pub async fn handle_update(mut update: Update, mutexes: Mutexes, origin: Origin) let id_u64 = match update.id.clone().parse::(){ Ok(id) => id, Err(err) => { - return Err(MizeError{ - code: 11, - kind: "don't know yet".to_string(), - message: "Error while parsing id to u64 in order to get it from the itemstore. (get or get_sub message)".to_string(), - }); + return Err(MizeError::new(11) + .extra_msg("Error while parsing id to u64 in order to get it from the itemstore.\ + (get or get_sub message)")); } }; let item = itemstore.get(id_u64).await?; - let commit_pos = item.iter().position(|field| field[0] == "_commit".to_string().into_bytes()).ok_or(MizeError{ - code: 103, - kind: "key_missing::_commit".to_string(), - message: format!("Item {} has not _commit", id_u64), - })?; - let cur_commit = u64::from_be_bytes(item[commit_pos][1].clone().try_into().map_err(|_|MizeError{ - code: 105, - kind: "don't know yet".to_string(), - message: "_commit is not 8 bytes long".to_string(), - })?); + let commit_pos = item.iter() + .position(|field| field[0] == "_commit".to_string().into_bytes()) + .ok_or(MizeError::new(103) + .extra_msg(&format!("Item {} has not _commit", id_u64)))?; + + let cur_commit = u64::from_be_bytes(item[commit_pos][1].clone().try_into() + .map_err(|_|MizeError::new(105))? + ); //because Update::change_whole_val trys to lock the itemstore as well drop(itemstore);