Added an entry point to the database.

This commit is contained in:
Jeff Baskin 2023-01-16 12:07:33 -05:00
parent fa9cbe6a25
commit 809bcb641b
2 changed files with 47 additions and 4 deletions

View File

@ -5,7 +5,7 @@ use std::{collections::HashMap, fmt, str};
pub struct Databases;
impl Databases {
fn new() -> Self {
pub fn new() -> Self {
Self {}
}
}
@ -17,7 +17,7 @@ pub enum CacheType {
}
impl CacheType {
fn entry_type(&self) -> String {
pub fn entry_type(&self) -> String {
match self {
CacheType::Raw(_) => "Raw".to_string(),
CacheType::DBMap(_) => "DBMap".to_string(),

View File

@ -7,7 +7,7 @@ use async_std::{
sync::{Arc, Mutex},
task::{sleep, spawn},
};
use cachetype::CacheType;
use cachetype::{CacheType, Databases};
use error::DBError;
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use std::{
@ -17,6 +17,7 @@ use std::{
};
const DATA: &str = "data";
const ENTRY: &str = "databases";
#[derive(Clone)]
struct CacheEntry {
@ -56,6 +57,7 @@ impl fmt::Display for CacheEntry {
pub struct MoreThanText {
cache: Arc<Mutex<HashMap<String, CacheEntry>>>,
dir: String,
entry: String,
}
impl MoreThanText {
@ -71,10 +73,24 @@ impl MoreThanText {
}
}
}
let output = Self {
let mut output = Self {
cache: Arc::new(Mutex::new(HashMap::new())),
dir: data_dir.to_str().unwrap().to_string(),
entry: "undeclared".to_string(),
};
let entry_file = Path::new(dir).join(ENTRY);
let id: String;
if entry_file.is_file().await {
let holder = read(entry_file).await.unwrap();
id = str::from_utf8(&holder).unwrap().to_string();
} else {
id = output
.add_entry(CacheType::DBMap(Databases::new()))
.await
.unwrap();
write(entry_file, id.as_bytes()).await.unwrap();
}
output.entry = id;
let looper = output.cache.clone();
spawn(async move {
let hold_time = Duration::from_secs(300);
@ -239,6 +255,33 @@ mod init {
}
};
}
#[async_std::test]
async fn creates_entry_point() {
let dir = tempdir().unwrap();
let db = MoreThanText::new(dir.path().to_str().unwrap())
.await
.unwrap();
let entry = dir.path().join(ENTRY);
assert!(entry.is_file(), "Did not create entry point file.");
let data = read(entry).await.unwrap();
let id = str::from_utf8(&data).unwrap();
let cache = db.get_entry(&id).await.unwrap();
assert_eq!(cache.data.entry_type(), "DBMap");
assert_eq!(db.entry, id);
}
#[async_std::test]
async fn use_existing_entry_point() {
let dir = tempdir().unwrap();
let db1 = MoreThanText::new(dir.path().to_str().unwrap())
.await
.unwrap();
let db2 = MoreThanText::new(dir.path().to_str().unwrap())
.await
.unwrap();
assert_eq!(db1.entry, db2.entry, "Did not read existing entry.");
}
}
#[cfg(test)]