morethantext-web/src/morethantext/mod.rs

108 lines
2.1 KiB
Rust

mod cache;
mod error;
mod store;
use async_std::{
channel::{unbounded, Sender},
path::PathBuf,
task::spawn,
};
use cache::Cache;
use error::{ErrorCode, MTTError};
use store::Store;
const ENTRY: &str = "EntryPoint";
#[derive(Debug)]
pub struct CacheGet {
id: String,
result: Sender<FromCache>,
}
#[derive(Debug)]
pub enum ToCache {
Get(CacheGet),
}
#[derive(Debug)]
pub enum FromCache {
Str(Store),
Error(MTTError),
}
#[derive(Clone, Debug)]
struct Data<D> {
id: Option<String>,
data: Option<D>,
}
impl<D> Data<D> {
fn from_id<S>(id: S) -> Self
where
S: Into<String>,
{
Self {
id: Some(id.into()),
data: None,
}
}
}
#[derive(Clone)]
pub struct MoreThanText {
to_cache: Sender<ToCache>,
entry: Data<Store>,
}
impl MoreThanText {
fn new(to_cache: Sender<ToCache>) -> Self {
Self {
to_cache: to_cache,
entry: Data::from_id(ENTRY),
}
}
async fn session(&self) -> Result<Store, MTTError> {
let (s, r) = unbounded();
let msg = CacheGet {
id: ENTRY.to_string(),
result: s,
};
self.to_cache.send(ToCache::Get(msg)).await.unwrap();
match r.recv().await.unwrap() {
FromCache::Str(store) => Ok(store),
FromCache::Error(err) => Err(err),
}
}
}
#[cfg(test)]
mod mtt {
use super::*;
use tempfile::tempdir;
#[async_std::test]
async fn create_new() {
let dir = tempdir().unwrap();
let mtt = start_db(dir.path()).await.unwrap();
assert_eq!(mtt.entry.id, Some(ENTRY.to_string()));
assert!(mtt.entry.data.is_none());
let store = mtt.session().await.unwrap();
let expected: Vec<String> = Vec::new();
assert_eq!(store.list(), expected);
}
}
pub async fn start_db<P>(dir: P) -> Result<MoreThanText, MTTError>
where
P: Into<PathBuf>,
{
let path = dir.into();
let (s, r) = unbounded();
spawn(async move {
let cache = Cache::new(path).await;
cache.listen(r).await;
});
Ok(MoreThanText::new(s))
}