1use std::fmt;
2use std::marker::PhantomData;
3use std::sync::Arc;
4use std::time::{Duration, SystemTime};
5
6use rusqlite::Connection;
7
8use super::cells::{self, Cell, MAX_VALUE};
9use super::encrypted::Encrypted;
10use super::engine::{Revision, next_version};
11#[cfg(feature = "replication")]
12use super::forward;
13use super::key_call::KeyCall;
14use super::path::Key;
15use super::renewals::Renewal;
16use super::scope::{Kind, Scope};
17use super::value::{self, Raw, Value};
18use crate::clock::{from_unix_millis, millis};
19use crate::engine::Home;
20#[cfg(any(feature = "sql", feature = "wire"))]
21use crate::engine::SharedFile;
22use crate::limits::VALUE_BYTES;
23use crate::sqlite::Tx;
24use crate::{Error, ErrorKind, Result, Store, unix_millis};
25
26const CLEAR_BOUND: usize = 10_000;
29
30pub const PAGE_KEYS: usize = 1000;
32
33const COUNT_KEYS: usize = 1 << 16;
36
37const REFRESHES: i64 = 30;
40const RENEW_AT_ONCE: i64 = 60_000;
41
42pub(crate) const UPDATE_ATTEMPTS: usize = 8;
45
46#[must_use = "a bucket opens with open()"]
49pub struct BucketBuilder<V> {
50 home: Home,
51 name: String,
52 expiry: Expiry,
53 encrypted: bool,
54 _value: PhantomData<fn() -> V>,
55}
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub(crate) enum Expiry {
60 Never,
61 Ttl(Duration),
63 Idle(Duration),
65}
66
67impl Store {
68 pub fn bucket<V: Value>(&self, name: &str) -> BucketBuilder<V> {
71 BucketBuilder::new(Home::Store(self.clone()), name)
72 }
73}
74
75impl<V: Value> BucketBuilder<V> {
76 #[cfg(feature = "replication")]
78 pub(crate) fn lent(home: Home, name: &str) -> Self {
79 BucketBuilder::new(home, name)
80 }
81
82 fn new(home: Home, name: &str) -> Self {
83 BucketBuilder { home, name: name.to_owned(), expiry: Expiry::Never, encrypted: false, _value: PhantomData }
84 }
85
86 #[cfg(any(feature = "sql", feature = "wire"))]
88 pub(crate) fn in_file(shared: Arc<SharedFile>, name: &str) -> Self {
89 BucketBuilder::new(Home::Shared(shared), name)
90 }
91}
92
93impl<V: Value> BucketBuilder<V> {
94 pub fn ttl(mut self, ttl: Duration) -> Self {
97 self.expiry = Expiry::Ttl(ttl);
98 self
99 }
100
101 pub fn idle(mut self, idle: Duration) -> Self {
103 self.expiry = Expiry::Idle(idle);
104 self
105 }
106
107 pub fn encrypted(mut self) -> Self {
122 self.encrypted = true;
123 self
124 }
125
126 pub fn open(self) -> Result<Bucket<V>> {
127 check_expiry(self.expiry).map_err(|error| error.within(format!("kv bucket {}", self.name)))?;
128 let kind = if self.encrypted { Kind::Encrypted } else { Kind::Values };
129 let scope = Scope::open(&self.home, &self.name, kind)?;
130 let encrypted = self.encrypted.then(|| Encrypted::of(&scope)).transpose()?;
131 Ok(Bucket { encrypted, ..Bucket::new(scope, self.expiry) })
132 }
133}
134
135pub struct Bucket<V> {
138 pub(crate) scope: Scope,
139 expiry: Expiry,
140 encrypted: Option<Encrypted>,
142 _value: PhantomData<fn() -> V>,
143}
144
145#[derive(Clone, Debug, PartialEq)]
147pub struct Entry<V> {
148 pub key: String,
149 pub value: V,
150 pub version: Version,
151 pub expires_at: Option<SystemTime>,
152}
153
154#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
157pub struct Version(i64);
158
159impl Version {
160 #[cfg(any(feature = "wire", feature = "replication"))]
161 pub(crate) fn new(revision: i64) -> Version {
162 Version(revision)
163 }
164
165 #[cfg(any(feature = "wire", feature = "replication"))]
166 pub(crate) fn revision(self) -> i64 {
167 self.0
168 }
169}
170
171impl fmt::Display for Version {
172 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173 self.0.fmt(f)
174 }
175}
176
177impl std::str::FromStr for Version {
178 type Err = Error;
179
180 fn from_str(text: &str) -> Result<Self> {
181 text.parse().map(Version).map_err(|_| Error::invalid(format!("{text:?} is not a version")))
182 }
183}
184
185#[derive(Clone, Debug, PartialEq)]
187pub struct Page<V> {
188 pub entries: Vec<Entry<V>>,
189 pub next: Option<String>,
191}
192
193#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
196pub(crate) struct WriteOptions {
197 pub(crate) expires: Option<Expires>,
198 pub(crate) if_version: Option<Version>,
199}
200
201#[derive(Clone, Copy, Debug, PartialEq, Eq)]
202pub(crate) enum Expires {
203 In(Duration),
204 At(SystemTime),
205}
206
207impl WriteOptions {
208 pub(crate) fn ttl(mut self, ttl: Duration) -> Self {
209 self.expires = Some(Expires::In(ttl));
210 self
211 }
212
213 pub(crate) fn expires_at(mut self, time: SystemTime) -> Self {
214 self.expires = Some(Expires::At(time));
215 self
216 }
217
218 pub(crate) fn if_version(mut self, version: Version) -> Self {
219 self.if_version = Some(version);
220 self
221 }
222
223 fn expires(self, now: i64) -> Option<i64> {
224 self.expires.map(|expires| match expires {
225 Expires::In(span) => now.saturating_add(millis(span)),
226 Expires::At(time) => unix_millis(time),
227 })
228 }
229
230 fn written_expires(self, now: i64) -> Result<Option<i64>> {
235 match self.expires {
236 Some(Expires::In(span)) if span.is_zero() => {
237 Err(Error::invalid("a ttl of zero, which writes a key already gone"))
238 }
239 _ => Ok(self.expires(now)),
240 }
241 }
242}
243
244#[derive(Clone, Copy, Debug, PartialEq, Eq)]
246pub(crate) enum Put {
247 Always,
248 OnlyNew,
249}
250
251#[derive(Clone, Copy, Debug, PartialEq, Eq)]
254pub(crate) struct Stamp {
255 pub(crate) written: bool,
256 pub(crate) version: Version,
257 pub(crate) expires: Option<i64>,
258}
259
260pub(crate) enum Proposed<V> {
262 Unchanged(Option<V>),
264 Write(V, (Raw, WriteOptions, Put)),
266}
267
268pub(crate) fn kept(written: Result<Stamp>) -> Result<bool> {
271 match written {
272 Ok(stamp) => Ok(stamp.written),
273 Err(error) if error.kind() == ErrorKind::Conflict => Ok(false),
274 Err(error) => Err(error),
275 }
276}
277
278pub(crate) trait Work<T>: FnOnce(&Tx<'_>, &Revision) -> Result<T> + Send + 'static {}
280
281impl<T, F: FnOnce(&Tx<'_>, &Revision) -> Result<T> + Send + 'static> Work<T> for F {}
282
283impl<V: Value> Bucket<V> {
284 pub fn set(&self, key: impl Key, value: &V) -> Result<()> {
287 self.put(&key.text(), value, WriteOptions::default(), Put::Always).map(|_| ())
288 }
289
290 pub fn create(&self, key: impl Key, value: &V) -> Result<bool> {
293 self.put(&key.text(), value, WriteOptions::default(), Put::OnlyNew)
294 }
295
296 pub fn update(&self, key: impl Key, mut change: impl FnMut(Option<V>) -> Option<V>) -> Result<Option<V>> {
322 let key = key.text();
323 for _ in 0..UPDATE_ATTEMPTS {
324 let found = self.read_cell(&key)?;
325 let (value, (raw, options, put)) = match self.proposed(&key, found, &mut change)? {
326 Proposed::Unchanged(current) => return Ok(current),
327 Proposed::Write(value, write) => (value, write),
328 };
329 if kept(self.put_raw(&key, raw, options, put))? {
330 return Ok(Some(value));
331 }
332 }
333 Err(self.raced(&key))
334 }
335
336 pub(crate) fn proposed(
340 &self,
341 key: &str,
342 found: Option<Cell>,
343 change: impl FnOnce(Option<V>) -> Option<V>,
344 ) -> Result<Proposed<V>> {
345 let decoded = |cell: &Cell| decode::<V>(&cell.raw).map_err(|error| error.within(self.scope.shown_key(key)));
346 let Some(next) = change(found.as_ref().map(decoded).transpose()?) else {
347 return Ok(Proposed::Unchanged(found.as_ref().map(decoded).transpose()?));
349 };
350 let raw = self.encode(key, &next)?;
351 let write = match found {
352 Some(cell) => (raw, WriteOptions::default().if_version(Version(cell.version)), Put::Always),
353 None => (raw, WriteOptions::default(), Put::OnlyNew),
354 };
355 Ok(Proposed::Write(next, write))
356 }
357
358 pub(crate) fn raced(&self, key: &str) -> Error {
360 let raced = Error::new(ErrorKind::Conflict, "other writes came first each time it was tried");
361 raced.within(self.scope.shown_key(key))
362 }
363
364 pub fn key(&self, key: impl Key) -> KeyCall<'_, V> {
368 KeyCall::new(self, None, key.text().into_owned())
369 }
370
371 pub fn get(&self, key: impl Key) -> Result<Option<V>> {
372 Ok(self.entry(key)?.map(|entry| entry.value))
373 }
374
375 pub fn entry(&self, key: impl Key) -> Result<Option<Entry<V>>> {
377 let key = key.text();
378 let found = self.read_cell(&key)?;
379 found.map(|cell| self.entry_of(&key, cell)).transpose()
380 }
381
382 pub fn take(&self, key: impl Key) -> Result<Option<V>> {
386 let key = key.text();
387 #[cfg(feature = "replication")]
388 if self.is_copy() {
389 let cell = self.take_at_home(&key, WriteOptions::default())?;
390 return cell.map(|cell| decode::<V>(&cell.raw)).transpose();
391 }
392 let work = self.take_work(&key, WriteOptions::default())?;
393 self.scope.write(&key, 0, work)
394 }
395
396 pub fn list(&self, limit: usize, after: Option<&str>) -> Result<Page<V>> {
400 let limit = limit.clamp(1, PAGE_KEYS);
401 let rows = self
402 .scope
403 .kv
404 .file()
405 .read(|connection| self.page_rows(connection, limit, after))
406 .map_err(|error| error.within(self.scope.shown_branch()))?;
407 self.page_of(rows, limit)
408 }
409
410 pub fn all(&self) -> All<V> {
414 All { bucket: self.clone(), page: Vec::new().into_iter(), next: None, done: false }
415 }
416
417 fn put(&self, key: &str, value: &V, options: WriteOptions, put: Put) -> Result<bool> {
418 Ok(self.put_raw(key, self.encode(key, value)?, options, put)?.written)
419 }
420
421 pub(crate) fn encode(&self, key: &str, value: &V) -> Result<Raw> {
422 value::encode(value).map_err(|mismatch| {
423 Error::invalid(format!("a value it cannot keep: {mismatch}")).within(self.scope.shown_key(key))
424 })
425 }
426
427 #[cfg(feature = "async")]
430 pub(crate) fn take_then(
431 &self,
432 key: &str,
433 options: WriteOptions,
434 done: impl FnOnce(Result<Option<V>>) + Send + 'static,
435 ) {
436 #[cfg(feature = "replication")]
437 if self.is_copy() {
438 let decoded = |cell: Result<Option<Cell>>| cell?.map(|cell| decode::<V>(&cell.raw)).transpose();
439 return self.take_cell_then(key, options, move |cell| done(decoded(cell)));
440 }
441 self.scope.submit_made(key, 0, self.take_work(key, options), done);
442 }
443
444 pub(crate) fn take_work(&self, key: &str, options: WriteOptions) -> Result<impl Work<Option<V>> + use<V>> {
445 let take = self.take_cell_work(key, options)?;
446 Ok(move |tx: &Tx<'_>, revision: &Revision| {
447 let cell = take(tx, revision)?;
448 cell.map(|cell| decode::<V>(&cell.raw)).transpose()
449 })
450 }
451
452 pub(crate) fn entry_of(&self, key: &str, cell: Cell) -> Result<Entry<V>> {
453 Ok(Entry {
454 key: key.to_owned(),
455 value: decode(&cell.raw).map_err(|error| error.within(self.scope.shown_key(key)))?,
456 version: Version(cell.version),
457 expires_at: cell.expires.map(from_unix_millis),
458 })
459 }
460
461 pub(crate) fn page_of(&self, rows: Vec<(Vec<u8>, Cell)>, limit: usize) -> Result<Page<V>> {
463 let branch = self.scope.branch()?;
464 let full = rows.len() == limit;
465 let mut entries = Vec::with_capacity(rows.len());
466 for (path, cell) in rows {
467 let key = branch.key_of(&path)?;
468 entries.push(self.entry_of(&key, cell)?);
469 }
470 let next = if full { entries.last().map(|entry| entry.key.clone()) } else { None };
471 Ok(Page { entries, next })
472 }
473}
474
475impl<V> Bucket<V> {
478 pub(crate) fn new(scope: Scope, expiry: Expiry) -> Bucket<V> {
479 Bucket { scope, expiry, encrypted: None, _value: PhantomData }
480 }
481
482 pub fn under(&self, owner: impl Key) -> Bucket<V> {
485 Bucket { encrypted: self.encrypted.clone(), ..Bucket::new(self.scope.under(owner), self.expiry) }
486 }
487
488 pub fn has(&self, key: impl Key) -> Result<bool> {
489 let key = key.text();
490 if matches!(self.expiry, Expiry::Idle(_)) {
491 return Ok(self.read_cell(&key)?.is_some());
492 }
493 let (id, path, now) = (self.scope.id, self.scope.path(&key)?, self.scope.now());
494 self.scope.read(&key, |connection| cells::has(connection, id, &path, now))
495 }
496
497 pub fn count(&self) -> Result<u64> {
503 let (mut after, past) = self.scope.branch()?.own_keys_after(None);
504 let (id, now) = (self.scope.id, self.scope.now());
505 let mut counted = 0;
506 loop {
507 let read = |connection: &Connection| cells::count(connection, id, (&after, &past), now, COUNT_KEYS);
508 let (keys, last) =
509 self.scope.kv.file().read(read).map_err(|error| error.within(self.scope.shown_branch()))?;
510 counted += keys as u64;
511 match last {
512 Some(last) if keys == COUNT_KEYS => after = last,
513 _ => return Ok(counted),
514 }
515 }
516 }
517
518 pub fn delete(&self, key: impl Key) -> Result<bool> {
520 self.remove(&key.text(), WriteOptions::default())
521 }
522
523 pub fn expire(&self, key: impl Key, ttl: Duration) -> Result<bool> {
526 self.expire_as(&key.text(), WriteOptions::default().ttl(ttl))
527 }
528
529 pub(crate) fn expire_as(&self, key: &str, options: WriteOptions) -> Result<bool> {
531 #[cfg(feature = "replication")]
532 if self.is_copy() {
533 return forward::found(&self.pass_on(key, forward::Call::Expire(options))?);
534 }
535 let work = self.expire_work(key, options)?;
536 self.scope.write(key, 0, work)
537 }
538
539 pub fn clear(&self) -> Result<()> {
542 #[cfg(feature = "replication")]
543 if self.is_copy() {
544 return self.pass_on("", forward::Call::Clear).map(drop);
545 }
546 let work = clear_work(&self.scope)?;
547 let revision = self.scope.kv.revision();
548 let shown = self.scope.shown_branch();
549 self.scope.kv.file().write(0, move |tx| work(tx, &revision)).map_err(|error| error.within(shown))
550 }
551
552 pub fn reseal(&self) -> Result<u64> {
560 let shown = self.scope.shown_branch();
561 let Some(encrypted) = self.encrypted.clone() else {
562 return Err(Error::invalid("a bucket that is not encrypted holds nothing sealed").within(shown));
563 };
564 #[cfg(feature = "replication")]
565 if self.is_copy() {
566 return Err(Error::invalid("a copy's values are sealed again by its home").within(shown));
567 }
568 let branch = self.scope.branch()?;
569 let (mut from, to) = branch.everything();
570 let whole = branch.prefix().is_empty();
571 let mut moved = 0;
572 loop {
573 let work = reseal_work(&self.scope, &encrypted, (from, to.clone()), whole);
574 let (count, next) = self.scope.kv.file().write(0, work).map_err(|error| error.within(&shown))?;
575 moved += count;
576 match next {
577 Some(next) => from = next,
578 None => return Ok(moved),
579 }
580 }
581 }
582
583 #[cfg(any(feature = "wire", feature = "async"))]
585 pub(crate) fn clear_then(&self, done: impl FnOnce(Result<()>) + Send + 'static) {
586 #[cfg(feature = "replication")]
587 if self.is_copy() {
588 return self.pass_on_then("", forward::Call::Clear, |_| Ok(()), done);
589 }
590 let work = match clear_work(&self.scope) {
591 Ok(work) => work,
592 Err(error) => return done(Err(error)),
593 };
594 let (revision, shown) = (self.scope.kv.revision(), self.scope.shown_branch());
595 let answered = move |cleared: Result<()>| done(cleared.map_err(|error| error.within(shown)));
596 self.scope.kv.file().submit(0, move |tx| work(tx, &revision), answered);
597 }
598
599 pub(crate) fn put_raw(&self, key: &str, raw: Raw, options: WriteOptions, put: Put) -> Result<Stamp> {
601 #[cfg(feature = "replication")]
602 if self.is_copy() {
603 return self
604 .pass_on(key, forward::Call::Put { raw, put, options })
605 .and_then(|bytes| forward::stamp(&bytes));
606 }
607 let (bytes, work) = self.put_work(key, raw, options, put)?;
608 self.scope.write(key, bytes, work)
609 }
610
611 #[cfg(any(feature = "wire", feature = "async"))]
613 pub(crate) fn put_raw_then(
614 &self,
615 key: &str,
616 (raw, options, put): (Raw, WriteOptions, Put),
617 done: impl FnOnce(Result<Stamp>) + Send + 'static,
618 ) {
619 #[cfg(feature = "replication")]
620 if self.is_copy() {
621 return self.pass_on_then(key, forward::Call::Put { raw, put, options }, forward::stamp, done);
622 }
623 match self.put_work(key, raw, options, put) {
624 Ok((bytes, work)) => self.scope.submit(key, bytes, work, done),
625 Err(error) => done(Err(error)),
626 }
627 }
628
629 pub(crate) fn put_work(
631 &self,
632 key: &str,
633 raw: Raw,
634 options: WriteOptions,
635 put: Put,
636 ) -> Result<(usize, impl Work<Stamp> + use<V>)> {
637 self.put_work_as(key, raw, options, put, true)
638 }
639
640 fn put_work_as(
643 &self,
644 key: &str,
645 raw: Raw,
646 options: WriteOptions,
647 put: Put,
648 seal: bool,
649 ) -> Result<(usize, impl Work<Stamp> + use<V>)> {
650 if raw.len() > MAX_VALUE {
651 let too_large =
652 VALUE_BYTES.refuse(raw.len() as u64, format!("a value of {} bytes, over {MAX_VALUE}", raw.len()));
653 return Err(too_large.within(self.scope.shown_key(key)));
654 }
655 let now = self.scope.now();
656 let given = options.written_expires(now).map_err(|error| error.within(self.scope.shown_key(key)))?;
657 let path = self.scope.path(key)?;
658 let raw =
659 if seal { self.kept(&path, raw).map_err(|error| error.within(self.scope.shown_key(key)))? } else { raw };
660 let bytes = raw.len();
661 let cell = PutCell {
662 id: self.scope.id,
663 path,
664 raw,
665 now,
666 put,
667 if_version: options.if_version,
668 given,
669 default: self.default_expires(now),
670 keeps_its_expiry: !matches!(self.expiry, Expiry::Idle(_)),
672 };
673 let encrypted = self.encrypted.clone();
674 let work = move |tx: &Tx<'_>, revision: &Revision| {
675 if let Some(encrypted) = &encrypted {
676 encrypted.claim(tx)?;
677 }
678 cell.write(tx, revision)
679 };
680 Ok((bytes, work))
681 }
682
683 pub(crate) fn remove(&self, key: &str, options: WriteOptions) -> Result<bool> {
686 #[cfg(feature = "replication")]
687 if self.is_copy() {
688 return forward::found(&self.pass_on(key, forward::Call::Remove(options))?);
689 }
690 let work = self.remove_work(key, options)?;
691 self.scope.write(key, 0, work)
692 }
693
694 #[cfg(any(feature = "wire", feature = "async"))]
696 pub(crate) fn remove_then(
697 &self,
698 key: &str,
699 options: WriteOptions,
700 done: impl FnOnce(Result<bool>) + Send + 'static,
701 ) {
702 #[cfg(feature = "replication")]
703 if self.is_copy() {
704 return self.pass_on_then(key, forward::Call::Remove(options), forward::found, done);
705 }
706 self.scope.submit_made(key, 0, self.remove_work(key, options), done);
707 }
708
709 #[cfg(any(feature = "wire", feature = "async"))]
711 pub(crate) fn expire_then(
712 &self,
713 key: &str,
714 options: WriteOptions,
715 done: impl FnOnce(Result<bool>) + Send + 'static,
716 ) {
717 #[cfg(feature = "replication")]
718 if self.is_copy() {
719 return self.pass_on_then(key, forward::Call::Expire(options), forward::found, done);
720 }
721 self.scope.submit_made(key, 0, self.expire_work(key, options), done);
722 }
723
724 pub(crate) fn remove_work(&self, key: &str, options: WriteOptions) -> Result<impl Work<bool> + use<V>> {
727 let now = self.scope.now();
728 let (id, path, if_version) = (self.scope.id, self.scope.path(key)?, options.if_version);
729 Ok(move |tx: &Tx<'_>, _: &Revision| {
730 let Some(found) = live_at(tx, id, &path, now, if_version)? else {
731 return Ok(false);
732 };
733 cells::remove(tx, id, &path, found.spill)?;
734 Ok(true)
735 })
736 }
737
738 #[cfg(any(feature = "wire", all(feature = "async", feature = "replication")))]
741 pub(crate) fn take_cell_then(
742 &self,
743 key: &str,
744 options: WriteOptions,
745 done: impl FnOnce(Result<Option<Cell>>) + Send + 'static,
746 ) {
747 #[cfg(feature = "replication")]
748 if self.is_copy() {
749 match self.unsealer(key) {
750 Ok(read) => self.pass_on_then(key, forward::Call::Take(options), read, done),
751 Err(error) => done(Err(error)),
752 }
753 return;
754 }
755 self.scope.submit_made(key, 0, self.take_cell_work(key, options), done);
756 }
757
758 pub(crate) fn take_cell_work(&self, key: &str, options: WriteOptions) -> Result<impl Work<Option<Cell>> + use<V>> {
761 let now = self.scope.now();
762 let (id, path, if_version) = (self.scope.id, self.scope.path(key)?, options.if_version);
763 let encrypted = self.encrypted.clone();
764 Ok(move |tx: &Tx<'_>, _: &Revision| {
765 let Some(found) = live_at(tx, id, &path, now, if_version)? else {
766 return Ok(None);
767 };
768 let cell = cells::live(tx, id, &path, now)?;
769 cells::remove(tx, id, &path, found.spill)?;
770 cell.map(|cell| opened(encrypted.as_ref(), &path, cell)).transpose()
771 })
772 }
773
774 pub(crate) fn expire_work(&self, key: &str, options: WriteOptions) -> Result<impl Work<bool> + use<V>> {
775 let now = self.scope.now();
776 let expires = options
777 .expires(now)
778 .ok_or_else(|| Error::invalid("an expiry needs a ttl or a time").within(self.scope.shown_key(key)))?;
779 let (id, path, if_version) = (self.scope.id, self.scope.path(key)?, options.if_version);
780 Ok(move |tx: &Tx<'_>, _: &Revision| {
781 if live_at(tx, id, &path, now, if_version)?.is_none() {
782 return Ok(false);
783 }
784 cells::set_expires(tx, id, &path, Some(expires))?;
785 Ok(true)
786 })
787 }
788
789 pub(crate) fn read_cell(&self, key: &str) -> Result<Option<Cell>> {
791 let (id, path, now) = (self.scope.id, self.scope.path(key)?, self.scope.now());
792 let read = |connection: &Connection| {
793 let found = cells::live(connection, id, &path, now)?;
794 found.map(|cell| opened(self.encrypted.as_ref(), &path, cell)).transpose()
795 };
796 let found = self.scope.read(key, read)?;
797 Ok(found.map(|cell| self.renew(key, path, cell, now)))
798 }
799
800 pub(crate) fn read_cell_in(&self, tx: &Tx<'_>, key: &str) -> Result<Option<Cell>> {
802 let (id, path, now) = (self.scope.id, self.scope.path(key)?, self.scope.now());
803 let Some(cell) = cells::live(tx, id, &path, now)? else {
804 return Ok(None);
805 };
806 let mut cell = opened(self.encrypted.as_ref(), &path, cell)?;
807 if let Some(renewal) = self.renewal_due(&cell, now)
808 && cells::renew(tx, id, &path, (renewal.version, renewal.seen), (renewal.until, now))?
809 {
810 cell.expires = Some(renewal.until);
811 }
812 Ok(Some(cell))
813 }
814
815 #[cfg(feature = "wire")]
818 pub(crate) fn list_rows(&self, limit: usize, after: Option<&str>) -> Result<Vec<(String, Cell)>> {
819 let limit = limit.clamp(1, PAGE_KEYS);
820 let rows = self
821 .scope
822 .kv
823 .file()
824 .read(|connection| self.page_rows(connection, limit, after))
825 .map_err(|error| error.within(self.scope.shown_branch()))?;
826 self.keyed(rows)
827 }
828
829 #[cfg(feature = "wire")]
831 pub(crate) fn keyed(&self, rows: Vec<(Vec<u8>, Cell)>) -> Result<Vec<(String, Cell)>> {
832 let branch = self.scope.branch()?;
833 rows.into_iter().map(|(path, cell)| Ok((branch.key_of(&path)?, cell))).collect()
834 }
835
836 pub(crate) fn page_rows(
838 &self,
839 connection: &Connection,
840 limit: usize,
841 after: Option<&str>,
842 ) -> Result<Vec<(Vec<u8>, Cell)>> {
843 let (from, past) = self.scope.branch()?.own_keys_after(after);
844 let rows = cells::page(connection, self.scope.id, (&from, &past), self.scope.now(), limit)?;
845 let read = |(path, cell): (Vec<u8>, Cell)| {
846 let cell = opened(self.encrypted.as_ref(), &path, cell)?;
847 Ok((path, cell))
848 };
849 rows.into_iter().map(read).collect()
850 }
851
852 fn kept(&self, path: &[u8], raw: Raw) -> Result<Raw> {
854 match &self.encrypted {
855 Some(encrypted) => encrypted.seal(path, &raw),
856 None => Ok(raw),
857 }
858 }
859
860 fn renew(&self, key: &str, path: Vec<u8>, mut cell: Cell, now: i64) -> Cell {
865 let Some(renewal) = self.renewal_due(&cell, now) else {
866 return cell;
867 };
868 #[cfg(feature = "replication")]
869 if self.is_copy() {
870 if self.renew_at_home(key, path, renewal, now) {
871 cell.expires = Some(renewal.until);
872 }
873 return cell;
874 }
875 let renewals = self.scope.kv.renewals();
876 if renewal.seen - now >= RENEW_AT_ONCE {
877 renewals.ask(self.scope.id, path, renewal);
878 return cell;
879 }
880 let (id, written_path, kv) = (self.scope.id, path.clone(), Arc::clone(&self.scope.kv));
881 let at_once = move |tx: &Tx<'_>, _: &Revision| {
882 cells::renew(tx, id, &written_path, (renewal.version, renewal.seen), (renewal.until, kv.now()))
883 };
884 match self.scope.write(key, 0, at_once) {
885 Ok(true) => cell.expires = Some(renewal.until),
886 Ok(false) => {}
887 Err(_) if crate::polled::waits_refused() => {}
889 Err(_) => renewals.ask(self.scope.id, path, renewal),
890 }
891 cell
892 }
893
894 fn renewal_due(&self, cell: &Cell, now: i64) -> Option<Renewal> {
895 let Expiry::Idle(term) = self.expiry else {
896 return None;
897 };
898 let (term, expires) = (millis(term), cell.expires?);
899 if expires - now > term - term / REFRESHES {
900 return None;
901 }
902 Some(Renewal { version: cell.version, seen: expires, until: now.saturating_add(term) })
903 }
904
905 fn default_expires(&self, now: i64) -> Option<i64> {
906 match self.expiry {
907 Expiry::Never => None,
908 Expiry::Ttl(span) | Expiry::Idle(span) => Some(now.saturating_add(millis(span))),
909 }
910 }
911}
912
913impl Bucket<()> {
914 pub fn add(&self, key: impl Key) -> Result<bool> {
917 self.create(key, &())
918 }
919}
920
921#[cfg(feature = "replication")]
923impl<V> Bucket<V> {
924 pub(crate) fn is_copy(&self) -> bool {
925 self.scope.kv.file().is_copy()
926 }
927
928 pub(crate) fn pass_on(&self, key: &str, call: forward::Call) -> Result<Vec<u8>> {
931 let shown = || self.scope.shown_key(key);
932 let call = self.sealed(key, call).map_err(|error| error.within(shown()))?;
933 self.scope.pass_on(&self.handle(), key, &call)
934 }
935
936 fn handle(&self) -> forward::Handle {
938 let name = self.scope.name().to_owned();
939 let database = self.scope.kv.lent_by().and_then(crate::replication::database_of).map(str::to_owned);
940 forward::Handle::Bucket { name, expiry: self.expiry, encrypted: self.encrypted.is_some(), database }
941 }
942
943 fn renew_at_home(&self, key: &str, path: Vec<u8>, renewal: Renewal, now: i64) -> bool {
950 let (Ok(store), Ok(branch)) = (self.scope.kv.store(), self.scope.branch()) else { return false };
951 if store.is_beside() {
952 return false;
953 }
954 let request = forward::encode(&self.handle(), branch.owners(), key, &forward::Call::Renew(renewal));
955 let renewals = self.scope.kv.renewals();
956 if renewal.seen - now >= RENEW_AT_ONCE {
957 renewals.pass(self.scope.id, path, renewal, request);
958 return false;
959 }
960 renewals.pass_now(&store, (self.scope.id, path), renewal, request) == Some(true)
961 }
962
963 pub(crate) fn renew_as(&self, key: &str, renewal: Renewal) -> Result<bool> {
968 let (id, path) = (self.scope.id, self.scope.path(key)?);
969 if self.is_copy() {
970 return Ok(self.renew_at_home(key, path, renewal, self.scope.now()));
971 }
972 if renewal.seen - self.scope.now() >= RENEW_AT_ONCE {
973 self.scope.kv.renewals().ask(id, path, renewal);
974 return Ok(false);
975 }
976 let kv = Arc::clone(&self.scope.kv);
977 self.scope.write(key, 0, move |tx: &Tx<'_>, _: &Revision| {
978 cells::renew(tx, id, &path, (renewal.version, renewal.seen), (renewal.until, kv.now()))
979 })
980 }
981
982 fn sealed(&self, key: &str, call: forward::Call) -> Result<forward::Call> {
985 let Some(encrypted) = &self.encrypted else {
986 return Ok(call);
987 };
988 match call {
989 forward::Call::Put { raw, put, options } => {
990 let raw = encrypted.seal(&self.scope.path(key)?, &raw)?;
991 Ok(forward::Call::PutSealed { raw, key_id: encrypted.key_id(), put, options })
992 }
993 forward::Call::Take(options) => Ok(forward::Call::TakeSealed { options, key_id: encrypted.key_id() }),
994 call => Ok(call),
995 }
996 }
997
998 pub(crate) fn take_at_home(&self, key: &str, options: WriteOptions) -> Result<Option<Cell>> {
1001 let answer = self.pass_on(key, forward::Call::Take(options))?;
1002 self.unsealer(key)?(&answer)
1003 }
1004
1005 fn unsealer(&self, key: &str) -> Result<impl FnOnce(&[u8]) -> Result<Option<Cell>> + Send + 'static + use<V>> {
1008 let (encrypted, path, shown) = (self.encrypted.clone(), self.scope.path(key)?, self.scope.shown_key(key));
1009 Ok(move |answer: &[u8]| {
1010 let cell = forward::cell(answer)?;
1011 cell.map(|cell| opened(encrypted.as_ref(), &path, cell)).transpose().map_err(|error| error.within(shown))
1012 })
1013 }
1014
1015 pub(crate) fn take_sealed(&self, key: &str, options: WriteOptions, key_id: &str) -> Result<Option<Cell>> {
1018 let encrypted = self.shared_key(key, key_id)?;
1019 if self.is_copy() {
1020 let call = forward::Call::TakeSealed { options, key_id: key_id.to_owned() };
1021 return forward::cell(&self.pass_on(key, call)?);
1022 }
1023 let path = self.scope.path(key)?;
1024 let taken = self.scope.write(key, 0, self.take_cell_work(key, options)?)?;
1025 let seal = |mut cell: Cell| -> Result<Cell> {
1026 cell.raw = encrypted.seal(&path, &cell.raw)?;
1027 Ok(cell)
1028 };
1029 taken.map(seal).transpose().map_err(|error| error.within(self.scope.shown_key(key)))
1030 }
1031
1032 fn shared_key(&self, key: &str, key_id: &str) -> Result<&Encrypted> {
1035 let Some(encrypted) = &self.encrypted else {
1036 return Err(
1037 Error::invalid("a sealed value for a bucket that is not encrypted").within(self.scope.shown_key(key))
1038 );
1039 };
1040 if encrypted.key_id() != key_id {
1041 return Err(Error::invalid(format!(
1042 "a value sealed with the key {key_id}, and this store's is {}: a copy and its home share one key",
1043 encrypted.key_id()
1044 ))
1045 .within(self.scope.shown_key(key)));
1046 }
1047 Ok(encrypted)
1048 }
1049
1050 pub(crate) fn put_sealed(
1053 &self,
1054 key: &str,
1055 raw: Raw,
1056 key_id: &str,
1057 options: WriteOptions,
1058 put: Put,
1059 ) -> Result<Stamp> {
1060 self.shared_key(key, key_id)?;
1061 let (bytes, work) = self.put_work_as(key, raw, options, put, false)?;
1062 self.scope.write(key, bytes, work)
1063 }
1064
1065 pub(crate) fn once_claim(&self, key: &str) -> Result<forward::Claimed> {
1067 forward::claimed(&self.pass_on_once(key, &forward::Call::OnceClaim)?)
1068 }
1069
1070 pub(crate) fn once_keep(&self, key: &str, token: u64, answer: Option<Raw>) -> Result<()> {
1072 self.pass_on_once(key, &forward::Call::OnceKeep { token, answer }).map(drop)
1073 }
1074
1075 fn pass_on_once(&self, key: &str, call: &forward::Call) -> Result<Vec<u8>> {
1076 let shown = || self.scope.shown_key(key);
1077 let keep = match self.expiry {
1078 Expiry::Ttl(keep) => crate::clock::millis(keep) as u64,
1079 _ => return Err(Error::internal("once's answers kept for no span").within(shown())),
1080 };
1081 let handle = forward::Handle::Once { name: self.scope.name().to_owned(), keep };
1082 self.scope.pass_on(&handle, key, call).map_err(|error| error.within(shown()))
1083 }
1084
1085 pub(crate) fn take_cell(&self, key: &str, options: WriteOptions) -> Result<Option<Cell>> {
1087 if self.is_copy() {
1088 return self.take_at_home(key, options);
1089 }
1090 let work = self.take_cell_work(key, options)?;
1091 self.scope.write(key, 0, work)
1092 }
1093
1094 #[cfg(any(feature = "wire", feature = "async"))]
1097 fn pass_on_then<T: Send + 'static>(
1098 &self,
1099 key: &str,
1100 call: forward::Call,
1101 read: impl FnOnce(&[u8]) -> Result<T> + Send + 'static,
1102 done: impl FnOnce(Result<T>) + Send + 'static,
1103 ) {
1104 let (bucket, key) = (self.untyped(), key.to_owned());
1105 std::thread::spawn(move || done(bucket.pass_on(&key, call).and_then(|bytes| read(&bytes))));
1106 }
1107}
1108
1109impl<V> Bucket<V> {
1110 #[cfg(any(all(feature = "wire", feature = "replication"), feature = "async"))]
1112 pub(crate) fn untyped(&self) -> Bucket<()> {
1113 Bucket { encrypted: self.encrypted.clone(), ..Bucket::new(self.scope.clone(), self.expiry) }
1114 }
1115}
1116
1117impl<V> Clone for Bucket<V> {
1118 fn clone(&self) -> Self {
1119 Bucket { encrypted: self.encrypted.clone(), ..Bucket::new(self.scope.clone(), self.expiry) }
1120 }
1121}
1122
1123impl<V> fmt::Debug for Bucket<V> {
1124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1125 write!(f, "Bucket({:?})", self.scope)
1126 }
1127}
1128
1129impl<V> fmt::Debug for BucketBuilder<V> {
1130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1131 write!(f, "BucketBuilder({})", self.name)
1132 }
1133}
1134
1135pub struct All<V> {
1137 bucket: Bucket<V>,
1138 page: std::vec::IntoIter<Entry<V>>,
1139 next: Option<String>,
1140 done: bool,
1141}
1142
1143impl<V: Value> Iterator for All<V> {
1144 type Item = Result<Entry<V>>;
1145
1146 fn next(&mut self) -> Option<Self::Item> {
1147 loop {
1148 if let Some(entry) = self.page.next() {
1149 return Some(Ok(entry));
1150 }
1151 if self.done {
1152 return None;
1153 }
1154 match self.bucket.list(PAGE_KEYS, self.next.as_deref()) {
1155 Ok(page) => {
1156 self.done = page.next.is_none();
1157 self.next = page.next;
1158 self.page = page.entries.into_iter();
1159 }
1160 Err(error) => {
1161 self.done = true;
1162 return Some(Err(error));
1163 }
1164 }
1165 }
1166 }
1167}
1168
1169impl<V> fmt::Debug for All<V> {
1170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1171 write!(f, "All({:?})", self.bucket.scope)
1172 }
1173}
1174
1175const RESEAL_BATCH: (usize, usize) = (1000, 8 << 20);
1178
1179fn reseal_work(
1184 scope: &Scope,
1185 encrypted: &Encrypted,
1186 (from, to): (Vec<u8>, Vec<u8>),
1187 whole: bool,
1188) -> impl FnOnce(&Tx<'_>) -> Result<(u64, Option<Vec<u8>>)> + Send + 'static + use<> {
1189 let (id, now, encrypted) = (scope.id, scope.now(), encrypted.clone());
1190 move |tx: &Tx<'_>| {
1191 let (cells, more) = cells::sealed_page(tx, id, (&from, &to), now, RESEAL_BATCH)?;
1192 let mut moved = 0;
1193 for cell in cells.iter().filter(|cell| !encrypted.sealed_it(&cell.bytes)) {
1194 let opened = encrypted.open(&cell.path, &Raw::Bytes(cell.bytes.clone()))?;
1195 let Raw::Bytes(sealed) = encrypted.seal(&cell.path, &opened)? else {
1196 return Err(Error::internal("a value sealed as no bytes"));
1197 };
1198 cells::reseal(tx, id, cell, &sealed)?;
1199 moved += 1;
1200 }
1201 if more {
1202 let mut next = cells.last().map(|cell| cell.path.clone()).unwrap_or_default();
1203 next.push(0);
1204 return Ok((moved, Some(next)));
1205 }
1206 if whole {
1207 cells::keep_bucket_key(tx, id, Some(&encrypted.sealing()))?;
1208 }
1209 Ok((moved, None))
1210 }
1211}
1212
1213pub(crate) fn clear_work(scope: &Scope) -> Result<impl Work<()> + use<>> {
1216 let branch = scope.branch()?;
1217 let (id, prefix, everything) = (scope.id, branch.prefix().to_vec(), branch.everything());
1218 Ok(move |tx: &Tx<'_>, revision: &Revision| {
1219 if prefix.is_empty() {
1221 cells::keep_bucket_key(tx, id, None)?;
1222 }
1223 if cells::delete_under(tx, id, (&everything.0, &everything.1), CLEAR_BOUND)? {
1224 return Ok(());
1225 }
1226 let cleared = next_version(revision, tx)?;
1227 cells::mark_cleared(tx, id, &prefix, cleared)
1228 })
1229}
1230
1231fn opened(encrypted: Option<&Encrypted>, path: &[u8], mut cell: Cell) -> Result<Cell> {
1234 if let Some(encrypted) = encrypted {
1235 cell.raw = encrypted.open(path, &cell.raw)?;
1236 }
1237 Ok(cell)
1238}
1239
1240pub(crate) fn decode<V: Value>(raw: &Raw) -> Result<V> {
1242 value::decode(raw)
1243 .map_err(|mismatch| Error::corrupt(format!("its value does not read as the bucket's type: {mismatch}")))
1244}
1245
1246struct PutCell {
1248 id: i64,
1249 path: Vec<u8>,
1250 raw: Raw,
1251 now: i64,
1252 put: Put,
1253 if_version: Option<Version>,
1254 given: Option<i64>,
1256 default: Option<i64>,
1258 keeps_its_expiry: bool,
1260}
1261
1262impl PutCell {
1263 fn write(self, tx: &Tx<'_>, revision: &Revision) -> Result<Stamp> {
1269 let expires = self.given.or(self.default);
1270 let keeps = self.keeps_its_expiry && self.given.is_none();
1271 let alone = self.put == Put::Always && self.if_version.is_none() && !cells::spills(&self.raw);
1272 if alone && (!keeps || expires.is_none()) {
1273 let version = next_version(revision, tx)?;
1274 if cells::set(tx, self.id, &self.path, (version, expires), &self.raw, keeps)? {
1275 return Ok(Stamp { written: true, version: Version(version), expires });
1276 }
1277 }
1278 self.read_then_write(tx, revision)
1279 }
1280
1281 fn read_then_write(self, tx: &Tx<'_>, revision: &Revision) -> Result<Stamp> {
1285 let current = cells::current(tx, self.id, &self.path, self.now)?;
1286 let live = current.filter(|current| current.live);
1287 if let (Put::OnlyNew, Some(live)) = (self.put, live) {
1288 return Ok(Stamp { written: false, version: Version(live.version), expires: live.expires });
1289 }
1290 check_version(live.map(|live| live.version), self.if_version)?;
1291 let expires = self.given.or(match live {
1292 Some(live) if self.keeps_its_expiry => live.expires,
1293 _ => self.default,
1294 });
1295 let version = next_version(revision, tx)?;
1296 let spilled = current.and_then(|current| current.spill);
1297 cells::put(tx, self.id, &self.path, (version, expires), &self.raw, spilled)?;
1298 Ok(Stamp { written: true, version: Version(version), expires })
1299 }
1300}
1301
1302fn live_at(tx: &Tx<'_>, id: i64, path: &[u8], now: i64, if_version: Option<Version>) -> Result<Option<cells::Current>> {
1305 let live = cells::current(tx, id, path, now)?.filter(|current| current.live);
1306 check_version(live.map(|live| live.version), if_version)?;
1307 Ok(live)
1308}
1309
1310fn check_version(found: Option<i64>, wanted: Option<Version>) -> Result<()> {
1311 match wanted {
1312 Some(Version(wanted)) if found != Some(wanted) => Err(Error::new(
1313 ErrorKind::Conflict,
1314 match found {
1315 Some(found) => format!("at version {found}, not {wanted}"),
1316 None => format!("not there at version {wanted}"),
1317 },
1318 )),
1319 _ => Ok(()),
1320 }
1321}
1322
1323pub(crate) fn check_expiry(expiry: Expiry) -> Result<()> {
1324 match expiry {
1325 Expiry::Ttl(span) | Expiry::Idle(span) if span.is_zero() => Err(Error::invalid("an expiry of zero")),
1326 _ => Ok(()),
1327 }
1328}
1329
1330#[cfg(test)]
1331#[path = "bucket_tests.rs"]
1332mod tests;