1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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!(),
        }
    }
}