mycelium_lib 0.1.2

Library for Mycelium DDM
Documentation
extern crate bincode;
extern crate bytes;
extern crate chrono;
extern crate fern;
extern crate mycelium_command;
extern crate mycelium_experimental;
extern crate mycelium_index;
extern crate ron;
#[macro_use]
extern crate serde;
extern crate serde_json;
extern crate socket2;
extern crate uuid;

mod client;
pub mod prelude;
mod tcp_server;
mod udp_server;

use std::sync::Arc;

use crate::prelude::*;
use mycelium_command::prelude::*;
use mycelium_experimental::crossbeam_skiplist::map::SkipMap;
use mycelium_experimental::crossbeam_skiplist::set::SkipSet;
use std::net::Ipv4Addr;

///
/// # Mycelium
///
/// Primary method to embed database into applications is
/// through this struct.
///
/// TCP, UDP, or calling functions implemented on Mycelium
/// in this library to interact with the database.
///
/// TCP (localhost) is not required. UDP server
/// should be started for distributed behavior, but is not
/// required if that behavior is not desired.
///
pub struct Mycelium {
    pub config: Config,
    data: Index,
    network: SkipMap<String, SkipSet<(Ipv4Addr, usize, usize)>>,
}

impl Mycelium {
    ///
    /// # Init_db
    ///
    /// Initialize a new instance of Mycelium
    ///
    /// ```
    /// use mycelium_lib::prelude::*;
    ///
    /// let config = Config::default()
    ///  .with_data_directory("./");
    ///
    /// let db = Mycelium::init_db(config);
    ///
    /// ```
    ///
    pub fn init_db(config: Config) -> std::sync::Arc<Mycelium> {
        let idx = Index::init(Some(config.clone())).expect("Failed to init db.");
        Arc::new(Mycelium {
            config,
            data: idx,
            network: SkipMap::new(),
        })
    }

    pub fn config(&self) -> Config {
        self.config.clone()
    }

    ///
    /// Embedded option
    ///
    /// ```
    /// use mycelium_command::prelude::*;
    /// use mycelium_lib::{ prelude::*, Mycelium };
    /// use mycelium_index::prelude::Config;
    ///
    /// let config = Config::fetch_or_default(&std::env::current_exe().expect("a path"))
    ///     .expect("failed to get a default config");
    /// let db = Mycelium::init_db(config.0);
    /// let cmd = Command::new()
    ///     .with_action(Action::Insert(b"Mastiff, Pyranese, Shepard...
    ///         I do not know my dogs well.".to_vec()))
    ///     .with_tag("dog")
    ///     .with_what(What::Index("working".to_string()));
    ///
    /// match db.execute_command(cmd) {
    ///     Ok(_) => assert!(true),
    ///     Err(_) => assert!((false)),
    /// }
    /// ```
    ///
    pub fn execute_command(
        &self,
        cmd: Command,
    ) -> std::result::Result<mycelium_command::Result, Box<dyn std::error::Error>> {
        match &cmd.action {
            Action::Default => Ok(mycelium_command::Result::Some((
                None,
                Some("Search action not set.".to_string()),
                None,
                None,
                None,
            ))),
            Action::Archive(_id) => unimplemented!(),
            Action::Insert(item) => {
                let id = self
                    .data
                    .add(&cmd.tag, item)
                    .expect("Failed to add item to db.");
                self.data.save_all()?;
                Ok(mycelium_command::Result::Some((
                    Some(id),
                    None,
                    None,
                    None,
                    None,
                )))
            }
            Action::Select => match cmd.what {
                What::Index(t) => {
                    let result = self
                        .data
                        .search(cmd.tag.as_str(), vec![t.as_str()].as_slice())
                        .unwrap();
                    let result: Vec<Vec<u8>> = result.iter().map(|x| x.get_item()).collect();
                    Ok(mycelium_command::Result::Some((
                        None,
                        None,
                        None,
                        Some(result),
                        None,
                    )))
                }
                What::Id(id) => {
                    let result = self.data.get(cmd.tag.as_str(), &[id]).unwrap();
                    let result: Vec<Vec<u8>> = result.iter().map(|x| x.get_item()).collect();
                    Ok(mycelium_command::Result::Some((
                        None,
                        None,
                        None,
                        Some(result),
                        None,
                    )))
                }
                What::Default => {
                    self.data.db.load_tag(cmd.tag.as_str())?;
                    let result = self.data.db.get_tag(cmd.tag.as_str()).unwrap();
                    let result: ResultList = result.iter().map(|x| x.get_item()).collect();
                    Ok(mycelium_command::Result::Some((
                        None,
                        None,
                        None,
                        Some(result),
                        None,
                    )))
                }
            },
            Action::Update((_id, _item)) => unimplemented!(),
        }
    }
}