use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
use std::time::Duration;
use crate::wire::Session;
pub use crate::wire::Wake;
use crate::wire::codec::Message;
use crate::wire::protocol::StoreOptions;
use crate::{Durability, Error, ErrorKind, Options, Result, Store, TestClock};
fn stores() -> MutexGuard<'static, HashMap<PathBuf, (Store, usize)>> {
static STORES: OnceLock<Mutex<HashMap<PathBuf, (Store, usize)>>> = OnceLock::new();
STORES.get_or_init(Mutex::default).lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn code(kind: ErrorKind) -> &'static str {
crate::wire::code_of(kind)
}
pub type Prove = Arc<dyn Fn(&[u8]) -> Vec<u8> + Send + Sync>;
pub type Stop = Arc<dyn Fn() + Send + Sync>;
pub type Greeted = Arc<dyn Fn(&str) + Send + Sync>;
pub type Admit = Arc<dyn Fn(Option<&str>) -> Option<Capability> + Send + Sync>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Capability {
Admin,
Data,
Read,
}
#[derive(Clone, Default)]
pub struct Connect {
pub wake: Option<Wake>,
pub prove: Option<Prove>,
pub stop: Option<Stop>,
pub clock: Option<Arc<TestClock>>,
pub admit: Option<Admit>,
pub greeted: Option<Greeted>,
}
impl fmt::Debug for Connect {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Connect")
.field("wake", &self.wake.is_some())
.field("prove", &self.prove.is_some())
.field("stop", &self.stop.is_some())
.field("clock", &self.clock)
.field("admit", &self.admit.is_some())
.field("greeted", &self.greeted.is_some())
.finish()
}
}
pub struct Pipe {
session: Session,
dir: Option<PathBuf>,
}
impl Pipe {
pub fn open(dir: impl AsRef<Path>, options: &[u8], wake: Option<Wake>) -> Result<Pipe> {
let dir = std::path::absolute(dir.as_ref()).map_err(|error| crate::Error::io("pipe: its directory", error))?;
let store = join(&dir, asked(options)?)?;
match Session::new(store, Connect { wake, ..Connect::default() }) {
Ok(session) => Ok(Pipe { session, dir: Some(dir) }),
Err(error) => {
leave(&dir);
Err(error)
}
}
}
pub fn connect(store: &Store, connect: Connect) -> Result<Pipe> {
Ok(Pipe { session: Session::new(store.clone(), connect)?, dir: None })
}
pub fn send(&self, frames: &[u8]) -> Vec<u8> {
self.session.receive(frames);
self.session.take_ready()
}
pub fn push(&self, frames: &[u8]) {
self.session.receive(frames);
}
pub fn recv(&self, wait: Duration) -> Vec<u8> {
self.session.take(wait)
}
pub fn send_into(&self, frames: &[u8], into: &mut [u8]) -> usize {
self.session.receive(frames);
self.session.take_ready_into(into)
}
pub fn recv_into(&self, wait: Duration, into: &mut [u8]) -> usize {
self.session.take_into(wait, into)
}
pub fn go_away(&self) {
self.session.go_away();
}
pub fn full(&self) -> bool {
self.session.full()
}
pub fn streams(&self) -> usize {
self.session.streams()
}
pub fn welcomed(&self) -> bool {
self.session.welcomed()
}
pub fn finished(&self) -> bool {
self.session.finished()
}
}
impl Drop for Pipe {
fn drop(&mut self) {
self.session.end();
if let Some(dir) = &self.dir {
leave(dir);
}
}
}
impl fmt::Debug for Pipe {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.dir {
Some(dir) => write!(f, "Pipe({})", dir.display()),
None => f.write_str("Pipe"),
}
}
}
#[derive(Default)]
struct Asked {
durability: Option<Durability>,
#[cfg(feature = "metrics")]
self_metrics: Option<crate::metrics::SelfMetrics>,
#[cfg(feature = "metrics")]
max_series: Option<u64>,
encryption_key_file: Option<PathBuf>,
#[cfg(feature = "replication")]
node: Option<crate::replication::Node>,
}
fn asked(options: &[u8]) -> Result<Asked> {
if options.is_empty() {
return Ok(Asked::default());
}
let asked = StoreOptions::decode(options)
.map_err(|refused| Error::invalid(format!("pipe: its options: {}", refused.message)))?;
let durability = asked.durability.map(|word| word.parse().map_err(|error: Error| error.within("pipe")));
let node_asked = asked.node
|| !asked.from.is_empty()
|| asked.serve.is_some()
|| asked.synchronous
|| asked.catalog
|| asked.insecure
|| !asked.synchronous_with.is_empty();
#[cfg(not(feature = "replication"))]
if node_asked {
return Err(Error::invalid("pipe: a node's options, and the library was built without replication"));
}
#[cfg(feature = "replication")]
let node = node_asked.then(|| crate::replication::Node {
from: asked.from,
serve: asked.serve,
files: (!asked.files.is_empty()).then_some(asked.files),
token: asked.token,
synchronous: asked.synchronous,
synchronous_with: asked.synchronous_with,
tls: None,
catalog: asked.catalog,
advertise: asked.advertise,
failover: None,
witness: false,
insecure: asked.insecure,
});
#[cfg(not(feature = "metrics"))]
if asked.self_metrics || asked.max_series.is_some() {
return Err(Error::invalid("pipe: the store's metrics, and the library was built without metrics"));
}
Ok(Asked {
durability: durability.transpose()?,
#[cfg(feature = "metrics")]
self_metrics: asked.self_metrics.then_some(crate::metrics::SelfMetrics { system: !asked.without_system }),
#[cfg(feature = "metrics")]
max_series: asked.max_series,
encryption_key_file: asked.encryption_key_file.map(PathBuf::from),
#[cfg(feature = "replication")]
node,
})
}
fn join(dir: &Path, asked: Asked) -> Result<Store> {
let mut stores = stores();
if let Some((store, pipes)) = stores.get_mut(dir) {
if let Some(durability) = asked.durability
&& store.durability() != Some(durability)
{
let (opened, instead) = match store.durability() {
None => ("no durability set, full but os for records and metrics".to_owned(), String::new()),
Some(opened) => (format!("durability {opened}"), format!("with {opened} or ")),
};
return Err(Error::invalid(format!(
"pipe: the store is open with {opened}, and asked for {durability}: open it {instead}without durability"
)));
}
if let Some(key_file) = &asked.encryption_key_file
&& store.encryption_key_file() != Some(key_file)
{
return Err(Error::invalid(format!(
"pipe: the store is open with another encryption key file than {}",
key_file.display()
)));
}
#[cfg(feature = "metrics")]
if asked.self_metrics.is_some() && !store.probe().listening() {
return Err(Error::invalid("pipe: the store is open without its own metrics, and asked for them"));
}
#[cfg(feature = "metrics")]
if let Some(max_series) = asked.max_series
&& store.max_series() != max_series
{
let opened = store.max_series();
return Err(Error::invalid(format!(
"pipe: the store is open with max_series {opened}, and asked for {max_series}: open it with \
{opened} or without max_series"
)));
}
#[cfg(feature = "replication")]
if asked.node.is_some() && store.node().is_none() {
return Err(Error::invalid("pipe: the store is open as no node, and asked to be one"));
}
*pipes += 1;
return Ok(store.clone());
}
let options = Options {
durability: asked.durability,
encryption_key_file: asked.encryption_key_file,
#[cfg(feature = "replication")]
node: asked.node,
#[cfg(feature = "metrics")]
self_metrics: asked.self_metrics,
#[cfg(feature = "metrics")]
max_series: asked.max_series.unwrap_or(crate::store::MAX_SERIES),
..Options::default()
};
let store = Store::open(dir, options)?;
stores.insert(dir.to_path_buf(), (store.clone(), 1));
Ok(store)
}
fn leave(dir: &Path) {
let mut stores = stores();
let Some((store, pipes)) = stores.get_mut(dir) else {
return;
};
*pipes -= 1;
if *pipes > 0 {
return;
}
let store = store.clone();
stores.remove(dir);
drop(stores);
if let Err(error) = store.close() {
tracing::warn!(target: "tinystore", %error, "a pipe's store did not close cleanly");
}
}
#[cfg(test)]
#[path = "pipe_fixture.rs"]
pub(crate) mod fixture;
#[cfg(test)]
#[path = "pipe_tests.rs"]
mod tests;