use std::sync::Arc;
use rusqlite::Connection;
use super::engine::{Kv, Revision};
use super::path::{Branch, Key};
use crate::engine::Home;
use crate::sqlite::Tx;
use crate::{Error, Result};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Kind {
Values,
Encrypted,
Counters,
RateLimit,
Quota,
Once,
}
impl Kind {
pub(crate) fn role(self) -> &'static str {
match self {
Kind::Values => "values",
Kind::Encrypted => "encrypted values",
Kind::Counters => "counters",
Kind::RateLimit => "rate limit",
Kind::Quota => "quota",
Kind::Once => "once",
}
}
#[cfg(feature = "replication")]
pub(crate) fn of_role(role: &str) -> Option<Kind> {
[Kind::Values, Kind::Encrypted, Kind::Counters, Kind::RateLimit, Kind::Quota, Kind::Once]
.into_iter()
.find(|kind| kind.role() == role)
}
fn shown(self) -> &'static str {
match self {
Kind::Values | Kind::Encrypted => "bucket",
Kind::Counters => "counters",
Kind::RateLimit => "rate limit",
Kind::Quota => "quota",
Kind::Once => "once",
}
}
}
#[derive(Clone)]
pub(crate) struct Scope {
pub(crate) kv: Arc<Kv>,
pub(crate) id: i64,
name: Arc<str>,
kind: Kind,
branch: std::result::Result<Branch, String>,
}
impl Scope {
pub(crate) fn open(home: &Home, name: &str, kind: Kind) -> Result<Scope> {
let lent_by = match home {
Home::Store(_) => None,
Home::Shared(shared) => Some(shared.owner()),
};
let shown = || described(lent_by, kind, name);
check_name(name).map_err(|error| error.within(shown()))?;
let kv = Kv::at(home).map_err(|error| error.within(shown()))?;
let id = kv.name(name, kind).map_err(|error| error.within(shown()))?;
Ok(Scope { kv, id, name: name.into(), kind, branch: Ok(Branch::default()) })
}
#[cfg(feature = "wire")]
pub(crate) fn open_as_it_is(home: &Home, name: &str, kind: Kind) -> Result<Scope> {
let lent_by = match home {
Home::Store(_) => None,
Home::Shared(shared) => Some(shared.owner()),
};
let shown = || described(lent_by, kind, name);
check_name(name).map_err(|error| error.within(shown()))?;
let kv = Kv::at_as_it_is(home).map_err(|error| error.within(shown()))?;
let id = kv.name_as_it_is(name, kind).map_err(|error| error.within(shown()))?;
Ok(Scope { kv, id, name: name.into(), kind, branch: Ok(Branch::default()) })
}
pub(crate) fn under(&self, owner: impl Key) -> Scope {
let branch = match &self.branch {
Ok(branch) => branch.under(&owner.text()).map_err(|error| error.to_string()),
Err(invalid) => Err(invalid.clone()),
};
Scope { branch, ..self.clone() }
}
pub(crate) fn branch(&self) -> Result<&Branch> {
self.branch.as_ref().map_err(|invalid| Error::invalid(invalid.clone()).within(self.shown()))
}
#[cfg(feature = "replication")]
pub(crate) fn pass_on(
&self,
handle: &super::forward::Handle,
key: &str,
call: &super::forward::Call,
) -> Result<Vec<u8>> {
let store = self.kv.store().map_err(|error| error.within(self.shown_key(key)))?;
super::forward::pass_on(&store, handle, self.branch()?.owners(), key, call)
}
pub(crate) fn path(&self, key: &str) -> Result<Vec<u8>> {
self.branch()?.path(key).map_err(|error| error.within(self.shown()))
}
pub(crate) fn now(&self) -> i64 {
self.kv.now()
}
pub(crate) fn name(&self) -> &str {
&self.name
}
pub(crate) fn shown(&self) -> String {
described(self.kv.lent_by(), self.kind, &self.name)
}
pub(crate) fn shown_key(&self, key: &str) -> String {
match &self.branch {
Ok(branch) => format!("{}: {}", self.shown(), branch.shown_key(key)),
Err(_) => self.shown(),
}
}
pub(crate) fn shown_branch(&self) -> String {
match &self.branch {
Ok(branch) => format!("{}: {}", self.shown(), branch.shown()),
Err(_) => self.shown(),
}
}
pub(crate) fn write<T: Send + 'static>(
&self,
key: &str,
bytes: usize,
work: impl FnOnce(&Tx<'_>, &Revision) -> Result<T> + Send + 'static,
) -> Result<T> {
let revision = self.kv.revision();
self.kv.file().write(bytes, move |tx| work(tx, &revision)).map_err(|error| error.within(self.shown_key(key)))
}
#[cfg(any(feature = "wire", feature = "async"))]
pub(crate) fn submit<T: Send + 'static>(
&self,
key: &str,
bytes: usize,
work: impl FnOnce(&Tx<'_>, &Revision) -> Result<T> + Send + 'static,
done: impl FnOnce(Result<T>) + Send + 'static,
) {
let revision = self.kv.revision();
let shown = self.shown_key(key);
let answered = move |answer: Result<T>| done(answer.map_err(|error| error.within(shown)));
self.kv.file().submit(bytes, move |tx| work(tx, &revision), answered);
}
#[cfg(any(feature = "wire", feature = "async"))]
pub(crate) fn submit_made<T: Send + 'static>(
&self,
key: &str,
bytes: usize,
work: Result<impl FnOnce(&Tx<'_>, &Revision) -> Result<T> + Send + 'static>,
done: impl FnOnce(Result<T>) + Send + 'static,
) {
match work {
Ok(work) => self.submit(key, bytes, work, done),
Err(error) => done(Err(error)),
}
}
#[cfg(feature = "async")]
pub(crate) fn pool(&self) -> Arc<crate::pool::Pool> {
match self.kv.store() {
Ok(store) => crate::pool::Pool::of_or_stopped(&store),
Err(_) => crate::pool::Pool::stopped(),
}
}
pub(crate) fn read<T>(&self, key: &str, read: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
self.kv.file().read(read).map_err(|error| error.within(self.shown_key(key)))
}
}
impl std::fmt::Debug for Scope {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.shown())
}
}
fn described(lent_by: Option<&str>, kind: Kind, name: &str) -> String {
match lent_by {
Some(owner) => format!("{owner}: kv {} {name}", kind.shown()),
None => format!("kv {} {name}", kind.shown()),
}
}
pub(super) fn check_name(name: &str) -> Result<()> {
crate::text::check_name("the", name)
}