use std::collections::HashMap;
use std::fmt;
use std::sync::mpsc;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::thread::{self, ThreadId};
use std::time::Duration;
use super::bucket::{Bucket, Expiry};
#[cfg(any(feature = "wire", feature = "replication", feature = "async"))]
use super::bucket::{Put, WriteOptions};
use super::path::Key;
use super::scope::{Kind, Scope};
use super::value::{Raw, 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, unkept: None };
match answers.read_cell(key)? {
Some(cell) => Ok(Hand::Kept(cell.raw)),
None => Ok(Hand::Yours(handed)),
}
}
#[cfg(any(feature = "wire", feature = "replication", feature = "async"))]
pub(crate) struct Handed {
answers: Bucket<()>,
key: String,
running: (i64, Vec<u8>),
unkept: Option<Box<Raw>>,
}
#[cfg(any(feature = "wire", feature = "replication"))]
impl Handed {
pub(crate) fn keep(mut self, answer: Option<Raw>) {
let Some(raw) = answer else { return };
if let Err(error) = self.answers.put_raw(&self.key, raw.clone(), WriteOptions::default(), Put::Always) {
not_kept(&error);
self.unkept = Some(Box::new(raw));
}
}
}
#[cfg(any(feature = "wire", feature = "replication", feature = "async"))]
impl Drop for Handed {
fn drop(&mut self) {
self.answers.scope.kv.runs().release(&self.running, self.unkept.take().map(|raw| *raw));
}
}
#[cfg(any(feature = "wire", feature = "replication", feature = "async"))]
impl fmt::Debug for Handed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Handed({})", self.answers.scope.shown_key(&self.key))
}
}
#[cfg(feature = "async")]
impl Handed {
pub(crate) fn keep_then(mut self, raw: Raw, done: impl FnOnce() + Send + 'static) {
let (answers, key) = (self.answers.clone(), self.key.clone());
answers.put_raw_then(&key, (raw.clone(), WriteOptions::default(), Put::Always), move |kept| {
if let Err(error) = kept {
not_kept(&error);
self.unkept = Some(Box::new(raw));
}
drop(self);
done();
});
}
pub(crate) fn not_kept(self, error: &Error) {
not_kept(error);
}
pub(crate) fn polling<T>(&self, poll: impl FnOnce() -> T) -> T {
let runs = std::ptr::from_ref(self.answers.scope.kv.runs()).addr();
POLLING.with(|polling| polling.borrow_mut().push((runs, self.running.clone())));
let _unmark = Unmark;
poll()
}
}
#[cfg(feature = "async")]
thread_local! {
static POLLING: std::cell::RefCell<Polled> = const { std::cell::RefCell::new(Vec::new()) };
}
#[cfg(feature = "async")]
type Polled = Vec<(usize, (i64, Vec<u8>))>;
#[cfg(feature = "async")]
struct Unmark;
#[cfg(feature = "async")]
impl Drop for Unmark {
fn drop(&mut self) {
POLLING.with(|polling| polling.borrow_mut().pop());
}
}
#[cfg(feature = "replication")]
pub(crate) enum AtHome<V> {
Kept(V),
Yours(u64),
}
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 mut claimed = loop {
if let Some(answer) = self.answers.get(&*key)? {
return Ok(answer);
}
match self.claim(&key)? {
Claim::Yours(claimed) => break claimed,
Claim::Unkept(raw) => return Ok(super::bucket::decode(&raw)?),
Claim::Ended => continue,
}
};
if let Some(answer) = self.answers.get(&*key)? {
return Ok(answer);
}
let answer = work()?;
if let Err(error) = self.answers.set(&*key, &answer) {
not_kept(&error);
claimed.unkept = self.answers.encode(&key, &answer).ok();
}
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.claim_at_home(key)? {
AtHome::Kept(answer) => return Ok(answer),
AtHome::Yours(token) => token,
};
let answer = work();
let raw = match &answer {
Ok(value) => Some(self.answers.encode(key, value)?),
Err(_) => None,
};
self.keep_at_home(key, token, raw);
answer
}
#[cfg(feature = "replication")]
pub(crate) fn claim_at_home(&self, key: &str) -> Result<AtHome<V>> {
match self.answers.once_claim(key)? {
super::forward::Claimed::Kept(raw) => Ok(AtHome::Kept(super::bucket::decode(&raw)?)),
super::forward::Claimed::Yours(token) => Ok(AtHome::Yours(token)),
}
}
#[cfg(feature = "replication")]
pub(crate) fn keep_at_home(&self, key: &str, token: u64, raw: Option<Raw>) {
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",
);
}
}
#[cfg(feature = "async")]
pub(crate) fn answers(&self) -> &Bucket<V> {
&self.answers
}
#[cfg(feature = "async")]
pub(crate) fn claim_then(&self, key: &str, waiter: Waiter) -> Result<Option<Handed>> {
let running = (self.answers.scope.id, self.answers.scope.path(key)?);
let claimed = self.answers.scope.kv.runs().claim_or_wait(running.clone(), None, waiter);
if !claimed.map_err(|error| error.within(self.answers.scope.shown_key(key)))? {
return Ok(None);
}
Ok(Some(Handed { answers: self.answers.untyped(), key: key.to_owned(), running, unkept: None }))
}
#[cfg(feature = "async")]
pub(crate) fn unkept(&self, raw: &Raw) -> Result<V> {
super::bucket::decode(raw)
}
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<Claim<'_>> {
crate::polled::may_wait(|| format!("{}: a run", self.answers.scope.shown_key(key)))?;
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 |unkept| {
let _ = ended.send(unkept);
});
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(Claim::Yours(Claimed { runs, running, unkept: None }));
}
Ok(match waiting.recv() {
Ok(Some(raw)) => Claim::Unkept(raw),
_ => Claim::Ended,
})
}
}
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(Option<Arc<Raw>>) + 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 itself = || Error::invalid("a run of a key inside its own run would wait for itself");
if self.polled_here(&key) {
return Err(itself());
}
let mut running = self.lock();
match running.get_mut(&key) {
Some(run) if run.thread == Some(thread::current().id()) => Err(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>), unkept: Option<Raw>) {
let run = self.lock().remove(key);
let unkept = unkept.map(Arc::new);
for waiter in run.map(|run| run.waiters).unwrap_or_default() {
waiter(unkept.clone());
}
}
#[cfg(all(test, feature = "async"))]
pub(crate) fn under_way(&self) -> (usize, usize) {
let running = self.lock();
(running.len(), running.values().map(|run| run.waiters.len()).sum())
}
#[cfg(feature = "async")]
fn polled_here(&self, key: &(i64, Vec<u8>)) -> bool {
let runs = std::ptr::from_ref(self).addr();
POLLING.with(|polling| polling.borrow().iter().any(|(held, polled)| *held == runs && polled == key))
}
#[cfg(not(feature = "async"))]
fn polled_here(&self, _key: &(i64, Vec<u8>)) -> bool {
false
}
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())
}
}
enum Claim<'a> {
Yours(Claimed<'a>),
Unkept(Arc<Raw>),
Ended,
}
struct Claimed<'a> {
runs: &'a Runs,
running: (i64, Vec<u8>),
unkept: Option<Raw>,
}
impl Drop for Claimed<'_> {
fn drop(&mut self) {
self.runs.release(&self.running, self.unkept.take());
}
}
fn not_kept(error: &Error) {
tracing::warn!(
target: "tinystore",
%error,
"a once answer was not kept; the callers that waited have it, and the next run of its key runs again",
);
}
#[cfg(test)]
#[path = "once_tests.rs"]
mod tests;