use std::fmt;
use std::future::{Future, poll_fn};
use std::pin::pin;
use std::sync::Arc;
use std::time::Duration;
use super::named;
use crate::aio::oneshot::pending;
use crate::aio::{Store, run};
use crate::cancel::{self, Captured};
use crate::kv::{Handed, Key, Value, WriteOptions};
use crate::pool::Pool;
use crate::{Error, Result};
#[must_use = "once's answers open with open()"]
pub struct OnceBuilder<V> {
builder: crate::kv::OnceBuilder<V>,
pool: Arc<Pool>,
}
impl Store {
pub fn once<V: Value>(&self, name: &str) -> OnceBuilder<V> {
OnceBuilder { builder: self.blocking().once(name), pool: Arc::clone(self.pool()) }
}
}
impl<V: Value> OnceBuilder<V> {
pub fn keep(self, keep: Duration) -> Self {
OnceBuilder { builder: self.builder.keep(keep), ..self }
}
pub fn open(self) -> Result<Once<V>> {
Ok(Once { once: self.builder.open()?, pool: self.pool })
}
}
pub struct Once<V> {
once: crate::kv::Once<V>,
pool: Arc<Pool>,
}
impl<V: Value> Once<V> {
pub fn run<K, E, W, F>(&self, key: K, work: W) -> impl Future<Output = Result<V, E>> + Send + use<K, V, E, W, F>
where
K: Key,
E: From<Error> + Send,
W: FnOnce() -> F + Send,
F: Future<Output = Result<V, E>> + Send,
{
let run = Run {
once: self.once.clone(),
pool: Arc::clone(&self.pool),
tokens: cancel::captured(),
key: key.text().into_owned(),
};
async move {
#[cfg(feature = "replication")]
if run.once.answers().is_copy() {
return run.at_home(work).await;
}
let handed = match run.claim().await? {
Start::Kept(answer) => return Ok(answer),
Start::Yours(handed) => *handed,
};
let mut function = pin!(work());
let answer = poll_fn(|context| handed.polling(|| function.as_mut().poll(context))).await?;
run.keep(handed, &answer).await;
Ok(answer)
}
}
pub fn get(&self, key: impl Key) -> impl Future<Output = Result<Option<V>>> + Send + 'static {
let (once, key) = (self.once.clone(), key.text().into_owned());
let what = named(once.answers().scope.shown_key(&key), "a get");
run::point(&self.pool, what, move || once.get(&*key))
}
pub fn delete(&self, key: impl Key) -> impl Future<Output = Result<bool>> + Send + 'static {
let (answers, key) = (self.once.answers().clone(), key.text().into_owned());
let what = named(answers.scope.shown_key(&key), "a delete");
run::write(&self.pool, what, move |answer| {
answers.remove_then(&key, WriteOptions::default(), move |found| answer.send(found));
})
}
pub fn under(&self, owner: impl Key) -> Once<V> {
Once { once: self.once.under(owner), pool: Arc::clone(&self.pool) }
}
pub fn blocking(&self) -> &crate::kv::Once<V> {
&self.once
}
}
struct Run<V> {
once: crate::kv::Once<V>,
pool: Arc<Pool>,
tokens: Captured,
key: String,
}
enum Start<V> {
Kept(V),
Yours(Box<Handed>),
}
impl<V: Value> Run<V> {
async fn claim(&self) -> Result<Start<V>> {
loop {
if let Some(answer) = self.kept().await? {
return Ok(Start::Kept(answer));
}
let (answer, ended) = pending(named(self.shown_key(), "a run under way"));
let Some(handed) = self.once.claim_then(&self.key, Box::new(move |unkept| answer.send(Ok(unkept))))? else {
match ended.await? {
Some(unkept) => return Ok(Start::Kept(self.once.unkept(&unkept)?)),
None => continue,
}
};
return match self.kept().await? {
Some(answer) => Ok(Start::Kept(answer)),
None => Ok(Start::Yours(Box::new(handed))),
};
}
}
fn keep(&self, handed: Handed, answer: &V) -> impl Future<Output = ()> + Send + 'static {
let kept = match self.once.answers().encode(&self.key, answer) {
Ok(raw) => {
let what = named(self.shown_key(), "a keep");
Some(run::write(&self.pool, what, move |done| handed.keep_then(raw, move || done.send(Ok(())))))
}
Err(error) => {
handed.not_kept(&error);
None
}
};
async move {
if let Some(kept) = kept {
let _ = kept.await;
}
}
}
async fn kept(&self) -> Result<Option<V>> {
let (once, key) = (self.once.clone(), self.key.clone());
let what = named(self.shown_key(), "a kept answer");
self.tokens.run(None, || run::point(&self.pool, what, move || once.get(&*key))).await
}
fn shown_key(&self) -> String {
self.once.answers().scope.shown_key(&self.key)
}
}
#[cfg(feature = "replication")]
impl<V: Value> Run<V> {
async fn at_home<E, W, F>(self, work: W) -> Result<V, E>
where
E: From<Error>,
W: FnOnce() -> F,
F: Future<Output = Result<V, E>>,
{
if let Some(answer) = self.kept().await? {
return Ok(answer);
}
let held = match self.claim_at_home().await? {
AtHome::Kept(answer) => return Ok(answer),
AtHome::Held(held) => held,
};
let answer = work().await;
let raw = match &answer {
Ok(value) => Some(self.once.answers().encode(&self.key, value)?),
Err(_) => None,
};
held.keep(named(self.shown_key(), "a keep at home"), raw).await;
answer
}
fn claim_at_home(&self) -> impl Future<Output = Result<AtHome<V>>> + Send + 'static {
let what = named(self.shown_key(), "a run claimed at home");
let (once, key) = (self.once.clone(), self.key.clone());
run::passed_on(what, move || {
let held = |token| HeldAtHome { once: Some(once.clone()), key: key.clone(), token };
once.claim_at_home(&key).map(|claimed| match claimed {
crate::kv::AtHome::Kept(answer) => AtHome::Kept(answer),
crate::kv::AtHome::Yours(token) => AtHome::Held(held(token)),
})
})
}
}
#[cfg(feature = "replication")]
enum AtHome<V: Value> {
Kept(V),
Held(HeldAtHome<V>),
}
#[cfg(feature = "replication")]
struct HeldAtHome<V: Value> {
once: Option<crate::kv::Once<V>>,
key: String,
token: u64,
}
#[cfg(feature = "replication")]
impl<V: Value> HeldAtHome<V> {
fn keep(mut self, what: String, raw: Option<crate::kv::Raw>) -> impl Future<Output = ()> + Send + 'static {
let (once, key, token) = (self.once.take(), self.key.clone(), self.token);
let kept = run::passed_on(what, move || {
if let Some(once) = once {
once.keep_at_home(&key, token, raw);
}
Ok(())
});
async move {
let _ = kept.await;
}
}
}
#[cfg(feature = "replication")]
impl<V: Value> Drop for HeldAtHome<V> {
fn drop(&mut self) {
if let Some(once) = self.once.take() {
let (key, token) = (std::mem::take(&mut self.key), self.token);
if let Err(error) = run::own_thread(move || once.keep_at_home(&key, token, None)) {
tracing::warn!(
target: "tinystore",
%error,
"a once run abandoned on a copy could not give its key back to the home, which holds it meanwhile",
);
}
}
}
}
impl<V: Value> From<crate::kv::Once<V>> for Once<V> {
fn from(once: crate::kv::Once<V>) -> Once<V> {
let pool = once.answers().scope.pool();
Once { once, pool }
}
}
impl<V> Clone for Once<V> {
fn clone(&self) -> Self {
Once { once: self.once.clone(), pool: Arc::clone(&self.pool) }
}
}
impl<V> fmt::Debug for Once<V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.once, f)
}
}
impl<V> fmt::Debug for OnceBuilder<V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.builder, f)
}
}
#[cfg(test)]
#[path = "once_tests.rs"]
mod tests;