use std::fmt;
use std::future::Future;
use std::path::Path;
use std::sync::Arc;
use std::time::SystemTime;
use super::oneshot::pending;
use crate::pool::Pool;
use crate::{Error, Options, Result};
#[cfg(any(feature = "kv", feature = "jobs"))]
const TRANSACTIONS: &str = "store";
#[derive(Clone)]
pub struct Store {
store: crate::Store,
pool: Arc<Pool>,
}
impl Store {
pub fn open(dir: impl AsRef<Path>, options: Options) -> Result<Store> {
crate::Store::open(dir, options).map(Store::from)
}
pub fn open_beside(dir: impl AsRef<Path>) -> Result<Store> {
crate::Store::open_beside(dir).map(Store::from)
}
pub fn blocking(&self) -> &crate::Store {
&self.store
}
pub fn dir(&self) -> &Path {
self.store.dir()
}
pub fn now(&self) -> SystemTime {
self.store.now()
}
pub fn close(&self) -> impl Future<Output = Result<()>> + Send + 'static {
let store = self.store.clone();
async move {
store.refuse_where_a_close_would_wait_for_itself()?;
let (answer, closed) = pending(format!("{store:?}: its close"));
std::thread::Builder::new()
.name("tinystore-close".to_owned())
.spawn(move || answer.send(store.close()))
.map_err(|error| Error::io("a store's close: its thread", error))?;
closed.await
}
}
#[cfg(any(feature = "kv", feature = "jobs"))]
pub fn tx<T, E, F>(&self, work: F) -> impl Future<Output = Result<T, E>> + Send + 'static
where
F: FnOnce(&crate::Tx<'_>) -> Result<T, E> + Send + 'static,
T: Send + 'static,
E: From<Error> + Send + 'static,
{
let (store, what) = (self.store.clone(), format!("{:?}: a transaction", self.store));
let ran = super::run::blocking(&self.pool, Some(TRANSACTIONS.to_owned()), what, move || Ok(store.tx(work)));
async move { ran.await.unwrap_or_else(|error| Err(E::from(error))) }
}
#[allow(dead_code, reason = "the engines' async handles take the pool from here")]
pub(crate) fn pool(&self) -> &Arc<Pool> {
&self.pool
}
}
impl From<crate::Store> for Store {
fn from(store: crate::Store) -> Store {
let pool = Pool::of_or_stopped(&store);
Store { store, pool }
}
}
impl fmt::Debug for Store {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.store, f)
}
}
#[cfg(test)]
#[path = "store_tests.rs"]
mod tests;