diff --git a/Cargo.toml b/Cargo.toml index ad289e92..112e0410 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ homepage = "https://github.com/scattered-systems/scsys/wiki" keywords = ["blockchain", "primitives", "scsys"] license = "Apache-2.0" repository = "https://github.com/scattered-systems/scsys" -version = "0.1.38" +version = "0.1.39" [profile.dev] codegen-units = 256 diff --git a/README.md b/README.md index 231f3f6d..c40aaee2 100644 --- a/README.md +++ b/README.md @@ -3,14 +3,41 @@ [![Clippy](https://github.com/Scattered-Systems/scsys/actions/workflows/clippy.yml/badge.svg)](https://github.com/Scattered-Systems/scsys/actions/workflows/clippy.yml) [![Rust](https://github.com/Scattered-Systems/scsys/actions/workflows/rust.yml/badge.svg)](https://github.com/Scattered-Systems/scsys/actions/workflows/rust.yml) +*** + Welcome to scsys, this crate was created in support of the Scattered-Systems ecosystem. The crate is reserved primarily for implementing a variety of critical primitives and utilities. ## Getting Started Use Rust's built-in package manager [crates](https://crates.io/crates/scsys) to install *scsys*. +### Building from the source + +#### *Clone the repository* + +```bash +git clone https://github.com/scattered-systems/scsys +cd scsys +``` + +#### *Build the workspace locally* + +```bash +cargo xtask build +``` + +or + +```bash +cargo xtask build --release +``` + +#### *Auto* + +Automatically format and analyze the codebase before building then testing. + ```bash -cargo install package +cargo xtask auto ``` ## Usage diff --git a/SECURITY.md b/SECURITY.md index acf7d036..fa503bef 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -6,7 +6,7 @@ This section is used to update intrested parties as to which versions are curren | Package | Current | Supported | |---------|---------|-----------| -| scsys | 0.1.33 | <=0.1.30 | +| scsys | 0.1.39 | <=0.1.30 | ## Reporting a Vulnerability @@ -16,5 +16,5 @@ for more information. ### _GitHub_ -* [Company](https://github.com/scattered-systems) -* [Creator](https://github.com/FL03) \ No newline at end of file +- [Company](https://github.com/scattered-systems) +- [Creator](https://github.com/FL03) diff --git a/actors/Cargo.toml b/actors/Cargo.toml index ab5e3c54..fadda99a 100644 --- a/actors/Cargo.toml +++ b/actors/Cargo.toml @@ -8,7 +8,7 @@ keywords = ["core", "primitives", "scsys"] license = "Apache-2.0" name = "scsys-actors" repository = "https://github.com/scattered-systems/scsys" -version = "0.1.38" # TODO: Update the package version +version = "0.1.39" # TODO: Update the package version [lib] crate-type = ["cdylib", "rlib"] @@ -22,8 +22,8 @@ bson = { features = ["chrono-0_4", "serde_with", "uuid-0_8"], version = "2.4.0" chrono = "0.4.22" config = "0.13.2" glob = "0.3.0" -serde = { features = ["derive"], version = "1.0.148" } -serde_json = "1.0.89" +serde = { features = ["derive"], version = "1" } +serde_json = "1" strum = { features = ["derive"], version = "0.24.1" } url = "2.3.1" diff --git a/actors/src/lib.rs b/actors/src/lib.rs index 0d1b2b04..98649bc9 100644 --- a/actors/src/lib.rs +++ b/actors/src/lib.rs @@ -10,7 +10,10 @@ pub mod agents; pub mod catalysts; pub mod contexts; pub mod handlers; +pub mod loggers; pub mod messages; +pub mod networking; +pub mod providers; pub mod sessions; pub mod states; @@ -18,3 +21,5 @@ pub(crate) mod direction; pub(crate) mod justify; pub type Job = Box; + +pub trait Temporal {} diff --git a/core/src/loggers/logger.rs b/actors/src/loggers/logger.rs similarity index 100% rename from core/src/loggers/logger.rs rename to actors/src/loggers/logger.rs diff --git a/core/src/loggers/mod.rs b/actors/src/loggers/mod.rs similarity index 100% rename from core/src/loggers/mod.rs rename to actors/src/loggers/mod.rs diff --git a/core/src/networking/mod.rs b/actors/src/networking/mod.rs similarity index 100% rename from core/src/networking/mod.rs rename to actors/src/networking/mod.rs diff --git a/core/src/networking/proxy.rs b/actors/src/networking/proxy.rs similarity index 100% rename from core/src/networking/proxy.rs rename to actors/src/networking/proxy.rs diff --git a/core/src/networking/server.rs b/actors/src/networking/server.rs similarity index 61% rename from core/src/networking/server.rs rename to actors/src/networking/server.rs index ef7904ca..3c030e46 100644 --- a/core/src/networking/server.rs +++ b/actors/src/networking/server.rs @@ -4,8 +4,8 @@ Description: ... Summary ... */ -use crate::extract::Extractor; use serde::{Deserialize, Serialize}; +use std::str::FromStr; #[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] pub struct Server { @@ -21,8 +21,7 @@ impl Server { std::net::SocketAddr::from(self.pieces()) } pub fn pieces(&self) -> ([u8; 4], u16) { - let host: [u8; 4] = Extractor::new('.', self.host.clone(), None) - .extract() + let host: [u8; 4] = extractor('.', &self.host.clone(), None) .try_into() .ok() .unwrap(); @@ -45,3 +44,23 @@ impl std::fmt::Display for Server { ) } } + +const DEFAULT_IGNORE_CHARS: &[char] = &['[', ']', ',', '.', ' ']; + +/// Implements the basic algorithm used by the extractor +fn extractor( + bp: char, + data: &S, + exclude: Option<&[char]>, +) -> Vec +where + ::Err: std::fmt::Debug, +{ + let data = data.to_string(); + let skip = exclude.unwrap_or(DEFAULT_IGNORE_CHARS); + let trimmed: &str = data.trim_matches(skip); + trimmed + .split(bp) + .map(|i| i.trim_matches(skip).parse::().unwrap()) + .collect() +} diff --git a/core/src/providers/mod.rs b/actors/src/providers/mod.rs similarity index 100% rename from core/src/providers/mod.rs rename to actors/src/providers/mod.rs diff --git a/core/src/providers/networks/ethereum.rs b/actors/src/providers/networks/ethereum.rs similarity index 100% rename from core/src/providers/networks/ethereum.rs rename to actors/src/providers/networks/ethereum.rs diff --git a/core/src/providers/networks/mod.rs b/actors/src/providers/networks/mod.rs similarity index 100% rename from core/src/providers/networks/mod.rs rename to actors/src/providers/networks/mod.rs diff --git a/core/src/providers/provider.rs b/actors/src/providers/provider.rs similarity index 100% rename from core/src/providers/provider.rs rename to actors/src/providers/provider.rs diff --git a/core/src/providers/storage/cache.rs b/actors/src/providers/storage/cache.rs similarity index 100% rename from core/src/providers/storage/cache.rs rename to actors/src/providers/storage/cache.rs diff --git a/core/src/providers/storage/database.rs b/actors/src/providers/storage/database.rs similarity index 100% rename from core/src/providers/storage/database.rs rename to actors/src/providers/storage/database.rs diff --git a/core/src/providers/storage/mod.rs b/actors/src/providers/storage/mod.rs similarity index 100% rename from core/src/providers/storage/mod.rs rename to actors/src/providers/storage/mod.rs diff --git a/core/src/providers/storage/s3.rs b/actors/src/providers/storage/s3.rs similarity index 99% rename from core/src/providers/storage/s3.rs rename to actors/src/providers/storage/s3.rs index 412b9708..e2afc5ce 100644 --- a/core/src/providers/storage/s3.rs +++ b/actors/src/providers/storage/s3.rs @@ -4,7 +4,7 @@ Description: ... Summary ... */ -use crate::Result; + use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)] diff --git a/actors/src/states/mod.rs b/actors/src/states/mod.rs index d287875a..fc259fc3 100644 --- a/actors/src/states/mod.rs +++ b/actors/src/states/mod.rs @@ -11,6 +11,21 @@ pub(crate) mod specs { use crate::messages::Message; use std::sync::Arc; + pub trait Eventful: Clone + Default + ToString { + type Event: Clone + Default + ToString; + + fn by_arc(self: Arc) -> Arc { + self + } + fn event(&self) -> Self::Event + where + Self: Sized; + fn timestamp(self) -> i64; + fn now(self) -> i64 { + chrono::Utc::now().timestamp() + } + } + pub trait StatePack: Default + ToString {} pub trait Stateful: Clone + Default { diff --git a/core/Cargo.toml b/core/Cargo.toml index a3c42982..9d64ae33 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -8,22 +8,28 @@ keywords = ["core", "primitives", "scsys"] license = "Apache-2.0" name = "scsys-core" repository = "https://github.com/scattered-systems/scsys" -version = "0.1.38" # TODO: Update the package version +version = "0.1.39" # TODO: Update the package version + +[features] +default = [] +# wasm = ["wasm-bindgen/serde-serialize"] [lib] crate-type = ["cdylib", "rlib"] test = true [dependencies] -bson = { features = ["chrono-0_4", "serde_with", "uuid-0_8"], version = "2.4.0" } +anyhow = "1.0.68" +bson = { features = ["chrono-0_4", "uuid-0_8"], version = "2.4.0" } chrono = "0.4.22" config = "0.13.2" glob = "0.3.0" -nom = "7.1.1" -serde = { features = ["derive"], version = "1.0.148" } -serde_json = "1.0.89" +serde = { features = ["derive"], version = "1" } +serde_json = "1" strum = { features = ["derive"], version = "0.24.1" } url = "2.3.1" +# wasm-bindgen = { features = ["serde-serialize"], optional = true, version = "0.2.83" } + [package.metadata.docs.rs] rustc-args = ["--cfg", "docsrs"] diff --git a/core/src/events/event.rs b/core/src/events/event.rs deleted file mode 100644 index baca3f8d..00000000 --- a/core/src/events/event.rs +++ /dev/null @@ -1,48 +0,0 @@ -/* - Appellation: interface - Contributors: FL03 - Description: - ... Summary ... -*/ -use super::Eventful; -use crate::Timestamp; -use serde::{Deserialize, Serialize}; - -#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] -pub struct Event { - pub message: String, - pub timestamp: Timestamp, -} - -impl Event { - pub fn new(message: String, timestamp: Timestamp) -> Self { - Self { message, timestamp } - } -} - -impl Eventful for Event { - fn message(&self) -> String { - self.message.clone() - } - fn timestamp(&self) -> i64 { - self.clone().timestamp.into() - } -} - -impl std::convert::From<&T> for Event { - fn from(data: &T) -> Self { - Self::new(data.to_string(), Timestamp::default()) - } -} - -impl Default for Event { - fn default() -> Self { - Self::from(&String::new()) - } -} - -impl std::fmt::Display for Event { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", serde_json::to_string_pretty(&self).unwrap()) - } -} diff --git a/core/src/events/misc/mod.rs b/core/src/events/misc/mod.rs deleted file mode 100644 index 02a4883d..00000000 --- a/core/src/events/misc/mod.rs +++ /dev/null @@ -1,10 +0,0 @@ -/* - Appellation: events - Creator: FL03 - Description: - ... Summary ... -*/ -pub use self::{payload::*, variants::*}; - -pub(crate) mod payload; -pub(crate) mod variants; diff --git a/core/src/events/misc/payload.rs b/core/src/events/misc/payload.rs deleted file mode 100644 index 638278e1..00000000 --- a/core/src/events/misc/payload.rs +++ /dev/null @@ -1,17 +0,0 @@ -/* - Appellation: payload - Contributors: FL03 (https://gitlab.com/FL03) - Description: - ... Summary ... -*/ -use crate::Timestamp; -use bson::oid::ObjectId; -use serde::{Deserialize, Serialize}; - -#[derive(Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)] -pub struct EventModel { - pub id: ObjectId, - pub created: Timestamp, - pub dispersed: Timestamp, - pub data: Vec, -} diff --git a/core/src/events/misc/variants.rs b/core/src/events/misc/variants.rs deleted file mode 100644 index 9462eabd..00000000 --- a/core/src/events/misc/variants.rs +++ /dev/null @@ -1,31 +0,0 @@ -/* - Appellation: variants - Contributors: FL03 - Description: - ... Summary ... -*/ -use crate::events::{Event, Eventful}; -use serde::{Deserialize, Serialize}; -use strum::{EnumString, EnumVariantNames}; - -/// Encapsulates the availible events for the ecosystem -#[derive( - Clone, Copy, Debug, Deserialize, EnumString, EnumVariantNames, Eq, Hash, PartialEq, Serialize, -)] -#[strum(serialize_all = "snake_case")] -pub enum Events { - GenericEvent(T), - Idle, -} - -impl Default for Events { - fn default() -> Self { - Self::Idle - } -} - -impl std::fmt::Display for Events { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", serde_json::to_string_pretty(&self).unwrap()) - } -} diff --git a/core/src/events/mod.rs b/core/src/events/mod.rs deleted file mode 100644 index 627748e0..00000000 --- a/core/src/events/mod.rs +++ /dev/null @@ -1,32 +0,0 @@ -/* - Appellation: events - Creator: FL03 - Description: - ... Summary ... -*/ -pub use self::{event::*, misc::*, specs::*}; - -pub(crate) mod event; -pub(crate) mod misc; - -pub(crate) mod specs { - use serde::Serialize; - use std::fmt::Display; - - pub trait Eventful: Clone + Default + Display + Serialize { - fn message(&self) -> String; - fn timestamp(&self) -> i64; - } -} - -#[cfg(test)] -mod tests { - use super::Event; - - #[test] - fn test_event_default() { - let a = Event::default(); - let b = a.clone(); - assert_eq!(a, b) - } -} diff --git a/core/src/extract/extractor.rs b/core/src/extract/extractor.rs index 9831980c..2098f409 100644 --- a/core/src/extract/extractor.rs +++ b/core/src/extract/extractor.rs @@ -4,7 +4,7 @@ Description: ... Summary ... */ -use crate::{extract::base_extractor, DEFAULT_IGNORE_CHARS}; +use crate::{extract::extractor, DEFAULT_IGNORE_CHARS}; use std::str::FromStr; /// Implements the formal interface for operating the extraction features @@ -28,6 +28,6 @@ impl<'a> Extractor<'a> { where ::Err: std::fmt::Debug, { - base_extractor::(self.breakpoint, &self.data, Some(self.exclude)) + extractor::(self.breakpoint, &self.data, Some(self.exclude)) } } diff --git a/core/src/extract/mod.rs b/core/src/extract/mod.rs index fedde009..9f1e0e6c 100644 --- a/core/src/extract/mod.rs +++ b/core/src/extract/mod.rs @@ -1,20 +1,17 @@ /* Appellation: extract - Creator: FL03 - Description: - ... Summary ... + Contrib: FL03 + Description: ... Summary ... */ pub use self::{extractor::*, files::*, utils::*}; mod extractor; mod files; -pub trait ExtractorSpec { - fn extract(&self) -> Vec; -} +pub trait Extraction { + type Res: std::str::FromStr + ToString; -pub trait FileExtSpec: ExtractorSpec { - fn path(&self) -> std::path::Path; + fn extract(bp: char, data: &S, exclude: Option<&[char]>) -> Vec; } pub(crate) mod utils { @@ -22,7 +19,7 @@ pub(crate) mod utils { use std::str::FromStr; /// Implements the basic algorithm used by the extractor - pub fn base_extractor( + pub fn extractor( bp: char, data: &S, exclude: Option<&[char]>, @@ -56,8 +53,8 @@ mod tests { #[test] fn test_extractor_comma() { let a = Extractor::new(',', "[0, 0, 0, 0]".to_string(), None); - - assert_eq!(a.extract::(), vec![0, 0, 0, 0]) + let b = extractor::<&str, u8>(',', &"[0, 0, 0, 0]", None); + assert_eq!(a.extract::(), b) } #[test] diff --git a/core/src/lib.rs b/core/src/lib.rs index 5e494c42..e42ddbb9 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -4,21 +4,16 @@ Description: ... Summary ... */ #[doc(inline)] -pub use self::{appellation::*, ids::*, links::*, primitives::*, specs::*, times::*, utils::*}; +pub use self::{misc::*, primitives::*, specs::*, utils::*}; pub mod accounts; pub mod errors; -pub mod events; pub mod extract; -pub mod loggers; -pub mod networking; -pub mod parse; -pub mod providers; -pub(crate) mod appellation; -pub(crate) mod ids; -pub(crate) mod links; +pub(crate) mod misc; pub(crate) mod primitives; pub(crate) mod specs; -pub(crate) mod times; pub(crate) mod utils; + +/// Type alias for [anyhow::Result] +pub type Result = anyhow::Result; diff --git a/core/src/appellation.rs b/core/src/misc/appellation.rs similarity index 86% rename from core/src/appellation.rs rename to core/src/misc/appellation.rs index c61aaadf..739026bc 100644 --- a/core/src/appellation.rs +++ b/core/src/misc/appellation.rs @@ -9,6 +9,16 @@ */ use serde::{Deserialize, Serialize}; +pub trait AppellationSpec { + type Id; + type Key; + type Name: ToString; + + fn id(&self) -> &Self::Id; + fn key(&self) -> &Self::Key; + fn name(&self) -> &Self::Name; +} + #[derive(Clone, Default, Deserialize, Eq, Hash, PartialEq, Serialize)] pub struct Appellation { pub id: T, diff --git a/core/src/ids.rs b/core/src/misc/ids.rs similarity index 100% rename from core/src/ids.rs rename to core/src/misc/ids.rs diff --git a/core/src/links.rs b/core/src/misc/links.rs similarity index 100% rename from core/src/links.rs rename to core/src/misc/links.rs diff --git a/core/src/misc/mod.rs b/core/src/misc/mod.rs new file mode 100644 index 00000000..3df42496 --- /dev/null +++ b/core/src/misc/mod.rs @@ -0,0 +1,11 @@ +/* + Appellation: misc + Contrib: FL03 + Description: ... Summary ... +*/ +pub use self::{appellation::*, ids::*, links::*, timestamp::*,}; + +pub(crate) mod appellation; +pub(crate) mod ids; +pub(crate) mod links; +pub(crate) mod timestamp; \ No newline at end of file diff --git a/core/src/times/timestamp.rs b/core/src/misc/timestamp.rs similarity index 87% rename from core/src/times/timestamp.rs rename to core/src/misc/timestamp.rs index 3889b268..ccd2bf21 100644 --- a/core/src/times/timestamp.rs +++ b/core/src/misc/timestamp.rs @@ -3,7 +3,7 @@ Contrib: FL03 Description: ... Summary ... */ -use crate::{timestamp, DefaultTimezone, Temporal}; +use crate::{timestamp, DefaultTimezone, Temporal, TemporalExt}; use serde::{Deserialize, Serialize}; use std::convert::{From, TryFrom}; use strum::EnumVariantNames; @@ -18,7 +18,7 @@ pub enum Timestamp { impl Timestamp { pub fn new() -> Self { - Self::timestamp() + Self::Ts(timestamp()) } pub fn now() -> chrono::DateTime { chrono::Utc::now() @@ -26,8 +26,8 @@ impl Timestamp { pub fn rfc3339() -> Self { Self::Rfc3339(chrono::Utc::now().to_rfc3339()) } - pub fn timestamp() -> Self { - Self::Ts(timestamp()) + pub fn timestamp(&self) -> i64 { + self.into() } } @@ -42,12 +42,12 @@ impl std::fmt::Display for Timestamp { write!(f, "{}", serde_json::to_string(&self).unwrap()) } } - impl Temporal for Timestamp { - fn timestamp(&self) -> i64 { + fn created(&self) -> i64 { self.into() } } +impl TemporalExt for Timestamp {} impl From<&Timestamp> for Timestamp { fn from(data: &Timestamp) -> Self { @@ -101,17 +101,17 @@ impl TryFrom<&str> for Timestamp { } } + #[cfg(test)] mod tests { use super::*; #[test] fn test_timestamp() { - let ts = Timestamp::now(); - let str_ts = ts.to_rfc3339(); - let a = Timestamp::from(&ts); - let b = Timestamp::try_from(str_ts).unwrap(); - assert_eq!(a, b) + let boundary = Timestamp::now(); + let a = Timestamp::from(&boundary); + let b = Timestamp::try_from(boundary.to_rfc3339()).ok().unwrap(); + assert_eq!(&a, &b); } #[test] diff --git a/core/src/parse/basic.rs b/core/src/parse/basic.rs deleted file mode 100644 index d7ea7e9b..00000000 --- a/core/src/parse/basic.rs +++ /dev/null @@ -1,158 +0,0 @@ -/* - Appellation: unicode - Contributors: FL03 (https://github.com) - Description: - ... Summary ... -*/ -use nom::{ - branch::alt, - bytes::streaming::{is_not, take_while_m_n}, - character::streaming::{char, multispace1}, - combinator::{map, map_opt, map_res, value, verify}, - error::{FromExternalError, ParseError}, - multi::fold_many0, - sequence::{delimited, preceded}, - IResult, -}; - -// parser combinators are constructed from the bottom up: -// first we write parsers for the smallest elements (escaped characters), -// then combine them into larger parsers. - -/// Parse a unicode sequence, of the form u{XXXX}, where XXXX is 1 to 6 -/// hexadecimal numerals. We will combine this later with parse_escaped_char -/// to parse sequences like \u{00AC}. -pub fn parse_unicode<'a, E>(input: &'a str) -> IResult<&'a str, char, E> -where - E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>, -{ - // `take_while_m_n` parses between `m` and `n` bytes (inclusive) that match - // a predicate. `parse_hex` here parses between 1 and 6 hexadecimal numerals. - let parse_hex = take_while_m_n(1, 6, |c: char| c.is_ascii_hexdigit()); - - // `preceded` takes a prefix parser, and if it succeeds, returns the result - // of the body parser. In this case, it parses u{XXXX}. - let parse_delimited_hex = preceded( - char('u'), - // `delimited` is like `preceded`, but it parses both a prefix and a suffix. - // It returns the result of the middle parser. In this case, it parses - // {XXXX}, where XXXX is 1 to 6 hex numerals, and returns XXXX - delimited(char('{'), parse_hex, char('}')), - ); - - // `map_res` takes the result of a parser and applies a function that returns - // a Result. In this case we take the hex bytes from parse_hex and attempt to - // convert them to a u32. - let parse_u32 = map_res(parse_delimited_hex, move |hex| u32::from_str_radix(hex, 16)); - - // map_opt is like map_res, but it takes an Option instead of a Result. If - // the function returns None, map_opt returns an error. In this case, because - // not all u32 values are valid unicode code points, we have to fallibly - // convert to char with from_u32. - map_opt(parse_u32, std::char::from_u32)(input) -} - -/// Parse an escaped character: \n, \t, \r, \u{00AC}, etc. -pub fn parse_escaped_char<'a, E>(input: &'a str) -> IResult<&'a str, char, E> -where - E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>, -{ - preceded( - char('\\'), - // `alt` tries each parser in sequence, returning the result of - // the first successful match - alt(( - parse_unicode, - // The `value` parser returns a fixed value (the first argument) if its - // parser (the second argument) succeeds. In these cases, it looks for - // the marker characters (n, r, t, etc) and returns the matching - // character (\n, \r, \t, etc). - value('\n', char('n')), - value('\r', char('r')), - value('\t', char('t')), - value('\u{08}', char('b')), - value('\u{0C}', char('f')), - value('\\', char('\\')), - value('/', char('/')), - value('"', char('"')), - )), - )(input) -} - -/// Parse a backslash, followed by any amount of whitespace. This is used later -/// to discard any escaped whitespace. -pub fn parse_escaped_whitespace<'a, E: ParseError<&'a str>>( - input: &'a str, -) -> IResult<&'a str, &'a str, E> { - preceded(char('\\'), multispace1)(input) -} - -/// Parse a non-empty block of text that doesn't include \ or " -pub fn parse_literal<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, &'a str, E> { - // `is_not` parses a string of 0 or more characters that aren't one of the - // given characters. - let not_quote_slash = is_not("\"\\"); - - // `verify` runs a parser, then runs a verification function on the output of - // the parser. The verification function accepts out output only if it - // returns true. In this case, we want to ensure that the output of is_not - // is non-empty. - verify(not_quote_slash, |s: &str| !s.is_empty())(input) -} - -/// A string fragment contains a fragment of a string being parsed: either -/// a non-empty Literal (a series of non-escaped characters), a single -/// parsed escaped character, or a block of escaped whitespace. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum StringFragment<'a> { - Literal(&'a str), - EscapedChar(char), - EscapedWS, -} - -/// Combine parse_literal, parse_escaped_whitespace, and parse_escaped_char -/// into a StringFragment. -pub fn parse_fragment<'a, E>(input: &'a str) -> IResult<&'a str, StringFragment<'a>, E> -where - E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>, -{ - alt(( - // The `map` combinator runs a parser, then applies a function to the output - // of that parser. - map(parse_literal, StringFragment::Literal), - map(parse_escaped_char, StringFragment::EscapedChar), - value(StringFragment::EscapedWS, parse_escaped_whitespace), - ))(input) -} - -/// Parse a string. Use a loop of parse_fragment and push all of the fragments -/// into an output string. -pub fn parse_string<'a, E>(input: &'a str) -> IResult<&'a str, String, E> -where - E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>, -{ - // fold_many0 is the equivalent of iterator::fold. It runs a parser in a loop, - // and for each output value, calls a folding function on each output value. - let build_string = fold_many0( - // Our parser function– parses a single string fragment - parse_fragment, - // Our init value, an empty string - String::new, - // Our folding function. For each fragment, append the fragment to the - // string. - |mut string, fragment| { - match fragment { - StringFragment::Literal(s) => string.push_str(s), - StringFragment::EscapedChar(c) => string.push(c), - StringFragment::EscapedWS => {} - } - string - }, - ); - - // Finally, parse the string. Note that, if `build_string` could accept a raw - // " character, the closing delimiter " would never match. When using - // `delimited` with a looping parser (like fold_many0), be sure that the - // loop won't accidentally match your closing delimiter! - delimited(char('"'), build_string, char('"'))(input) -} diff --git a/core/src/parse/mod.rs b/core/src/parse/mod.rs deleted file mode 100644 index 239efc76..00000000 --- a/core/src/parse/mod.rs +++ /dev/null @@ -1,33 +0,0 @@ -/* - Appellation: actors - Contributors: FL03 (https://github.com) - Description: ... summary ... -*/ -pub use self::basic::*; - -pub(crate) mod basic; - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_parser_default() { - let data = "\"abc\""; - let result = parse_string::<()>(data); - assert_eq!(result, Ok(("", String::from("abc")))) - } - - #[test] - fn test_other_parser() { - let data = "\"tab:\\tafter tab, newline:\\nnew line, quote: \\\", emoji: \\u{1F602}, newline:\\nescaped whitespace: \\ abc\""; - let result = parse_string::<()>(data); - assert_eq!( - result, - Ok(( - "", - String::from("tab:\tafter tab, newline:\nnew line, quote: \", emoji: 😂, newline:\nescaped whitespace: abc") - )) - ) - } -} diff --git a/core/src/primitives.rs b/core/src/primitives.rs index 8b27a53d..a49b5581 100644 --- a/core/src/primitives.rs +++ b/core/src/primitives.rs @@ -34,8 +34,7 @@ pub(crate) mod types { pub type BaseError = Box; /// Type alias for a boxed error with send, sync, and static flags enabled pub type BoxError = Box; - /// Type alias of a result implementing the [BaseError] - pub type Result = std::result::Result; + /// Type alias for the standard result used pub type BoxResult = Result; /// Type alias for [bson::DateTime] diff --git a/core/src/specs.rs b/core/src/specs.rs index 60f923a6..50e50ba2 100644 --- a/core/src/specs.rs +++ b/core/src/specs.rs @@ -3,9 +3,12 @@ Contrib: FL03 Description: ... Summary ... */ +use crate::{chrono_into_bson, ChronoDateTime}; +use chrono::Utc; -pub trait Addressable { - fn address(&self) -> T; +pub trait Addressable { + type Addr; + fn address(self) -> Self::Addr; } /// Trait for signaling a structure with a dedicated build stage pub trait Buildable { @@ -17,8 +20,33 @@ pub trait Buildable { /// Quickly derive elligible naming schematics for the desired structure pub trait Named { - fn name() -> String; + fn name(&self) -> String; fn slug(&self) -> String { - Self::name().to_lowercase() + self.name().to_lowercase() } } + + + +pub trait TemporalExt: Temporal { + fn chrono_to_bson(&self, data: ChronoDateTime) -> bson::DateTime { + chrono_into_bson::(data) + } + fn bson_datetime() -> bson::DateTime { + chrono_into_bson::(chrono::Utc::now()) + } + fn datetime() -> ChronoDateTime { + chrono::Utc::now() + } + fn gen_rfc3339() -> String { + chrono::Utc::now().to_rfc3339() + } + fn ts() -> i64 { + chrono::Utc::now().timestamp() + } +} + +/// Interface for time-related data-structures +pub trait Temporal { + fn created(&self) -> i64; // Recall an objects time of creation +} diff --git a/core/src/times/mod.rs b/core/src/times/mod.rs deleted file mode 100644 index 6b7914f7..00000000 --- a/core/src/times/mod.rs +++ /dev/null @@ -1,68 +0,0 @@ -/* - Appellation: times - Contrib: FL03 - Description: ... Summary ... -*/ -pub use self::{specs::*, timestamp::*, utils::*}; - -pub(crate) mod timestamp; - -pub(crate) mod specs { - use crate::{chrono_into_bson, ChronoDateTime}; - use chrono::Utc; - - pub trait TemporalExt {} - - /// Interface for time-related data-structures - pub trait Temporal { - fn chrono_to_bson(&self, data: ChronoDateTime) -> bson::DateTime { - chrono_into_bson::(data) - } - fn bson_datetime() -> bson::DateTime { - chrono_into_bson::(chrono::Utc::now()) - } - fn datetime() -> ChronoDateTime { - chrono::Utc::now() - } - fn gen_rfc3339() -> String { - chrono::Utc::now().to_rfc3339() - } - fn ts() -> i64 { - chrono::Utc::now().timestamp() - } - fn timestamp(&self) -> i64; // Recall an objects time of creation - } -} - -pub(crate) mod utils { - use chrono::{DateTime, TimeZone, Utc}; - - pub fn chrono_datetime_now() -> DateTime { - Utc::now() - } - - pub fn ts_rfc3339() -> String { - Utc::now().to_rfc3339() - } - - pub fn chrono_into_bson(data: DateTime) -> bson::DateTime { - bson::DateTime::from_chrono(data) - } - - pub fn timestamp() -> i64 { - Utc::now().timestamp() - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_timestamp() { - let boundary = Timestamp::now(); - let a = Timestamp::from(&boundary); - let b = Timestamp::try_from(boundary.to_rfc3339()).ok().unwrap(); - assert_eq!(&a, &b); - } -} diff --git a/core/src/utils.rs b/core/src/utils.rs index 52265494..25aad7b9 100644 --- a/core/src/utils.rs +++ b/core/src/utils.rs @@ -4,6 +4,7 @@ Description: ... Summary ... */ use crate::{BoxResult, ConfigFile, ConfigFileVec}; +use chrono::{DateTime, TimeZone, Utc}; use std::io::{self, BufRead, BufReader}; use std::{fs::File, str::FromStr, string::ToString}; @@ -51,6 +52,22 @@ pub fn project_root() -> std::path::PathBuf { .unwrap() .to_path_buf() } +/// +pub fn chrono_datetime_now() -> DateTime { + Utc::now() +} +/// +pub fn chrono_into_bson(data: DateTime) -> bson::DateTime { + bson::DateTime::from_chrono(data) +} +/// +pub fn ts_rfc3339() -> String { + Utc::now().to_rfc3339() +} +/// +pub fn timestamp() -> i64 { + Utc::now().timestamp() +} #[cfg(test)] mod tests { diff --git a/crypto/Cargo.toml b/crypto/Cargo.toml index a91cea49..23c61ba6 100644 --- a/crypto/Cargo.toml +++ b/crypto/Cargo.toml @@ -8,7 +8,7 @@ keywords = ["crypto", "scsys"] license = "Apache-2.0" name = "scsys-crypto" repository = "https://github.com/scattered-systems/scsys" -version = "0.1.38" # TODO: Update the package version +version = "0.1.39" # TODO: Update the package version [features] default = [] diff --git a/derive/Cargo.toml b/derive/Cargo.toml index 24fa796d..11a77144 100644 --- a/derive/Cargo.toml +++ b/derive/Cargo.toml @@ -8,7 +8,7 @@ keywords = ["derive", "macros", "scsys"] license = "Apache-2.0" name = "scsys-derive" repository = "https://github.com/scattered-systems/scsys" -version = "0.1.38" # TODO: Update the package version +version = "0.1.39" # TODO: Update the package version [lib] proc-macro = true diff --git a/derive/src/lib.rs b/derive/src/lib.rs index dafa7c73..a69883de 100644 --- a/derive/src/lib.rs +++ b/derive/src/lib.rs @@ -33,25 +33,6 @@ fn impl_hashable(ast: &syn::DeriveInput) -> proc_macro2::TokenStream { res } -#[proc_macro_derive(Temporal)] -pub fn temporal(input: TokenStream) -> TokenStream { - let ast = parse_macro_input!(input as DeriveInput); - let gen = impl_temporal(&ast); - gen.into() -} - -pub(crate) fn impl_temporal(ast: &syn::DeriveInput) -> proc_macro2::TokenStream { - let name = &ast.ident; - let res = quote::quote! { - impl Temporal for #name { - fn timestamp(&self) -> i64 { - self.timestamp.clone().into() - } - } - }; - res -} - #[proc_macro_derive(Named, attributes(Alternative))] pub fn named(input: TokenStream) -> TokenStream { // Parse the inputs into the proper struct diff --git a/gen/Cargo.toml b/gen/Cargo.toml index 9d612f89..19dbade1 100644 --- a/gen/Cargo.toml +++ b/gen/Cargo.toml @@ -8,7 +8,7 @@ keywords = ["scsys"] license = "Apache-2.0" name = "scsys-gen" repository = "https://github.com/scattered-systems/scsys" -version = "0.1.38" # TODO: Update the package version +version = "0.1.39" # TODO: Update the package version [features] default = [] diff --git a/macros/Cargo.toml b/macros/Cargo.toml index 089ca8d9..4de1a5fd 100644 --- a/macros/Cargo.toml +++ b/macros/Cargo.toml @@ -8,7 +8,7 @@ keywords = ["macros", "scsys"] license = "Apache-2.0" name = "scsys-macros" repository = "https://github.com/scattered-systems/scsys" -version = "0.1.38" # TODO: Update the package version +version = "0.1.39" # TODO: Update the package version [lib] crate-type = ["cdylib", "rlib"] diff --git a/scsys/Cargo.toml b/scsys/Cargo.toml index 3949b37a..d708b269 100644 --- a/scsys/Cargo.toml +++ b/scsys/Cargo.toml @@ -9,7 +9,7 @@ license = "Apache-2.0" name = "scsys" readme = "README.md" repository = "https://github.com/scattered-systems/scsys" -version = "0.1.38" # TODO: Update the package version +version = "0.1.39" # TODO: Update the package version [features] default = [ @@ -31,14 +31,11 @@ full = [ ] wasm = [ - "actors", - "core", - "scsys-crypto/wasm", - "scsys-gen/wasm" + "scsys-core/default" ] actors = ["scsys-actors"] -core = ["scsys-core"] +core = ["scsys-core/default"] crypto = ["scsys-crypto/default"] derive = ["scsys-derive"] gen = ["scsys-gen/default"] @@ -58,12 +55,12 @@ bson = { features = ["chrono-0_4", "serde_with", "uuid-0_8"], optional = true, v chrono = { optional = true, version = "0.4.22" } config = { optional = true, version = "0.13.2" } -scsys-actors = { features = [], optional = true, path = "../actors", version = "0.1.38" } -scsys-core = { features = [], optional = true, path = "../core", version = "0.1.38" } -scsys-crypto = { features = ["wasm"], optional = true, path = "../crypto", version = "0.1.38" } -scsys-derive = { features = [], optional = true, path = "../derive", version = "0.1.38" } -scsys-gen = { features = ["wasm"], optional = true, path = "../gen", version = "0.1.38" } -scsys-macros = { features = [], optional = true, path = "../macros", version = "0.1.38" } +scsys-actors = { features = [], optional = true, path = "../actors", version = "0.1.39" } +scsys-core = { features = [], optional = true, path = "../core", version = "0.1.39" } +scsys-crypto = { features = ["wasm"], optional = true, path = "../crypto", version = "0.1.39" } +scsys-derive = { features = [], optional = true, path = "../derive", version = "0.1.39" } +scsys-gen = { features = ["wasm"], optional = true, path = "../gen", version = "0.1.39" } +scsys-macros = { features = [], optional = true, path = "../macros", version = "0.1.39" } [package.metadata.docs.rs] all-features = true diff --git a/scsys/src/lib.rs b/scsys/src/lib.rs index 5628aa31..f719ebc0 100644 --- a/scsys/src/lib.rs +++ b/scsys/src/lib.rs @@ -20,7 +20,8 @@ pub use scsys_macros::*; pub mod prelude { #[cfg(feature = "actors")] pub use super::actors::{ - agents::*, catalysts::*, contexts::*, handlers::*, messages::*, sessions::*, states::*, + agents::*, catalysts::*, contexts::*, handlers::*, loggers::*, messages::*, networking::*, + providers::*, sessions::*, states::*, }; #[cfg(feature = "crypto")] pub use super::crypto::*; @@ -28,10 +29,7 @@ pub mod prelude { pub use super::gen::*; pub use super::*; #[cfg(feature = "core")] - pub use super::{ - accounts::*, errors::*, events::*, extract::*, loggers::*, networking::*, parse::*, - providers::*, - }; + pub use super::{accounts::*, errors::*, extract::*}; // Extras #[cfg(feature = "bson")] pub use bson; diff --git a/scsys/tests/derive.rs b/scsys/tests/derive.rs index f38caba1..d4e40eb7 100644 --- a/scsys/tests/derive.rs +++ b/scsys/tests/derive.rs @@ -8,9 +8,9 @@ mod tests { use scsys::prelude::*; use scsys::Hashable; - use scsys::{Named, Temporal, Timestamp}; + use scsys::Timestamp; - #[derive(Default, Hashable, Named, Temporal)] + #[derive(Default, Hashable)] pub struct TestStruct { timestamp: Timestamp, } @@ -21,19 +21,13 @@ mod tests { } } - #[derive(Named)] + #[derive(Default)] struct Pancakes; - #[test] - fn test_simple_derive() { - let a = Pancakes::name(); - assert_eq!(a, String::from("Pancakes")) - } - #[test] fn test_hashable_derive() { - let _a = TestStruct::default(); - // let hash = a.hash(); - assert_eq!(TestStruct::name(), String::from("TestStruct")); + let a = TestStruct::default(); + let _hash = a.hash(); + assert!(true) } }