use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::{Duration, SystemTime};
use super::named;
use crate::aio::oneshot::Answer;
use crate::aio::{Store, run};
use crate::cancel::{self, Captured};
use crate::kv::{
Entry, Key, PAGE_KEYS, Page, Proposed, Put, Stamp, TxBucket, UPDATE_ATTEMPTS, Value, Version, WriteOptions, kept,
};
use crate::pool::Pool;
use crate::transaction::sealed::Sealed;
use crate::{Result, Transaction, TxHandle};
#[must_use = "a bucket opens with open()"]
pub struct BucketBuilder<V> {
builder: crate::kv::BucketBuilder<V>,
pool: Arc<Pool>,
}
impl Store {
pub fn bucket<V: Value>(&self, name: &str) -> BucketBuilder<V> {
BucketBuilder::new(self.blocking().bucket(name), Arc::clone(self.pool()))
}
}
impl<V: Value> BucketBuilder<V> {
pub(crate) fn new(builder: crate::kv::BucketBuilder<V>, pool: Arc<Pool>) -> Self {
BucketBuilder { builder, pool }
}
pub fn ttl(self, ttl: Duration) -> Self {
BucketBuilder { builder: self.builder.ttl(ttl), ..self }
}
pub fn idle(self, idle: Duration) -> Self {
BucketBuilder { builder: self.builder.idle(idle), ..self }
}
pub fn encrypted(self) -> Self {
BucketBuilder { builder: self.builder.encrypted(), ..self }
}
pub fn open(self) -> Result<Bucket<V>> {
Ok(Bucket { bucket: self.builder.open()?, pool: self.pool })
}
}
pub struct Bucket<V> {
bucket: crate::kv::Bucket<V>,
pool: Arc<Pool>,
}
impl<V: Value> Bucket<V> {
pub fn set(&self, key: impl Key, value: &V) -> impl Future<Output = Result<()>> + Send + 'static {
let written = self.put(key.text().into_owned(), value, Put::Always);
async move { written.await.map(drop) }
}
pub fn create(&self, key: impl Key, value: &V) -> impl Future<Output = Result<bool>> + Send + 'static {
let written = self.put(key.text().into_owned(), value, Put::OnlyNew);
async move { written.await.map(|stamp| stamp.written) }
}
pub fn update(
&self,
key: impl Key,
change: impl FnMut(Option<V>) -> Option<V> + Send + 'static,
) -> impl Future<Output = Result<Option<V>>> + Send + 'static {
let (bucket, pool, key) = (self.bucket.clone(), Arc::clone(&self.pool), key.text().into_owned());
updated(bucket, pool, cancel::captured(), key, change)
}
pub fn key(&self, key: impl Key) -> KeyCall<'_, V> {
KeyCall { call: self.bucket.key(key), pool: &self.pool }
}
pub fn get(&self, key: impl Key) -> impl Future<Output = Result<Option<V>>> + Send + 'static {
let (bucket, key) = (self.bucket.clone(), key.text().into_owned());
let what = named(bucket.scope.shown_key(&key), "a get");
run::point(&self.pool, what, move || bucket.get(&*key))
}
pub fn entry(&self, key: impl Key) -> impl Future<Output = Result<Option<Entry<V>>>> + Send + 'static {
let (bucket, key) = (self.bucket.clone(), key.text().into_owned());
let what = named(bucket.scope.shown_key(&key), "an entry");
run::point(&self.pool, what, move || bucket.entry(&*key))
}
pub fn has(&self, key: impl Key) -> impl Future<Output = Result<bool>> + Send + 'static {
let (bucket, key) = (self.bucket.clone(), key.text().into_owned());
let what = named(bucket.scope.shown_key(&key), "a has");
run::point(&self.pool, what, move || bucket.has(&*key))
}
pub fn take(&self, key: impl Key) -> impl Future<Output = Result<Option<V>>> + Send + 'static {
take(&self.bucket, &self.pool, key.text().into_owned(), WriteOptions::default())
}
pub fn delete(&self, key: impl Key) -> impl Future<Output = Result<bool>> + Send + 'static {
remove(&self.bucket, &self.pool, key.text().into_owned(), WriteOptions::default())
}
pub fn expire(&self, key: impl Key, ttl: Duration) -> impl Future<Output = Result<bool>> + Send + 'static {
expire(&self.bucket, &self.pool, key.text().into_owned(), WriteOptions::default().ttl(ttl))
}
pub fn clear(&self) -> impl Future<Output = Result<()>> + Send + 'static {
let bucket = self.bucket.clone();
let what = named(bucket.scope.shown_branch(), "a clear");
run::write(&self.pool, what, move |answer| bucket.clear_then(move |cleared| answer.send(cleared)))
}
pub fn reseal(&self) -> impl Future<Output = Result<u64>> + Send + 'static {
let bucket = self.bucket.clone();
let what = named(bucket.scope.shown_branch(), "a reseal");
run::blocking(&self.pool, None, what, move || bucket.reseal())
}
pub fn list(&self, limit: usize, after: Option<&str>) -> impl Future<Output = Result<Page<V>>> + Send + 'static {
let (bucket, after) = (self.bucket.clone(), after.map(str::to_owned));
let what = named(bucket.scope.shown_branch(), "a page");
run::read(&self.pool, what, move || bucket.list(limit, after.as_deref()))
}
pub fn all(&self) -> All<V> {
All {
bucket: self.clone(),
tokens: cancel::captured(),
page: Vec::new().into_iter(),
next: None,
done: false,
reading: None,
}
}
pub fn under(&self, owner: impl Key) -> Bucket<V> {
Bucket { bucket: self.bucket.under(owner), pool: Arc::clone(&self.pool) }
}
pub fn blocking(&self) -> &crate::kv::Bucket<V> {
&self.bucket
}
fn put(&self, key: String, value: &V, put: Put) -> impl Future<Output = Result<Stamp>> + Send + 'static {
write(&self.bucket, &self.pool, key, value, (WriteOptions::default(), put))
}
}
impl Bucket<()> {
pub fn add(&self, key: impl Key) -> impl Future<Output = Result<bool>> + Send + 'static {
self.create(key, &())
}
}
impl<V: Value> From<crate::kv::Bucket<V>> for Bucket<V> {
fn from(bucket: crate::kv::Bucket<V>) -> Bucket<V> {
let pool = bucket.scope.pool();
Bucket { bucket, pool }
}
}
impl<V> Clone for Bucket<V> {
fn clone(&self) -> Self {
Bucket { bucket: self.bucket.clone(), pool: Arc::clone(&self.pool) }
}
}
impl<V> fmt::Debug for Bucket<V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.bucket, f)
}
}
impl<V> fmt::Debug for BucketBuilder<V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.builder, f)
}
}
impl<V> Sealed for Bucket<V> {}
impl<V: Value> TxHandle for Bucket<V> {
type InTx<'h>
= TxBucket<'h, V>
where
Self: 'h;
fn in_tx<'h>(&'h self, tx: &'h Transaction<'h>) -> TxBucket<'h, V> {
self.bucket.in_tx(tx)
}
}
#[must_use = "a key's call runs at its last step: set, create, take, delete or expire"]
pub struct KeyCall<'a, V> {
call: crate::kv::KeyCall<'a, V>,
pool: &'a Arc<Pool>,
}
impl<V: Value> KeyCall<'_, V> {
pub fn ttl(self, ttl: Duration) -> Self {
KeyCall { call: self.call.ttl(ttl), ..self }
}
pub fn expires_at(self, time: SystemTime) -> Self {
KeyCall { call: self.call.expires_at(time), ..self }
}
pub fn if_version(self, version: Version) -> Self {
KeyCall { call: self.call.if_version(version), ..self }
}
pub fn set(self, value: &V) -> impl Future<Output = Result<()>> + Send + 'static {
let written = self.put(value, Put::Always);
async move { written.await.map(drop) }
}
pub fn create(self, value: &V) -> impl Future<Output = Result<bool>> + Send + 'static {
let written = self.put(value, Put::OnlyNew);
async move { written.await.map(|stamp| stamp.written) }
}
pub fn take(self) -> impl Future<Output = Result<Option<V>>> + Send + 'static {
let refused = self.call.refuse_expiry("take");
let (pool, (bucket, key, options)) = (self.pool, self.call.into_parts());
let taken = refused.map(|()| take(bucket, pool, key, options));
async move { taken?.await }
}
pub fn delete(self) -> impl Future<Output = Result<bool>> + Send + 'static {
let refused = self.call.refuse_expiry("delete");
let (pool, (bucket, key, options)) = (self.pool, self.call.into_parts());
let removed = refused.map(|()| remove(bucket, pool, key, options));
async move { removed?.await }
}
pub fn expire(self) -> impl Future<Output = Result<bool>> + Send + 'static {
let (bucket, key, options) = self.call.into_parts();
expire(bucket, self.pool, key, options)
}
fn put(self, value: &V, put: Put) -> impl Future<Output = Result<Stamp>> + Send + 'static {
let (bucket, key, options) = self.call.into_parts();
write(bucket, self.pool, key, value, (options, put))
}
}
impl<V> fmt::Debug for KeyCall<'_, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.call, f)
}
}
fn write<V: Value>(
bucket: &crate::kv::Bucket<V>,
pool: &Arc<Pool>,
key: String,
value: &V,
(options, put): (WriteOptions, Put),
) -> impl Future<Output = Result<Stamp>> + Send + 'static {
let written = bucket.encode(&key, value).map(|raw| {
let bucket = bucket.clone();
let what = named(bucket.scope.shown_key(&key), "a write");
run::write(pool, what, move |answer| {
bucket.put_raw_then(&key, (raw, options, put), move |stamp| answer.send(stamp));
})
});
async move { written?.await }
}
async fn updated<V: Value>(
bucket: crate::kv::Bucket<V>,
pool: Arc<Pool>,
tokens: Captured,
key: String,
mut change: impl FnMut(Option<V>) -> Option<V> + Send,
) -> Result<Option<V>> {
let what = named(bucket.scope.shown_key(&key), "an update");
for _ in 0..UPDATE_ATTEMPTS {
let (reading, read_key) = (bucket.clone(), key.clone());
let read = || run::point(&pool, what.clone(), move || reading.read_cell(&read_key));
let found = tokens.run(None, read).await?;
let (value, write) = match bucket.proposed(&key, found, &mut change)? {
Proposed::Unchanged(current) => return Ok(current),
Proposed::Write(value, write) => (value, write),
};
let (writing, write_key) = (bucket.clone(), key.clone());
let submit = move |answer: Answer<Stamp>| {
writing.put_raw_then(&write_key, write, move |stamp| answer.send(stamp));
};
if kept(run::write(&pool, what.clone(), submit).await)? {
return Ok(Some(value));
}
}
Err(bucket.raced(&key))
}
fn take<V: Value>(
bucket: &crate::kv::Bucket<V>,
pool: &Arc<Pool>,
key: String,
options: WriteOptions,
) -> impl Future<Output = Result<Option<V>>> + Send + 'static {
let bucket = bucket.clone();
let what = named(bucket.scope.shown_key(&key), "a take");
run::write(pool, what, move |answer| bucket.take_then(&key, options, move |taken| answer.send(taken)))
}
fn remove<V: Value>(
bucket: &crate::kv::Bucket<V>,
pool: &Arc<Pool>,
key: String,
options: WriteOptions,
) -> impl Future<Output = Result<bool>> + Send + 'static {
let bucket = bucket.clone();
let what = named(bucket.scope.shown_key(&key), "a delete");
run::write(pool, what, move |answer| bucket.remove_then(&key, options, move |found| answer.send(found)))
}
fn expire<V: Value>(
bucket: &crate::kv::Bucket<V>,
pool: &Arc<Pool>,
key: String,
options: WriteOptions,
) -> impl Future<Output = Result<bool>> + Send + 'static {
let bucket = bucket.clone();
let what = named(bucket.scope.shown_key(&key), "an expire");
run::write(pool, what, move |answer| bucket.expire_then(&key, options, move |found| answer.send(found)))
}
pub struct All<V> {
bucket: Bucket<V>,
tokens: Captured,
page: std::vec::IntoIter<Entry<V>>,
next: Option<String>,
done: bool,
reading: Option<PageRead<V>>,
}
type PageRead<V> = Pin<Box<dyn Future<Output = Result<Page<V>>> + Send>>;
impl<V> Unpin for All<V> {}
impl<V: Value> futures_core::Stream for All<V> {
type Item = Result<Entry<V>>;
fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let all = self.get_mut();
loop {
if let Some(entry) = all.page.next() {
return Poll::Ready(Some(Ok(entry)));
}
if all.done {
return Poll::Ready(None);
}
let (bucket, tokens, after) = (&all.bucket, &all.tokens, all.next.as_deref());
let reading =
all.reading.get_or_insert_with(|| Box::pin(tokens.run(None, || bucket.list(PAGE_KEYS, after))));
let Poll::Ready(read) = reading.as_mut().poll(context) else {
return Poll::Pending;
};
all.reading = None;
match read {
Ok(page) => {
all.done = page.next.is_none();
all.next = page.next;
all.page = page.entries.into_iter();
}
Err(error) => {
all.done = true;
return Poll::Ready(Some(Err(error)));
}
}
}
}
}
impl<V> fmt::Debug for All<V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "All({:?})", self.bucket)
}
}
#[cfg(test)]
#[path = "bucket_tests.rs"]
mod tests;