use std::collections::HashMap;
use std::fmt;
use std::sync::mpsc;
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::thread::{self, ThreadId};
use std::time::Duration;
use super::bucket::{Bucket, Expiry};
#[cfg(any(feature = "wire", feature = "replication"))]
use super::bucket::{Put, WriteOptions};
use super::path::Key;
use super::scope::{Kind, Scope};
#[cfg(any(feature = "wire", feature = "replication"))]
use super::value::Raw;
use super::value::Value;
use crate::engine::Home;
use crate::{Error, Result, Store};
const KEEP: Duration = Duration::from_secs(24 * 60 * 60);
#[must_use = "once's answers open with open()"]
pub struct OnceBuilder<V> {
store: Store,
name: String,
keep: Duration,
_value: std::marker::PhantomData<fn() -> V>,
}
impl Store {
pub fn once<V: Value>(&self, name: &str) -> OnceBuilder<V> {
OnceBuilder { store: self.clone(), name: name.to_owned(), keep: KEEP, _value: std::marker::PhantomData }
}
}
impl<V: Value> OnceBuilder<V> {
pub fn keep(mut self, keep: Duration) -> Self {
self.keep = keep;
self
}
pub fn open(self) -> Result<Once<V>> {
Ok(Once { answers: answers(&self.store, &self.name, self.keep)? })
}
}
#[cfg(any(feature = "wire", feature = "replication"))]
pub(crate) fn rows(store: &Store, name: &str, keep: Option<Duration>) -> Result<Bucket<()>> {
answers(store, name, keep.unwrap_or(KEEP))
}
fn answers<T>(store: &Store, name: &str, keep: Duration) -> Result<Bucket<T>> {
if keep.is_zero() {
return Err(Error::invalid("a keep of zero").within(format!("kv once {name}")));
}
let scope = Scope::open(&Home::Store(store.clone()), name, Kind::Once)?;
Ok(Bucket::new(scope, Expiry::Ttl(keep)))
}
#[cfg(any(feature = "wire", feature = "replication"))]
pub(crate) enum Hand {
Kept(Raw),
Yours(Handed),
Wait,
}
#[cfg(any(feature = "wire", feature = "replication"))]
pub(crate) fn hand(answers: &Bucket<()>, key: &str, waiter: Waiter) -> Result<Hand> {
if let Some(cell) = answers.read_cell(key)? {
return Ok(Hand::Kept(cell.raw));
}
let running = (answers.scope.id, answers.scope.path(key)?);
if !answers.scope.kv.runs().claim_or_wait(running.clone(), None, waiter)? {
return Ok(Hand::Wait);
}
let handed = Handed { answers: answers.clone(), key: key.to_owned(), running };
match answers.read_cell(key)? {
Some(cell) => Ok(Hand::Kept(cell.raw)),
None => Ok(Hand::Yours(handed)),
}
}
#[cfg(any(feature = "wire", feature = "replication"))]
pub(crate) struct Handed {
answers: Bucket<()>,
key: String,
running: (i64, Vec<u8>),
}
#[cfg(any(feature = "wire", feature = "replication"))]
impl Handed {
pub(crate) fn keep(self, answer: Option<Raw>) -> Result<()> {
match answer {
Some(raw) => self.answers.put_raw(&self.key, raw, WriteOptions::default(), Put::Always).map(|_| ()),
None => Ok(()),
}
}
}
#[cfg(any(feature = "wire", feature = "replication"))]
impl Drop for Handed {
fn drop(&mut self) {
self.answers.scope.kv.runs().release(&self.running);
}
}
#[cfg(any(feature = "wire", feature = "replication"))]
impl fmt::Debug for Handed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Handed({})", self.answers.scope.shown_key(&self.key))
}
}
pub struct Once<V> {
answers: Bucket<V>,
}
impl<V: Value> Once<V> {
pub fn under(&self, owner: impl Key) -> Once<V> {
Once { answers: self.answers.under(owner) }
}
pub fn run<E: From<Error>>(&self, key: impl Key, work: impl FnOnce() -> Result<V, E>) -> Result<V, E> {
let key = key.text();
#[cfg(feature = "replication")]
if self.answers.is_copy() {
return self.run_at_home(&key, work);
}
let claimed = loop {
if let Some(answer) = self.answers.get(&*key)? {
return Ok(answer);
}
match self.claim(&key)? {
Some(claim) => break claim,
None => continue,
}
};
if let Some(answer) = self.answers.get(&*key)? {
return Ok(answer);
}
let answer = work()?;
if let Err(error) = self.answers.set(&*key, &answer) {
tracing::warn!(
target: "tinystore",
%error,
"a once answer was not kept; the next run of its key runs again",
);
}
drop(claimed);
Ok(answer)
}
#[cfg(feature = "replication")]
fn run_at_home<E: From<Error>>(&self, key: &str, work: impl FnOnce() -> Result<V, E>) -> Result<V, E> {
if let Some(answer) = self.answers.get(key)? {
return Ok(answer);
}
let token = match self.answers.once_claim(key)? {
super::forward::Claimed::Kept(raw) => return Ok(super::bucket::decode(&raw)?),
super::forward::Claimed::Yours(token) => token,
};
let answer = work();
let raw = match &answer {
Ok(value) => Some(self.answers.encode(key, value)?),
Err(_) => None,
};
if let Err(error) = self.answers.once_keep(key, token, raw) {
tracing::warn!(
target: "tinystore",
%error,
"a once answer was not kept at its home; the next run of its key runs again",
);
}
answer
}
pub fn get(&self, key: impl Key) -> Result<Option<V>> {
self.answers.get(key)
}
pub fn delete(&self, key: impl Key) -> Result<bool> {
self.answers.delete(key)
}
fn claim(&self, key: &str) -> Result<Option<Claimed<'_>>> {
let running = (self.answers.scope.id, self.answers.scope.path(key)?);
let (ended, waiting) = mpsc::channel();
let runs = self.answers.scope.kv.runs();
let wake = Box::new(move || {
let _ = ended.send(());
});
let claimed = runs.claim_or_wait(running.clone(), Some(thread::current().id()), wake);
if claimed.map_err(|error| error.within(self.answers.scope.shown_key(key)))? {
return Ok(Some(Claimed { runs, running }));
}
let _ = waiting.recv();
Ok(None)
}
}
impl<V> Clone for Once<V> {
fn clone(&self) -> Self {
Once { answers: self.answers.clone() }
}
}
impl<V> fmt::Debug for Once<V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Once({:?})", self.answers.scope)
}
}
impl<V> fmt::Debug for OnceBuilder<V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "OnceBuilder({})", self.name)
}
}
pub(crate) type Waiter = Box<dyn FnOnce() + Send>;
#[derive(Default)]
pub(crate) struct Runs {
running: Mutex<Running>,
}
type Running = HashMap<(i64, Vec<u8>), Run>;
struct Run {
thread: Option<ThreadId>,
waiters: Vec<Waiter>,
}
impl Runs {
pub(crate) fn claim_or_wait(&self, key: (i64, Vec<u8>), thread: Option<ThreadId>, waiter: Waiter) -> Result<bool> {
let mut running = self.lock();
match running.get_mut(&key) {
Some(run) if thread.is_some() && run.thread == thread => {
Err(Error::invalid("a run of a key inside its own run would wait for itself"))
}
Some(run) => {
run.waiters.push(waiter);
Ok(false)
}
None => {
running.insert(key, Run { thread, waiters: Vec::new() });
Ok(true)
}
}
}
pub(crate) fn release(&self, key: &(i64, Vec<u8>)) {
let run = self.lock().remove(key);
for waiter in run.map(|run| run.waiters).unwrap_or_default() {
waiter();
}
}
fn lock(&self) -> MutexGuard<'_, Running> {
self.running.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl fmt::Debug for Runs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Runs({} running)", self.lock().len())
}
}
struct Claimed<'a> {
runs: &'a Runs,
running: (i64, Vec<u8>),
}
impl Drop for Claimed<'_> {
fn drop(&mut self) {
self.runs.release(&self.running);
}
}
#[cfg(test)]
#[path = "once_tests.rs"]
mod tests;