Database is now stored as an entry.

This commit is contained in:
Jeff Baskin 2023-07-01 15:56:12 -04:00
parent de93ee1f2c
commit 4dad6f7a05
3 changed files with 69 additions and 23 deletions

View File

@ -1,7 +1,10 @@
use super::{ErrorCode, FromCache, MTTError, Store, ToCache, ENTRY}; use super::{Database, ErrorCode, FromCache, MTTError, Store, ToCache, ENTRY};
use async_std::{channel::Receiver, path::PathBuf}; use async_std::{channel::Receiver, path::PathBuf};
use rand::{distributions::Alphanumeric, thread_rng, Rng}; use rand::{distributions::Alphanumeric, thread_rng, Rng};
use std::{collections::{HashMap, VecDeque}, iter::Iterator}; use std::{
collections::{HashMap, VecDeque},
iter::Iterator,
};
struct IDGenerator { struct IDGenerator {
ids: Option<VecDeque<String>>, ids: Option<VecDeque<String>>,
@ -9,20 +12,20 @@ struct IDGenerator {
impl IDGenerator { impl IDGenerator {
fn new() -> Self { fn new() -> Self {
Self { Self { ids: None }
ids: None,
}
} }
fn with_ids<T, D>(ids: T) -> Self where T: Into<Vec<D>>, D: Into<String> { fn with_ids<T, D>(ids: T) -> Self
where
T: Into<Vec<D>>,
D: Into<String>,
{
let id_list = ids.into(); let id_list = ids.into();
let mut data = VecDeque::new(); let mut data = VecDeque::new();
for id in id_list { for id in id_list {
data.push_back(id.into()); data.push_back(id.into());
} }
Self { Self { ids: Some(data) }
ids: Some(data),
}
} }
} }
@ -33,10 +36,7 @@ impl Iterator for IDGenerator {
match &self.ids { match &self.ids {
Some(id_list) => { Some(id_list) => {
let mut ids = id_list.clone(); let mut ids = id_list.clone();
let output = match ids.pop_front() { let output = ids.pop_front();
Some(id) => Some(id.to_string()),
None => None,
};
self.ids = Some(ids); self.ids = Some(ids);
output output
} }
@ -71,7 +71,7 @@ mod genid {
} }
pub struct Cache { pub struct Cache {
data: HashMap<String, Store>, data: HashMap<String, FromCache>,
ids: IDGenerator, ids: IDGenerator,
} }
@ -81,13 +81,24 @@ impl Cache {
P: Into<PathBuf>, P: Into<PathBuf>,
{ {
let mut data = HashMap::new(); let mut data = HashMap::new();
data.insert(ENTRY.to_string(), Store::new()); data.insert(ENTRY.to_string(), FromCache::Str(Store::new()));
Self { Self {
data: data, data: data,
ids: IDGenerator::new(), ids: IDGenerator::new(),
} }
} }
async fn with_ids<P, T, D>(dir: P, ids: T) -> Self
where
P: Into<PathBuf>,
T: Into<Vec<D>>,
D: Into<String>,
{
let mut output = Self::new(dir).await;
output.ids = IDGenerator::with_ids(ids);
output
}
pub async fn listen(&mut self, listener: Receiver<ToCache>) { pub async fn listen(&mut self, listener: Receiver<ToCache>) {
loop { loop {
match listener.recv().await.unwrap() { match listener.recv().await.unwrap() {
@ -107,19 +118,31 @@ impl Cache {
{ {
let idd = id.into(); let idd = id.into();
match self.data.get(&idd) { match self.data.get(&idd) {
Some(store) => FromCache::Str(store.clone()), Some(data) => data.clone(),
None => FromCache::Error(MTTError::from_code(ErrorCode::IDNotFound(idd))), None => FromCache::Error(MTTError::from_code(ErrorCode::IDNotFound(idd))),
} }
} }
pub fn commit(&mut self, data: Store) -> FromCache { pub fn commit(&mut self, data: Store) -> FromCache {
let store = self.data.get_mut(ENTRY).unwrap(); let entry_data = self.data.get(ENTRY).unwrap();
let mut store = match entry_data {
FromCache::Str(ep) => ep.clone(),
_ => {
unreachable!()
}
};
for name in data.list() { for name in data.list() {
match store.add(name) { match store.add(name) {
Ok(_) => (), Ok(_) => {
self.data
.insert(self.ids.next().unwrap(), FromCache::DB(Database::new()));
}
Err(err) => return FromCache::Error(err), Err(err) => return FromCache::Error(err),
} }
} }
self.data
.insert(ENTRY.to_string(), FromCache::Str(store))
.unwrap();
FromCache::Ok FromCache::Ok
} }
} }
@ -173,6 +196,7 @@ mod engine {
#[async_std::test] #[async_std::test]
async fn commit_database() { async fn commit_database() {
// remove this one for the one below, maybe.
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let mut cache = Cache::new(dir.path()).await; let mut cache = Cache::new(dir.path()).await;
let mut store = Store::new(); let mut store = Store::new();
@ -185,6 +209,27 @@ mod engine {
_ => assert!(false, "{:?} is not FromCache::Str", output), _ => assert!(false, "{:?} is not FromCache::Str", output),
} }
} }
#[async_std::test]
async fn add_database_entry() {
let id = "an_id";
let name = "garfield";
let dir = tempdir().unwrap();
let mut cache = Cache::with_ids(dir.path(), [id]).await;
let mut store = Store::new();
store.add(name).unwrap();
cache.commit(store.clone());
let db_out = cache.get(id);
match db_out {
FromCache::DB(_) => (),
_ => assert!(
false,
"{:?} is not FromCache::DB -- cache is {:?}",
db_out, cache.data
),
}
// Add test that only ids are in the cache.
}
} }
#[cfg(test)] #[cfg(test)]

View File

@ -1,6 +1,6 @@
use std::{error::Error, fmt}; use std::{error::Error, fmt};
#[derive(Debug)] #[derive(Clone, Debug)]
pub enum ErrorCode { pub enum ErrorCode {
// General // General
Undefined(String), Undefined(String),
@ -53,7 +53,7 @@ mod errorcodes {
} }
} }
#[derive(Debug)] #[derive(Clone, Debug)]
pub struct MTTError { pub struct MTTError {
pub code: ErrorCode, pub code: ErrorCode,
} }

View File

@ -27,10 +27,11 @@ pub enum ToCache {
Commit(ToCacheMsg<Store>), Commit(ToCacheMsg<Store>),
} }
#[derive(Debug)] #[derive(Clone, Debug)]
pub enum FromCache { pub enum FromCache {
Ok, Ok,
Str(Store), Str(Store),
DB(Database),
Error(MTTError), Error(MTTError),
} }