use std::fmt;
use std::marker::PhantomData;
#[cfg(any(feature = "sql", feature = "wire"))]
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use rusqlite::Connection;
use super::cells::{self, Cell, MAX_VALUE};
use super::encrypted::Encrypted;
use super::engine::{Revision, next_version};
#[cfg(feature = "replication")]
use super::forward;
use super::key_call::KeyCall;
use super::path::Key;
use super::renewals::Renewal;
use super::scope::{Kind, Scope};
use super::value::{self, Raw, Value};
use crate::clock::{from_unix_millis, millis};
use crate::engine::Home;
#[cfg(any(feature = "sql", feature = "wire"))]
use crate::engine::SharedFile;
use crate::limits::VALUE_BYTES;
use crate::sqlite::Tx;
use crate::{Error, ErrorKind, Result, Store, unix_millis};
const CLEAR_BOUND: usize = 10_000;
pub const PAGE_KEYS: usize = 1000;
const REFRESHES: i64 = 30;
const RENEW_AT_ONCE: i64 = 60_000;
pub(crate) const UPDATE_ATTEMPTS: usize = 8;
#[must_use = "a bucket opens with open()"]
pub struct BucketBuilder<V> {
home: Home,
name: String,
expiry: Expiry,
encrypted: bool,
_value: PhantomData<fn() -> V>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Expiry {
Never,
Ttl(Duration),
Idle(Duration),
}
impl Store {
pub fn bucket<V: Value>(&self, name: &str) -> BucketBuilder<V> {
BucketBuilder::new(Home::Store(self.clone()), name)
}
}
impl<V: Value> BucketBuilder<V> {
#[cfg(feature = "replication")]
pub(crate) fn lent(home: Home, name: &str) -> Self {
BucketBuilder::new(home, name)
}
fn new(home: Home, name: &str) -> Self {
BucketBuilder { home, name: name.to_owned(), expiry: Expiry::Never, encrypted: false, _value: PhantomData }
}
#[cfg(any(feature = "sql", feature = "wire"))]
pub(crate) fn in_file(shared: Arc<SharedFile>, name: &str) -> Self {
BucketBuilder::new(Home::Shared(shared), name)
}
}
impl<V: Value> BucketBuilder<V> {
pub fn ttl(mut self, ttl: Duration) -> Self {
self.expiry = Expiry::Ttl(ttl);
self
}
pub fn idle(mut self, idle: Duration) -> Self {
self.expiry = Expiry::Idle(idle);
self
}
pub fn encrypted(mut self) -> Self {
self.encrypted = true;
self
}
pub fn open(self) -> Result<Bucket<V>> {
check_expiry(self.expiry).map_err(|error| error.within(format!("kv bucket {}", self.name)))?;
let kind = if self.encrypted { Kind::Encrypted } else { Kind::Values };
let scope = Scope::open(&self.home, &self.name, kind)?;
let encrypted = self.encrypted.then(|| Encrypted::of(&scope)).transpose()?;
Ok(Bucket { encrypted, ..Bucket::new(scope, self.expiry) })
}
}
pub struct Bucket<V> {
pub(crate) scope: Scope,
expiry: Expiry,
encrypted: Option<Encrypted>,
_value: PhantomData<fn() -> V>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Entry<V> {
pub key: String,
pub value: V,
pub version: Version,
pub expires_at: Option<SystemTime>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Version(i64);
impl Version {
#[cfg(any(feature = "wire", feature = "replication"))]
pub(crate) fn new(revision: i64) -> Version {
Version(revision)
}
#[cfg(any(feature = "wire", feature = "replication"))]
pub(crate) fn revision(self) -> i64 {
self.0
}
}
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl std::str::FromStr for Version {
type Err = Error;
fn from_str(text: &str) -> Result<Self> {
text.parse().map(Version).map_err(|_| Error::invalid(format!("{text:?} is not a version")))
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Page<V> {
pub entries: Vec<Entry<V>>,
pub next: Option<String>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct WriteOptions {
pub(crate) expires: Option<Expires>,
pub(crate) if_version: Option<Version>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Expires {
In(Duration),
At(SystemTime),
}
impl WriteOptions {
pub(crate) fn ttl(mut self, ttl: Duration) -> Self {
self.expires = Some(Expires::In(ttl));
self
}
pub(crate) fn expires_at(mut self, time: SystemTime) -> Self {
self.expires = Some(Expires::At(time));
self
}
pub(crate) fn if_version(mut self, version: Version) -> Self {
self.if_version = Some(version);
self
}
fn expires(self, now: i64) -> Option<i64> {
self.expires.map(|expires| match expires {
Expires::In(span) => now.saturating_add(millis(span)),
Expires::At(time) => unix_millis(time),
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Put {
Always,
OnlyNew,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Stamp {
pub(crate) written: bool,
pub(crate) version: Version,
pub(crate) expires: Option<i64>,
}
pub(crate) enum Proposed<V> {
Unchanged(Option<V>),
Write(V, (Raw, WriteOptions, Put)),
}
pub(crate) fn kept(written: Result<Stamp>) -> Result<bool> {
match written {
Ok(stamp) => Ok(stamp.written),
Err(error) if error.kind() == ErrorKind::Conflict => Ok(false),
Err(error) => Err(error),
}
}
pub(crate) trait Work<T>: FnOnce(&Tx<'_>, &Revision) -> Result<T> + Send + 'static {}
impl<T, F: FnOnce(&Tx<'_>, &Revision) -> Result<T> + Send + 'static> Work<T> for F {}
impl<V: Value> Bucket<V> {
pub fn set(&self, key: impl Key, value: &V) -> Result<()> {
self.put(&key.text(), value, WriteOptions::default(), Put::Always).map(|_| ())
}
pub fn create(&self, key: impl Key, value: &V) -> Result<bool> {
self.put(&key.text(), value, WriteOptions::default(), Put::OnlyNew)
}
pub fn update(&self, key: impl Key, mut change: impl FnMut(Option<V>) -> Option<V>) -> Result<Option<V>> {
let key = key.text();
for _ in 0..UPDATE_ATTEMPTS {
let found = self.read_cell(&key)?;
let (value, (raw, options, put)) = match self.proposed(&key, found, &mut change)? {
Proposed::Unchanged(current) => return Ok(current),
Proposed::Write(value, write) => (value, write),
};
if kept(self.put_raw(&key, raw, options, put))? {
return Ok(Some(value));
}
}
Err(self.raced(&key))
}
pub(crate) fn proposed(
&self,
key: &str,
found: Option<Cell>,
change: impl FnOnce(Option<V>) -> Option<V>,
) -> Result<Proposed<V>> {
let decoded = |cell: &Cell| decode::<V>(&cell.raw).map_err(|error| error.within(self.scope.shown_key(key)));
let Some(next) = change(found.as_ref().map(decoded).transpose()?) else {
return Ok(Proposed::Unchanged(found.as_ref().map(decoded).transpose()?));
};
let raw = self.encode(key, &next)?;
let write = match found {
Some(cell) => (raw, WriteOptions::default().if_version(Version(cell.version)), Put::Always),
None => (raw, WriteOptions::default(), Put::OnlyNew),
};
Ok(Proposed::Write(next, write))
}
pub(crate) fn raced(&self, key: &str) -> Error {
let raced = Error::new(ErrorKind::Conflict, "other writes came first each time it was tried");
raced.within(self.scope.shown_key(key))
}
pub fn key(&self, key: impl Key) -> KeyCall<'_, V> {
KeyCall::new(self, None, key.text().into_owned())
}
pub fn get(&self, key: impl Key) -> Result<Option<V>> {
Ok(self.entry(key)?.map(|entry| entry.value))
}
pub fn entry(&self, key: impl Key) -> Result<Option<Entry<V>>> {
let key = key.text();
let found = self.read_cell(&key)?;
found.map(|cell| self.entry_of(&key, cell)).transpose()
}
pub fn take(&self, key: impl Key) -> Result<Option<V>> {
let key = key.text();
#[cfg(feature = "replication")]
if self.is_copy() {
let cell = self.take_at_home(&key, WriteOptions::default())?;
return cell.map(|cell| decode::<V>(&cell.raw)).transpose();
}
let work = self.take_work(&key, WriteOptions::default())?;
self.scope.write(&key, 0, work)
}
pub fn list(&self, limit: usize, after: Option<&str>) -> Result<Page<V>> {
let limit = limit.clamp(1, PAGE_KEYS);
let rows = self
.scope
.kv
.file()
.read(|connection| self.page_rows(connection, limit, after))
.map_err(|error| error.within(self.scope.shown_branch()))?;
self.page_of(rows, limit)
}
pub fn all(&self) -> All<V> {
All { bucket: self.clone(), page: Vec::new().into_iter(), next: None, done: false }
}
fn put(&self, key: &str, value: &V, options: WriteOptions, put: Put) -> Result<bool> {
Ok(self.put_raw(key, self.encode(key, value)?, options, put)?.written)
}
pub(crate) fn encode(&self, key: &str, value: &V) -> Result<Raw> {
value::encode(value).map_err(|mismatch| {
Error::invalid(format!("a value it cannot keep: {mismatch}")).within(self.scope.shown_key(key))
})
}
#[cfg(feature = "async")]
pub(crate) fn take_then(
&self,
key: &str,
options: WriteOptions,
done: impl FnOnce(Result<Option<V>>) + Send + 'static,
) {
#[cfg(feature = "replication")]
if self.is_copy() {
let decoded = |cell: Result<Option<Cell>>| cell?.map(|cell| decode::<V>(&cell.raw)).transpose();
return self.take_cell_then(key, options, move |cell| done(decoded(cell)));
}
self.scope.submit_made(key, 0, self.take_work(key, options), done);
}
pub(crate) fn take_work(&self, key: &str, options: WriteOptions) -> Result<impl Work<Option<V>> + use<V>> {
let take = self.take_cell_work(key, options)?;
Ok(move |tx: &Tx<'_>, revision: &Revision| {
let cell = take(tx, revision)?;
cell.map(|cell| decode::<V>(&cell.raw)).transpose()
})
}
pub(crate) fn entry_of(&self, key: &str, cell: Cell) -> Result<Entry<V>> {
Ok(Entry {
key: key.to_owned(),
value: decode(&cell.raw).map_err(|error| error.within(self.scope.shown_key(key)))?,
version: Version(cell.version),
expires_at: cell.expires.map(from_unix_millis),
})
}
pub(crate) fn page_of(&self, rows: Vec<(Vec<u8>, Cell)>, limit: usize) -> Result<Page<V>> {
let branch = self.scope.branch()?;
let full = rows.len() == limit;
let mut entries = Vec::with_capacity(rows.len());
for (path, cell) in rows {
let key = branch.key_of(&path)?;
entries.push(self.entry_of(&key, cell)?);
}
let next = if full { entries.last().map(|entry| entry.key.clone()) } else { None };
Ok(Page { entries, next })
}
}
impl<V> Bucket<V> {
pub(crate) fn new(scope: Scope, expiry: Expiry) -> Bucket<V> {
Bucket { scope, expiry, encrypted: None, _value: PhantomData }
}
pub fn under(&self, owner: impl Key) -> Bucket<V> {
Bucket { encrypted: self.encrypted.clone(), ..Bucket::new(self.scope.under(owner), self.expiry) }
}
pub fn has(&self, key: impl Key) -> Result<bool> {
let key = key.text();
if matches!(self.expiry, Expiry::Idle(_)) {
return Ok(self.read_cell(&key)?.is_some());
}
let (id, path, now) = (self.scope.id, self.scope.path(&key)?, self.scope.now());
self.scope.read(&key, |connection| cells::has(connection, id, &path, now))
}
pub fn delete(&self, key: impl Key) -> Result<bool> {
self.remove(&key.text(), WriteOptions::default())
}
pub fn expire(&self, key: impl Key, ttl: Duration) -> Result<bool> {
self.expire_as(&key.text(), WriteOptions::default().ttl(ttl))
}
pub(crate) fn expire_as(&self, key: &str, options: WriteOptions) -> Result<bool> {
#[cfg(feature = "replication")]
if self.is_copy() {
return forward::found(&self.pass_on(key, forward::Call::Expire(options))?);
}
let work = self.expire_work(key, options)?;
self.scope.write(key, 0, work)
}
pub fn clear(&self) -> Result<()> {
#[cfg(feature = "replication")]
if self.is_copy() {
return self.pass_on("", forward::Call::Clear).map(drop);
}
let work = clear_work(&self.scope)?;
let revision = self.scope.kv.revision();
let shown = self.scope.shown_branch();
self.scope.kv.file().write(0, move |tx| work(tx, &revision)).map_err(|error| error.within(shown))
}
pub fn reseal(&self) -> Result<u64> {
let shown = self.scope.shown_branch();
let Some(encrypted) = self.encrypted.clone() else {
return Err(Error::invalid("a bucket that is not encrypted holds nothing sealed").within(shown));
};
#[cfg(feature = "replication")]
if self.is_copy() {
return Err(Error::invalid("a copy's values are sealed again by its home").within(shown));
}
let branch = self.scope.branch()?;
let (mut from, to) = branch.everything();
let whole = branch.prefix().is_empty();
let mut moved = 0;
loop {
let work = reseal_work(&self.scope, &encrypted, (from, to.clone()), whole);
let (count, next) = self.scope.kv.file().write(0, work).map_err(|error| error.within(&shown))?;
moved += count;
match next {
Some(next) => from = next,
None => return Ok(moved),
}
}
}
#[cfg(any(feature = "wire", feature = "async"))]
pub(crate) fn clear_then(&self, done: impl FnOnce(Result<()>) + Send + 'static) {
#[cfg(feature = "replication")]
if self.is_copy() {
return self.pass_on_then("", forward::Call::Clear, |_| Ok(()), done);
}
let work = match clear_work(&self.scope) {
Ok(work) => work,
Err(error) => return done(Err(error)),
};
let (revision, shown) = (self.scope.kv.revision(), self.scope.shown_branch());
let answered = move |cleared: Result<()>| done(cleared.map_err(|error| error.within(shown)));
self.scope.kv.file().submit(0, move |tx| work(tx, &revision), answered);
}
pub(crate) fn put_raw(&self, key: &str, raw: Raw, options: WriteOptions, put: Put) -> Result<Stamp> {
#[cfg(feature = "replication")]
if self.is_copy() {
return self
.pass_on(key, forward::Call::Put { raw, put, options })
.and_then(|bytes| forward::stamp(&bytes));
}
let (bytes, work) = self.put_work(key, raw, options, put)?;
self.scope.write(key, bytes, work)
}
#[cfg(any(feature = "wire", feature = "async"))]
pub(crate) fn put_raw_then(
&self,
key: &str,
(raw, options, put): (Raw, WriteOptions, Put),
done: impl FnOnce(Result<Stamp>) + Send + 'static,
) {
#[cfg(feature = "replication")]
if self.is_copy() {
return self.pass_on_then(key, forward::Call::Put { raw, put, options }, forward::stamp, done);
}
match self.put_work(key, raw, options, put) {
Ok((bytes, work)) => self.scope.submit(key, bytes, work, done),
Err(error) => done(Err(error)),
}
}
pub(crate) fn put_work(
&self,
key: &str,
raw: Raw,
options: WriteOptions,
put: Put,
) -> Result<(usize, impl Work<Stamp> + use<V>)> {
self.put_work_as(key, raw, options, put, true)
}
fn put_work_as(
&self,
key: &str,
raw: Raw,
options: WriteOptions,
put: Put,
seal: bool,
) -> Result<(usize, impl Work<Stamp> + use<V>)> {
if raw.len() > MAX_VALUE {
let too_large =
VALUE_BYTES.refuse(raw.len() as u64, format!("a value of {} bytes, over {MAX_VALUE}", raw.len()));
return Err(too_large.within(self.scope.shown_key(key)));
}
let now = self.scope.now();
let path = self.scope.path(key)?;
let raw =
if seal { self.kept(&path, raw).map_err(|error| error.within(self.scope.shown_key(key)))? } else { raw };
let bytes = raw.len();
let cell = PutCell {
id: self.scope.id,
path,
raw,
now,
put,
if_version: options.if_version,
given: options.expires(now),
default: self.default_expires(now),
keeps_its_expiry: !matches!(self.expiry, Expiry::Idle(_)),
};
let encrypted = self.encrypted.clone();
let work = move |tx: &Tx<'_>, revision: &Revision| {
if let Some(encrypted) = &encrypted {
encrypted.claim(tx)?;
}
cell.write(tx, revision)
};
Ok((bytes, work))
}
pub(crate) fn remove(&self, key: &str, options: WriteOptions) -> Result<bool> {
#[cfg(feature = "replication")]
if self.is_copy() {
return forward::found(&self.pass_on(key, forward::Call::Remove(options))?);
}
let work = self.remove_work(key, options)?;
self.scope.write(key, 0, work)
}
#[cfg(any(feature = "wire", feature = "async"))]
pub(crate) fn remove_then(
&self,
key: &str,
options: WriteOptions,
done: impl FnOnce(Result<bool>) + Send + 'static,
) {
#[cfg(feature = "replication")]
if self.is_copy() {
return self.pass_on_then(key, forward::Call::Remove(options), forward::found, done);
}
self.scope.submit_made(key, 0, self.remove_work(key, options), done);
}
#[cfg(any(feature = "wire", feature = "async"))]
pub(crate) fn expire_then(
&self,
key: &str,
options: WriteOptions,
done: impl FnOnce(Result<bool>) + Send + 'static,
) {
#[cfg(feature = "replication")]
if self.is_copy() {
return self.pass_on_then(key, forward::Call::Expire(options), forward::found, done);
}
self.scope.submit_made(key, 0, self.expire_work(key, options), done);
}
pub(crate) fn remove_work(&self, key: &str, options: WriteOptions) -> Result<impl Work<bool> + use<V>> {
let now = self.scope.now();
let (id, path, if_version) = (self.scope.id, self.scope.path(key)?, options.if_version);
Ok(move |tx: &Tx<'_>, _: &Revision| {
let Some(found) = live_at(tx, id, &path, now, if_version)? else {
return Ok(false);
};
cells::remove(tx, id, &path, found.spill)?;
Ok(true)
})
}
#[cfg(any(feature = "wire", all(feature = "async", feature = "replication")))]
pub(crate) fn take_cell_then(
&self,
key: &str,
options: WriteOptions,
done: impl FnOnce(Result<Option<Cell>>) + Send + 'static,
) {
#[cfg(feature = "replication")]
if self.is_copy() {
match self.unsealer(key) {
Ok(read) => self.pass_on_then(key, forward::Call::Take(options), read, done),
Err(error) => done(Err(error)),
}
return;
}
self.scope.submit_made(key, 0, self.take_cell_work(key, options), done);
}
pub(crate) fn take_cell_work(&self, key: &str, options: WriteOptions) -> Result<impl Work<Option<Cell>> + use<V>> {
let now = self.scope.now();
let (id, path, if_version) = (self.scope.id, self.scope.path(key)?, options.if_version);
let encrypted = self.encrypted.clone();
Ok(move |tx: &Tx<'_>, _: &Revision| {
let Some(found) = live_at(tx, id, &path, now, if_version)? else {
return Ok(None);
};
let cell = cells::live(tx, id, &path, now)?;
cells::remove(tx, id, &path, found.spill)?;
cell.map(|cell| opened(encrypted.as_ref(), &path, cell)).transpose()
})
}
pub(crate) fn expire_work(&self, key: &str, options: WriteOptions) -> Result<impl Work<bool> + use<V>> {
let now = self.scope.now();
let expires = options
.expires(now)
.ok_or_else(|| Error::invalid("an expiry needs a ttl or a time").within(self.scope.shown_key(key)))?;
let (id, path, if_version) = (self.scope.id, self.scope.path(key)?, options.if_version);
Ok(move |tx: &Tx<'_>, _: &Revision| {
if live_at(tx, id, &path, now, if_version)?.is_none() {
return Ok(false);
}
cells::set_expires(tx, id, &path, Some(expires))?;
Ok(true)
})
}
pub(crate) fn read_cell(&self, key: &str) -> Result<Option<Cell>> {
let (id, path, now) = (self.scope.id, self.scope.path(key)?, self.scope.now());
let read = |connection: &Connection| {
let found = cells::live(connection, id, &path, now)?;
found.map(|cell| opened(self.encrypted.as_ref(), &path, cell)).transpose()
};
let found = self.scope.read(key, read)?;
Ok(found.map(|cell| self.renew(key, path, cell, now)))
}
pub(crate) fn read_cell_in(&self, tx: &Tx<'_>, key: &str) -> Result<Option<Cell>> {
let (id, path, now) = (self.scope.id, self.scope.path(key)?, self.scope.now());
let Some(cell) = cells::live(tx, id, &path, now)? else {
return Ok(None);
};
let mut cell = opened(self.encrypted.as_ref(), &path, cell)?;
if let Some(renewal) = self.renewal_due(&cell, now)
&& cells::renew(tx, id, &path, (renewal.version, renewal.seen), renewal.until)?
{
cell.expires = Some(renewal.until);
}
Ok(Some(cell))
}
#[cfg(feature = "wire")]
pub(crate) fn list_rows(&self, limit: usize, after: Option<&str>) -> Result<Vec<(String, Cell)>> {
let limit = limit.clamp(1, PAGE_KEYS);
let rows = self
.scope
.kv
.file()
.read(|connection| self.page_rows(connection, limit, after))
.map_err(|error| error.within(self.scope.shown_branch()))?;
self.keyed(rows)
}
#[cfg(feature = "wire")]
pub(crate) fn keyed(&self, rows: Vec<(Vec<u8>, Cell)>) -> Result<Vec<(String, Cell)>> {
let branch = self.scope.branch()?;
rows.into_iter().map(|(path, cell)| Ok((branch.key_of(&path)?, cell))).collect()
}
pub(crate) fn page_rows(
&self,
connection: &Connection,
limit: usize,
after: Option<&str>,
) -> Result<Vec<(Vec<u8>, Cell)>> {
let (from, past) = self.scope.branch()?.own_keys_after(after);
let rows = cells::page(connection, self.scope.id, (&from, &past), self.scope.now(), limit)?;
let read = |(path, cell): (Vec<u8>, Cell)| {
let cell = opened(self.encrypted.as_ref(), &path, cell)?;
Ok((path, cell))
};
rows.into_iter().map(read).collect()
}
fn kept(&self, path: &[u8], raw: Raw) -> Result<Raw> {
match &self.encrypted {
Some(encrypted) => encrypted.seal(path, &raw),
None => Ok(raw),
}
}
fn renew(&self, key: &str, path: Vec<u8>, mut cell: Cell, now: i64) -> Cell {
let Some(renewal) = self.renewal_due(&cell, now) else {
return cell;
};
#[cfg(feature = "replication")]
if self.is_copy() {
if self.renew_at_home(key, path, renewal, now) {
cell.expires = Some(renewal.until);
}
return cell;
}
let renewals = self.scope.kv.renewals();
if renewal.seen - now >= RENEW_AT_ONCE {
renewals.ask(self.scope.id, path, renewal);
return cell;
}
let (id, written_path) = (self.scope.id, path.clone());
let at_once = move |tx: &Tx<'_>, _: &Revision| {
cells::renew(tx, id, &written_path, (renewal.version, renewal.seen), renewal.until)
};
match self.scope.write(key, 0, at_once) {
Ok(true) => cell.expires = Some(renewal.until),
Ok(false) => {}
Err(_) if crate::polled::waits_refused() => {}
Err(_) => renewals.ask(self.scope.id, path, renewal),
}
cell
}
fn renewal_due(&self, cell: &Cell, now: i64) -> Option<Renewal> {
let Expiry::Idle(term) = self.expiry else {
return None;
};
let (term, expires) = (millis(term), cell.expires?);
if expires - now > term - term / REFRESHES {
return None;
}
Some(Renewal { version: cell.version, seen: expires, until: now.saturating_add(term) })
}
fn default_expires(&self, now: i64) -> Option<i64> {
match self.expiry {
Expiry::Never => None,
Expiry::Ttl(span) | Expiry::Idle(span) => Some(now.saturating_add(millis(span))),
}
}
}
impl Bucket<()> {
pub fn add(&self, key: impl Key) -> Result<bool> {
self.create(key, &())
}
}
#[cfg(feature = "replication")]
impl<V> Bucket<V> {
pub(crate) fn is_copy(&self) -> bool {
self.scope.kv.file().is_copy()
}
pub(crate) fn pass_on(&self, key: &str, call: forward::Call) -> Result<Vec<u8>> {
let shown = || self.scope.shown_key(key);
let call = self.sealed(key, call).map_err(|error| error.within(shown()))?;
self.scope.pass_on(&self.handle(), key, &call)
}
fn handle(&self) -> forward::Handle {
let name = self.scope.name().to_owned();
let database = self.scope.kv.lent_by().and_then(crate::replication::database_of).map(str::to_owned);
forward::Handle::Bucket { name, expiry: self.expiry, encrypted: self.encrypted.is_some(), database }
}
fn renew_at_home(&self, key: &str, path: Vec<u8>, renewal: Renewal, now: i64) -> bool {
let (Ok(store), Ok(branch)) = (self.scope.kv.store(), self.scope.branch()) else { return false };
if store.is_beside() {
return false;
}
let request = forward::encode(&self.handle(), branch.owners(), key, &forward::Call::Renew(renewal));
let renewals = self.scope.kv.renewals();
if renewal.seen - now >= RENEW_AT_ONCE {
renewals.pass(self.scope.id, path, renewal, request);
return false;
}
renewals.pass_now(&store, (self.scope.id, path), renewal, request) == Some(true)
}
pub(crate) fn renew_as(&self, key: &str, renewal: Renewal) -> Result<bool> {
let (id, path) = (self.scope.id, self.scope.path(key)?);
if self.is_copy() {
return Ok(self.renew_at_home(key, path, renewal, self.scope.now()));
}
if renewal.seen - self.scope.now() >= RENEW_AT_ONCE {
self.scope.kv.renewals().ask(id, path, renewal);
return Ok(false);
}
self.scope.write(key, 0, move |tx: &Tx<'_>, _: &Revision| {
cells::renew(tx, id, &path, (renewal.version, renewal.seen), renewal.until)
})
}
fn sealed(&self, key: &str, call: forward::Call) -> Result<forward::Call> {
let Some(encrypted) = &self.encrypted else {
return Ok(call);
};
match call {
forward::Call::Put { raw, put, options } => {
let raw = encrypted.seal(&self.scope.path(key)?, &raw)?;
Ok(forward::Call::PutSealed { raw, key_id: encrypted.key_id(), put, options })
}
forward::Call::Take(options) => Ok(forward::Call::TakeSealed { options, key_id: encrypted.key_id() }),
call => Ok(call),
}
}
pub(crate) fn take_at_home(&self, key: &str, options: WriteOptions) -> Result<Option<Cell>> {
let answer = self.pass_on(key, forward::Call::Take(options))?;
self.unsealer(key)?(&answer)
}
fn unsealer(&self, key: &str) -> Result<impl FnOnce(&[u8]) -> Result<Option<Cell>> + Send + 'static + use<V>> {
let (encrypted, path, shown) = (self.encrypted.clone(), self.scope.path(key)?, self.scope.shown_key(key));
Ok(move |answer: &[u8]| {
let cell = forward::cell(answer)?;
cell.map(|cell| opened(encrypted.as_ref(), &path, cell)).transpose().map_err(|error| error.within(shown))
})
}
pub(crate) fn take_sealed(&self, key: &str, options: WriteOptions, key_id: &str) -> Result<Option<Cell>> {
let encrypted = self.shared_key(key, key_id)?;
if self.is_copy() {
let call = forward::Call::TakeSealed { options, key_id: key_id.to_owned() };
return forward::cell(&self.pass_on(key, call)?);
}
let path = self.scope.path(key)?;
let taken = self.scope.write(key, 0, self.take_cell_work(key, options)?)?;
let seal = |mut cell: Cell| -> Result<Cell> {
cell.raw = encrypted.seal(&path, &cell.raw)?;
Ok(cell)
};
taken.map(seal).transpose().map_err(|error| error.within(self.scope.shown_key(key)))
}
fn shared_key(&self, key: &str, key_id: &str) -> Result<&Encrypted> {
let Some(encrypted) = &self.encrypted else {
return Err(
Error::invalid("a sealed value for a bucket that is not encrypted").within(self.scope.shown_key(key))
);
};
if encrypted.key_id() != key_id {
return Err(Error::invalid(format!(
"a value sealed with the key {key_id}, and this store's is {}: a copy and its home share one key",
encrypted.key_id()
))
.within(self.scope.shown_key(key)));
}
Ok(encrypted)
}
pub(crate) fn put_sealed(
&self,
key: &str,
raw: Raw,
key_id: &str,
options: WriteOptions,
put: Put,
) -> Result<Stamp> {
self.shared_key(key, key_id)?;
let (bytes, work) = self.put_work_as(key, raw, options, put, false)?;
self.scope.write(key, bytes, work)
}
pub(crate) fn once_claim(&self, key: &str) -> Result<forward::Claimed> {
forward::claimed(&self.pass_on_once(key, &forward::Call::OnceClaim)?)
}
pub(crate) fn once_keep(&self, key: &str, token: u64, answer: Option<Raw>) -> Result<()> {
self.pass_on_once(key, &forward::Call::OnceKeep { token, answer }).map(drop)
}
fn pass_on_once(&self, key: &str, call: &forward::Call) -> Result<Vec<u8>> {
let shown = || self.scope.shown_key(key);
let keep = match self.expiry {
Expiry::Ttl(keep) => crate::clock::millis(keep) as u64,
_ => return Err(Error::internal("once's answers kept for no span").within(shown())),
};
let handle = forward::Handle::Once { name: self.scope.name().to_owned(), keep };
self.scope.pass_on(&handle, key, call).map_err(|error| error.within(shown()))
}
pub(crate) fn take_cell(&self, key: &str, options: WriteOptions) -> Result<Option<Cell>> {
if self.is_copy() {
return self.take_at_home(key, options);
}
let work = self.take_cell_work(key, options)?;
self.scope.write(key, 0, work)
}
#[cfg(any(feature = "wire", feature = "async"))]
fn pass_on_then<T: Send + 'static>(
&self,
key: &str,
call: forward::Call,
read: impl FnOnce(&[u8]) -> Result<T> + Send + 'static,
done: impl FnOnce(Result<T>) + Send + 'static,
) {
let (bucket, key) = (self.untyped(), key.to_owned());
std::thread::spawn(move || done(bucket.pass_on(&key, call).and_then(|bytes| read(&bytes))));
}
}
impl<V> Bucket<V> {
#[cfg(any(all(feature = "wire", feature = "replication"), feature = "async"))]
pub(crate) fn untyped(&self) -> Bucket<()> {
Bucket { encrypted: self.encrypted.clone(), ..Bucket::new(self.scope.clone(), self.expiry) }
}
}
impl<V> Clone for Bucket<V> {
fn clone(&self) -> Self {
Bucket { encrypted: self.encrypted.clone(), ..Bucket::new(self.scope.clone(), self.expiry) }
}
}
impl<V> fmt::Debug for Bucket<V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Bucket({:?})", self.scope)
}
}
impl<V> fmt::Debug for BucketBuilder<V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "BucketBuilder({})", self.name)
}
}
pub struct All<V> {
bucket: Bucket<V>,
page: std::vec::IntoIter<Entry<V>>,
next: Option<String>,
done: bool,
}
impl<V: Value> Iterator for All<V> {
type Item = Result<Entry<V>>;
fn next(&mut self) -> Option<Self::Item> {
loop {
if let Some(entry) = self.page.next() {
return Some(Ok(entry));
}
if self.done {
return None;
}
match self.bucket.list(PAGE_KEYS, self.next.as_deref()) {
Ok(page) => {
self.done = page.next.is_none();
self.next = page.next;
self.page = page.entries.into_iter();
}
Err(error) => {
self.done = true;
return Some(Err(error));
}
}
}
}
}
impl<V> fmt::Debug for All<V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "All({:?})", self.bucket.scope)
}
}
const RESEAL_BATCH: (usize, usize) = (1000, 8 << 20);
fn reseal_work(
scope: &Scope,
encrypted: &Encrypted,
(from, to): (Vec<u8>, Vec<u8>),
whole: bool,
) -> impl FnOnce(&Tx<'_>) -> Result<(u64, Option<Vec<u8>>)> + Send + 'static + use<> {
let (id, now, encrypted) = (scope.id, scope.now(), encrypted.clone());
move |tx: &Tx<'_>| {
let (cells, more) = cells::sealed_page(tx, id, (&from, &to), now, RESEAL_BATCH)?;
let mut moved = 0;
for cell in cells.iter().filter(|cell| !encrypted.sealed_it(&cell.bytes)) {
let opened = encrypted.open(&cell.path, &Raw::Bytes(cell.bytes.clone()))?;
let Raw::Bytes(sealed) = encrypted.seal(&cell.path, &opened)? else {
return Err(Error::internal("a value sealed as no bytes"));
};
cells::reseal(tx, id, cell, &sealed)?;
moved += 1;
}
if more {
let mut next = cells.last().map(|cell| cell.path.clone()).unwrap_or_default();
next.push(0);
return Ok((moved, Some(next)));
}
if whole {
cells::keep_bucket_key(tx, id, Some(&encrypted.sealing()))?;
}
Ok((moved, None))
}
}
pub(crate) fn clear_work(scope: &Scope) -> Result<impl Work<()> + use<>> {
let branch = scope.branch()?;
let (id, prefix, everything) = (scope.id, branch.prefix().to_vec(), branch.everything());
Ok(move |tx: &Tx<'_>, revision: &Revision| {
if prefix.is_empty() {
cells::keep_bucket_key(tx, id, None)?;
}
if cells::delete_under(tx, id, (&everything.0, &everything.1), CLEAR_BOUND)? {
return Ok(());
}
let cleared = next_version(revision, tx)?;
cells::mark_cleared(tx, id, &prefix, cleared)
})
}
fn opened(encrypted: Option<&Encrypted>, path: &[u8], mut cell: Cell) -> Result<Cell> {
if let Some(encrypted) = encrypted {
cell.raw = encrypted.open(path, &cell.raw)?;
}
Ok(cell)
}
pub(crate) fn decode<V: Value>(raw: &Raw) -> Result<V> {
value::decode(raw)
.map_err(|mismatch| Error::corrupt(format!("its value does not read as the bucket's type: {mismatch}")))
}
struct PutCell {
id: i64,
path: Vec<u8>,
raw: Raw,
now: i64,
put: Put,
if_version: Option<Version>,
given: Option<i64>,
default: Option<i64>,
keeps_its_expiry: bool,
}
impl PutCell {
fn write(self, tx: &Tx<'_>, revision: &Revision) -> Result<Stamp> {
let expires = self.given.or(self.default);
let keeps = self.keeps_its_expiry && self.given.is_none();
let alone = self.put == Put::Always && self.if_version.is_none() && !cells::spills(&self.raw);
if alone && (!keeps || expires.is_none()) {
let version = next_version(revision, tx)?;
if cells::set(tx, self.id, &self.path, (version, expires), &self.raw, keeps)? {
return Ok(Stamp { written: true, version: Version(version), expires });
}
}
self.read_then_write(tx, revision)
}
fn read_then_write(self, tx: &Tx<'_>, revision: &Revision) -> Result<Stamp> {
let current = cells::current(tx, self.id, &self.path, self.now)?;
let live = current.filter(|current| current.live);
if let (Put::OnlyNew, Some(live)) = (self.put, live) {
return Ok(Stamp { written: false, version: Version(live.version), expires: live.expires });
}
check_version(live.map(|live| live.version), self.if_version)?;
let expires = self.given.or(match live {
Some(live) if self.keeps_its_expiry => live.expires,
_ => self.default,
});
let version = next_version(revision, tx)?;
let spilled = current.and_then(|current| current.spill);
cells::put(tx, self.id, &self.path, (version, expires), &self.raw, spilled)?;
Ok(Stamp { written: true, version: Version(version), expires })
}
}
fn live_at(tx: &Tx<'_>, id: i64, path: &[u8], now: i64, if_version: Option<Version>) -> Result<Option<cells::Current>> {
let live = cells::current(tx, id, path, now)?.filter(|current| current.live);
check_version(live.map(|live| live.version), if_version)?;
Ok(live)
}
fn check_version(found: Option<i64>, wanted: Option<Version>) -> Result<()> {
match wanted {
Some(Version(wanted)) if found != Some(wanted) => Err(Error::new(
ErrorKind::Conflict,
match found {
Some(found) => format!("at version {found}, not {wanted}"),
None => format!("not there at version {wanted}"),
},
)),
_ => Ok(()),
}
}
pub(crate) fn check_expiry(expiry: Expiry) -> Result<()> {
match expiry {
Expiry::Ttl(span) | Expiry::Idle(span) if span.is_zero() => Err(Error::invalid("an expiry of zero")),
_ => Ok(()),
}
}
#[cfg(test)]
#[path = "bucket_tests.rs"]
mod tests;