Skip to main content

vcon_server/
store.rs

1//! One tenant's vCons: a sealed object per kept version and a catalog row
2//! for it. The catalog is the truth: a version exists once its row is
3//! committed, and an object with no row is garbage. Every rule is here;
4//! the catalog and the objects are reached through the backend traits.
5
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8#[cfg(test)]
9use std::sync::{Mutex, MutexGuard};
10
11#[cfg(test)]
12use crate::backend::local::LocalConn;
13
14use uuid::Uuid;
15use vcon::read::Inspection;
16
17use crate::audit::{self, Action, Actor, Entry};
18use crate::backend::local::{LocalCatalog, LocalObjects};
19use crate::backend::{
20    Catalog, CatalogTx, CommitError, NewVersion, ObjectError, Objects, Packed, Packs,
21};
22use crate::catalog;
23use crate::clock::{Clock, nanos};
24use crate::envelope::{self, Context, Key, WrapLimit};
25use crate::fs::Fs;
26use crate::ids::{KeyId, TenantId, VersionId};
27use crate::retention::Retention;
28use crate::reveal::Part;
29use pending::Writers;
30
31mod backup;
32mod compact;
33mod examine;
34mod export;
35mod group;
36#[cfg(test)]
37mod group_tests;
38mod legal;
39mod list;
40pub(crate) mod manifest;
41pub(crate) mod packed;
42pub(crate) mod packer;
43pub(crate) mod pending;
44mod purge;
45mod rekey;
46mod rewrite;
47#[cfg(test)]
48mod statement_tests;
49
50pub use backup::{BackupError, Copied, TRIES};
51pub use examine::{Examination, ExamineError};
52pub use export::KeptVersion;
53pub use legal::{Legal, VersionInfo};
54pub use list::{Cursor, ListQuery, Listed, Listing};
55pub use purge::{Kept, PurgeReport, due};
56
57/// Who is calling, for the audit record.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub struct Caller {
60    pub key: KeyId,
61}
62
63/// What `create` did.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum Created {
66    /// Stored as a new vCon.
67    New(VersionId),
68    /// The same bytes were already current; nothing was written.
69    Same(VersionId),
70}
71
72/// A version as `get` returns it.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct Stored {
75    pub version: VersionId,
76    pub form: vcon::Form,
77    /// Whether the body is gzipped, as it arrived.
78    pub gzip: bool,
79    /// The body exactly as it arrived.
80    pub body: Vec<u8>,
81}
82
83/// What a tenant's Store keeps, as removal checks it.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub struct Counts {
86    /// Versions kept, hidden ones included.
87    pub versions: u64,
88    /// Uuids under a legal hold.
89    pub held: u64,
90}
91
92/// Why a Store call was refused or failed.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum StoreError {
95    Conflict,
96    Gone,
97    NotFound,
98    NotDeleted,
99    PreconditionFailed,
100    Immutable,
101    /// The tenant key is at its wrap limit and must be rotated.
102    LimitReached,
103    /// A row's object file is missing or does not open.
104    Damaged,
105    /// The audit record could not be written, so nothing was done.
106    AuditFailed,
107    Io,
108}
109
110/// Why a tenant's Store did not open: kept apart so a key that does not
111/// open its catalog is never confused with files this process may not use.
112#[derive(Debug)]
113pub enum OpenError {
114    /// The catalog does not open under the tenant's catalog key.
115    WrongKey,
116    /// This process may not use `path`, a file or directory the Store
117    /// needs; `error` is the system's.
118    Access {
119        path: PathBuf,
120        error: std::io::Error,
121    },
122    /// Anything else.
123    Store(StoreError),
124}
125
126impl From<OpenError> for StoreError {
127    /// How the Store's callers see a Store that did not open.
128    fn from(_: OpenError) -> StoreError {
129        StoreError::Io
130    }
131}
132
133impl From<StoreError> for OpenError {
134    fn from(e: StoreError) -> OpenError {
135        OpenError::Store(e)
136    }
137}
138
139impl From<catalog::CatalogError> for OpenError {
140    fn from(e: catalog::CatalogError) -> OpenError {
141        match e {
142            catalog::CatalogError::WrongKey => OpenError::WrongKey,
143            catalog::CatalogError::Access { path, error } => OpenError::Access { path, error },
144            _ => OpenError::Store(StoreError::Io),
145        }
146    }
147}
148
149/// A catalog transaction.
150type Tx<'a> = Box<dyn CatalogTx + 'a>;
151
152/// One tenant's vCons.
153pub struct Store {
154    tenant: TenantId,
155    tenant_key: Key,
156    catalog: Box<dyn Catalog>,
157    objects: Arc<dyn Objects>,
158    /// The pack files of packed versions; None where the storage keeps
159    /// none.
160    packs: Option<Arc<dyn Packs>>,
161    /// The footers of the pack files read.
162    footers: packed::Footers,
163    /// The filesystem a backup is written to.
164    fs: Arc<dyn Fs>,
165    clock: Arc<dyn Clock>,
166    /// The reads waiting to record themselves, committed together.
167    group: group::Group,
168    /// The local objects directory, for tests that look at its files.
169    #[cfg(test)]
170    objects_dir: PathBuf,
171    #[cfg(test)]
172    hooks: tests::Hooks,
173}
174
175impl Store {
176    /// Opens the tenant's local catalog under its catalog key, making it
177    /// if new, then runs start-up recovery.
178    pub fn open(
179        dir: &Path,
180        tenant: TenantId,
181        tenant_key: Key,
182        fs: Arc<dyn Fs>,
183        clock: Arc<dyn Clock>,
184    ) -> Result<Store, OpenError> {
185        let store = Store::open_beside(dir, tenant, tenant_key, fs, clock)?;
186        // Every process that runs recovery holds the catalog alone: a
187        // server or a command that runs alone (datadir.rs).
188        store.recover(Writers::None)?;
189        Ok(store)
190    }
191
192    /// Opens the store as a command running beside a server does: without
193    /// start-up recovery, which would take the server's writes in progress
194    /// for a crash's leftovers.
195    pub fn open_beside(
196        dir: &Path,
197        tenant: TenantId,
198        tenant_key: Key,
199        fs: Arc<dyn Fs>,
200        clock: Arc<dyn Clock>,
201    ) -> Result<Store, OpenError> {
202        let catalog_key = envelope::catalog_key(&tenant_key).map_err(|_| StoreError::Io)?;
203        let catalog = LocalCatalog::open(&dir.join("catalog.sqlite"), catalog_key)?;
204        let objects = dir.join("objects");
205        fs.create_dir_all(&objects).map_err(|_| StoreError::Io)?;
206        // Each version is written into objects/, so it must be writable too.
207        catalog::may_use(&objects, libc::W_OK | libc::X_OK)?;
208        // A new directory survives a crash only once the directory that
209        // holds it is synced; without this a crash could take the objects
210        // directory, synced files and all, while the catalog keeps its rows.
211        fs.sync_dir(dir).map_err(|_| StoreError::Io)?;
212        #[cfg_attr(
213            not(test),
214            allow(unused_mut, reason = "only tests set the objects directory after")
215        )]
216        let mut store = Store::with_backends(
217            tenant,
218            tenant_key,
219            Box::new(catalog),
220            Arc::new(LocalObjects::new(objects.clone(), fs.clone())),
221            None,
222            fs,
223            clock,
224        );
225        #[cfg(test)]
226        {
227            store.objects_dir = objects;
228        }
229        Ok(store)
230    }
231
232    /// A Store over the given catalog, objects and pack files; with
233    /// `recover`, start-up recovery runs, as `open` runs it.
234    #[cfg(feature = "s3")]
235    #[expect(
236        clippy::too_many_arguments,
237        reason = "each backend is its own argument"
238    )]
239    pub(crate) fn open_on(
240        tenant: TenantId,
241        tenant_key: Key,
242        catalog: Box<dyn Catalog>,
243        objects: Arc<dyn Objects>,
244        packs: Option<Arc<dyn Packs>>,
245        fs: Arc<dyn Fs>,
246        clock: Arc<dyn Clock>,
247        recover: bool,
248    ) -> Result<Store, OpenError> {
249        let store = Store::with_backends(tenant, tenant_key, catalog, objects, packs, fs, clock);
250        if recover {
251            // A process that runs recovery holds the catalog alone: the
252            // data directory's lock, or the database's lock, which one
253            // serving server holds.
254            store.recover(Writers::None)?;
255        }
256        Ok(store)
257    }
258
259    /// A Store over the given catalog, objects and pack files, opened as
260    /// `open_beside` opens one: without start-up recovery.
261    pub(crate) fn with_backends(
262        tenant: TenantId,
263        tenant_key: Key,
264        catalog: Box<dyn Catalog>,
265        objects: Arc<dyn Objects>,
266        packs: Option<Arc<dyn Packs>>,
267        fs: Arc<dyn Fs>,
268        clock: Arc<dyn Clock>,
269    ) -> Store {
270        Store {
271            tenant,
272            tenant_key,
273            catalog,
274            objects,
275            packs,
276            footers: packed::Footers::new(packed::FOOTERS),
277            fs,
278            clock,
279            group: group::Group::default(),
280            #[cfg(test)]
281            objects_dir: PathBuf::new(),
282            #[cfg(test)]
283            hooks: tests::Hooks::default(),
284        }
285    }
286
287    /// Start-up recovery: the catalog recovers itself, and temporary
288    /// objects and objects with no row are removed, unless a write is
289    /// under way for them (store/pending.rs), and how many is logged. A
290    /// name that is not a version id, with or without `.tmp`, is not ours
291    /// and is left alone.
292    ///
293    /// The order is what keeps a write under way safe. A pending row no
294    /// write can still be under way for is deleted first, so that write's
295    /// last transaction refuses to add its row. The objects are listed
296    /// next, and the rows read after: a write adds its pending row before
297    /// it writes its object, so every object listed has its pending row or
298    /// its version's row in that read.
299    pub(crate) fn recover(&self, writers: Writers) -> Result<(), StoreError> {
300        self.catalog.recover()?;
301        let now = nanos(self.clock.now());
302        {
303            let mut tx = self.catalog.immediate()?;
304            for (version, started_at) in tx.pending()? {
305                if !pending::under_way(writers, started_at, now) {
306                    tx.drop_pending(version)?;
307                }
308            }
309            commit(tx)?;
310        }
311        let names = self.objects.list().map_err(io)?;
312        let (places, files, writing) = {
313            let mut tx = self.catalog.snapshot()?;
314            let places: std::collections::HashMap<VersionId, bool> = tx
315                .places()?
316                .into_iter()
317                .map(|(version, place)| (version, names_its_object(&place)))
318                .collect();
319            let files: std::collections::HashSet<_> = tx.pack_files()?.into_iter().collect();
320            let writing: std::collections::HashSet<VersionId> = tx
321                .pending()?
322                .into_iter()
323                .filter(|(_, started_at)| pending::under_way(writers, *started_at, now))
324                .map(|(version, _)| version)
325                .collect();
326            (places, files, writing)
327        };
328        let mut removed: u64 = 0;
329        for name in names {
330            let (id, temporary) = match name.strip_suffix(".tmp") {
331                Some(id) => (id, true),
332                None => (name.as_str(), false),
333            };
334            let Some(version) = VersionId::parse(id) else {
335                continue;
336            };
337            let named = places.get(&version).copied().unwrap_or(false);
338            if pending::leftover(named, temporary, writing.contains(&version)) {
339                self.objects.remove_name(&name).map_err(io)?;
340                removed += 1;
341            }
342        }
343        if let Some(packs) = &self.packs {
344            let mut unnamed: u64 = 0;
345            // A file a rewrite wrote but did not record is removed below; a
346            // purge whose file side was cut off is finished after.
347            for name in packs.list().map_err(io)? {
348                let Some((_, file)) = packed::parse_name(&name) else {
349                    continue;
350                };
351                if !files.contains(&file) {
352                    packs.remove(&name).map_err(io)?;
353                    unnamed += 1;
354                }
355            }
356            if unnamed > 0 {
357                tracing::info!(
358                    removed = unnamed,
359                    "start-up recovery removed pack files that no catalog row names"
360                );
361            }
362        }
363        self.finish_purges()?;
364        self.publish()?;
365        if removed > 0 {
366            self.objects.sync().map_err(io)?;
367            // A count only, as the purge sweep logs, never a tenant or a
368            // name.
369            tracing::info!(
370                removed,
371                "start-up recovery removed objects that no catalog row names"
372            );
373        }
374        Ok(())
375    }
376
377    /// Stores a new vCon. The uuid's state is checked before anything is
378    /// sealed, the body is written in the order below, and the
379    /// commit checks the state again, so of two racing writers one wins
380    /// and the other's object is removed.
381    pub fn create(
382        &self,
383        who: &Caller,
384        found: &Inspection,
385        body: &[u8],
386    ) -> Result<Created, StoreError> {
387        let uuid = found.uuid;
388        let entry = |status, version| Entry {
389            actor: Actor::Key(who.key),
390            action: Action::Create,
391            target: Some(uuid.to_string()),
392            version,
393            status,
394        };
395        let key_id = self.tenant_key.id();
396        let version = VersionId::generate();
397        {
398            let mut tx = self.catalog.immediate()?;
399            let refused = match state(&mut tx, uuid)? {
400                State::Gone => Some((410, None, StoreError::Gone)),
401                State::Live(current) => match self.read_version(&mut tx, uuid, current) {
402                    Ok(stored) if stored == body => {
403                        self.record(&mut tx, &entry(200, Some(current)))?;
404                        commit(tx)?;
405                        return Ok(Created::Same(current));
406                    }
407                    Ok(_) => Some((409, None, StoreError::Conflict)),
408                    Err(StoreError::Damaged) => Some((500, Some(current), StoreError::Damaged)),
409                    Err(e) => return Err(e),
410                },
411                State::Absent if envelope::wrap_limit(tx.wraps(key_id)?) == WrapLimit::Refuse => {
412                    Some((503, None, StoreError::LimitReached))
413                }
414                // The wrap is counted before it is made, so every wrap is
415                // counted once whether this write wins or loses. The
416                // pending row marks the object as a write under way until
417                // its row is added (store/pending.rs).
418                State::Absent => {
419                    tx.add_wrap(key_id)?;
420                    tx.add_pending(version, nanos(self.clock.now()))?;
421                    None
422                }
423            };
424            if let Some((status, version, error)) = refused {
425                self.record(&mut tx, &entry(status, version))?;
426                commit(tx)?;
427                return Err(error);
428            }
429            commit(tx)?;
430        }
431
432        let wrapped = self.write_version(uuid, version, body)?;
433        self.pause();
434
435        let unknown = std::cell::Cell::new(false);
436        let committed = (|| {
437            let mut tx = self.catalog.immediate()?;
438            let mine = tx.drop_pending(version)?;
439            match state(&mut tx, uuid)? {
440                State::Absent => {}
441                lost => {
442                    let (status, error) = match lost {
443                        State::Gone => (410, StoreError::Gone),
444                        _ => (409, StoreError::Conflict),
445                    };
446                    self.record(&mut tx, &entry(status, None))?;
447                    commit(tx)?;
448                    return Err(error);
449                }
450            }
451            if !mine {
452                // Recovery took the write for a leftover and removed its
453                // object: a row now would name nothing.
454                self.record(&mut tx, &entry(500, None))?;
455                commit(tx)?;
456                return Err(StoreError::Io);
457            }
458            // The version's time, and the uuid's first: the list keeps
459            // its place by it through replace, delete and restore.
460            let stored_at = nanos(self.clock.now());
461            tx.insert_version(&NewVersion {
462                version,
463                uuid,
464                form: form_name(found.form),
465                gzip: found.gzip,
466                size: i64::try_from(body.len()).map_err(io)?,
467                stored_at,
468                key: key_id,
469                wrapped: &wrapped,
470            })?;
471            tx.insert_vcon(uuid, version, stored_at)?;
472            self.record(&mut tx, &entry(201, Some(version)))?;
473            kept(tx.commit(), &unknown)?;
474            Ok(Created::New(version))
475        })();
476        self.drop_unless_kept(committed.is_err(), unknown.get(), version);
477        #[cfg(test)]
478        if committed.is_ok() {
479            self.forced_pack();
480        }
481        committed
482    }
483
484    /// Reads the current version of `uuid`. The body is decrypted whole,
485    /// then one transaction checks that the version is still current and
486    /// commits the audit record; only then is the body returned. If the
487    /// version changed meanwhile, the read starts again.
488    pub fn get(&self, who: &Caller, uuid: Uuid) -> Result<Stored, StoreError> {
489        self.read_as(who, uuid, Action::Read)
490    }
491
492    /// Reads the current version of `uuid` as [`Store::get`] does, for a
493    /// caller about to show `part` of it: the same answer, recorded under
494    /// the reveal action of that part.
495    pub fn reveal(&self, who: &Caller, uuid: Uuid, part: Part) -> Result<Stored, StoreError> {
496        self.read_as(who, uuid, Action::Reveal(part))
497    }
498
499    /// Reads the current version of `uuid` as [`Store::get`] does, for a
500    /// caller that answers its masked view: the same body, recorded as
501    /// `read_masked`.
502    pub fn read_masked(&self, who: &Caller, uuid: Uuid) -> Result<Stored, StoreError> {
503        self.read_as(who, uuid, Action::ReadMasked)
504    }
505
506    /// The read behind `get`, `reveal` and `read_masked`: every outcome is recorded as
507    /// `action`.
508    fn read_as(&self, who: &Caller, uuid: Uuid, action: Action) -> Result<Stored, StoreError> {
509        loop {
510            // The first step only reads, and takes no write lock (on
511            // PostgreSQL, no lock on the tenant): the last step checks
512            // again under the lock, and records the read or its refusal.
513            let found = {
514                let mut tx = self.catalog.snapshot()?;
515                match state(&mut tx, uuid)? {
516                    State::Live(version) => {
517                        #[cfg(test)]
518                        {
519                            let hook = self.hooks.in_first_step.lock().expect("hook").clone();
520                            if let Some(hook) = hook {
521                                hook();
522                            }
523                        }
524                        Some((version, version_row(&mut tx, version)))
525                    }
526                    State::Gone | State::Absent => None,
527                }
528            };
529            let (version, opened, place) = match found {
530                Some((version, row)) => {
531                    let place = row.as_ref().ok().and_then(|r| r.place.clone());
532                    #[cfg(test)]
533                    {
534                        let hook = self.hooks.before_read.lock().expect("hook").take();
535                        if let Some(hook) = hook {
536                            hook();
537                        }
538                    }
539                    let opened = row.and_then(|row| {
540                        let body = self.open_version(uuid, version, &row)?;
541                        Ok(Stored {
542                            version,
543                            form: row.form,
544                            gzip: row.gzip,
545                            body,
546                        })
547                    });
548                    (Some(version), Some(opened), place)
549                }
550                None => (None, None, None),
551            };
552            self.pause();
553            #[cfg(test)]
554            {
555                let hook = self.hooks.before_confirm.lock().expect("hook").clone();
556                if let Some(hook) = hook {
557                    hook();
558                }
559            }
560            let read = group::Confirm {
561                key: who.key,
562                action,
563                uuid,
564                version,
565                opened: opened.as_ref().is_some_and(Result::is_ok),
566                place,
567            };
568            match self.group.confirm(self, read)? {
569                // The last step answers only a read that read a version, so
570                // `opened` holds that version's outcome; without one (no
571                // such step answers so) the read would start again.
572                group::Confirmed::Answer => match opened {
573                    Some(opened) => return opened,
574                    None => continue,
575                },
576                group::Confirmed::Again => continue,
577                group::Confirmed::Refused(error) => return Err(error),
578            }
579        }
580    }
581
582    /// Replaces the current version of `found.uuid`, if it is `if_match`
583    /// and neither signed nor encrypted. The caller has checked that the
584    /// body's uuid is the one asked for. The old version is hidden, and
585    /// kept for legal reads until it is purged. As in `create`, the state
586    /// is checked before sealing and again at the commit, so of two racing
587    /// replaces one wins and the other's object is removed.
588    pub fn replace(
589        &self,
590        who: &Caller,
591        if_match: VersionId,
592        found: &Inspection,
593        body: &[u8],
594    ) -> Result<VersionId, StoreError> {
595        let uuid = found.uuid;
596        let entry = |status, version| Entry {
597            actor: Actor::Key(who.key),
598            action: Action::Replace,
599            target: Some(uuid.to_string()),
600            version,
601            status,
602        };
603        let key_id = self.tenant_key.id();
604        let version = VersionId::generate();
605        // Why the state does not allow this replace, if it does not.
606        let refusal = |tx: &mut Tx| -> Result<Option<(u16, StoreError)>, StoreError> {
607            Ok(match state(tx, uuid)? {
608                State::Absent => Some((404, StoreError::NotFound)),
609                State::Gone => Some((410, StoreError::Gone)),
610                State::Live(current) if version_row(tx, current)?.form != vcon::Form::Unsigned => {
611                    Some((409, StoreError::Immutable))
612                }
613                State::Live(current) if current != if_match => {
614                    Some((412, StoreError::PreconditionFailed))
615                }
616                State::Live(_) => None,
617            })
618        };
619        {
620            let mut tx = self.catalog.immediate()?;
621            let refused = match refusal(&mut tx)? {
622                None if envelope::wrap_limit(tx.wraps(key_id)?) == WrapLimit::Refuse => {
623                    Some((503, StoreError::LimitReached))
624                }
625                other => other,
626            };
627            if let Some((status, error)) = refused {
628                self.record(&mut tx, &entry(status, None))?;
629                commit(tx)?;
630                return Err(error);
631            }
632            tx.add_wrap(key_id)?;
633            tx.add_pending(version, nanos(self.clock.now()))?;
634            commit(tx)?;
635        }
636
637        let wrapped = self.write_version(uuid, version, body)?;
638        self.pause();
639
640        let unknown = std::cell::Cell::new(false);
641        let committed = (|| {
642            let mut tx = self.catalog.immediate()?;
643            let mine = tx.drop_pending(version)?;
644            if let Some((status, error)) = refusal(&mut tx)? {
645                self.record(&mut tx, &entry(status, None))?;
646                commit(tx)?;
647                return Err(error);
648            }
649            if !mine {
650                // As in `create`: recovery removed the object.
651                self.record(&mut tx, &entry(500, None))?;
652                commit(tx)?;
653                return Err(StoreError::Io);
654            }
655            let now = nanos(self.clock.now());
656            tx.insert_version(&NewVersion {
657                version,
658                uuid,
659                form: form_name(found.form),
660                gzip: found.gzip,
661                size: i64::try_from(body.len()).map_err(io)?,
662                stored_at: now,
663                key: key_id,
664                wrapped: &wrapped,
665            })?;
666            tx.hide_version(if_match, now)?;
667            tx.set_current(uuid, version)?;
668            self.record(&mut tx, &entry(200, Some(version)))?;
669            kept(tx.commit(), &unknown)?;
670            Ok(version)
671        })();
672        self.drop_unless_kept(committed.is_err(), unknown.get(), version);
673        #[cfg(test)]
674        if committed.is_ok() {
675            self.forced_pack();
676        }
677        committed
678    }
679
680    /// Deletes `uuid`: one transaction marks it deleted, empties its
681    /// current version and hides every kept version, with the audit
682    /// record. Its versions stay for legal reads until they are purged;
683    /// any already as old as `retention` is purged at once, so a zero
684    /// period erases the vCon inside the request.
685    /// Deleting a deleted or purged uuid succeeds again. A legal hold does
686    /// not stop a delete, only a purge.
687    pub fn delete(&self, who: &Caller, uuid: Uuid, retention: Retention) -> Result<(), StoreError> {
688        let entry = |status| Entry {
689            actor: Actor::Key(who.key),
690            action: Action::Delete,
691            target: Some(uuid.to_string()),
692            version: None,
693            status,
694        };
695        {
696            let mut tx = self.catalog.immediate()?;
697            let outcome = match state(&mut tx, uuid)? {
698                State::Absent => Err(StoreError::NotFound),
699                State::Gone => Ok(()),
700                State::Live(_) => {
701                    tx.mark_deleted(uuid, nanos(self.clock.now()))?;
702                    Ok(())
703                }
704            };
705            let status = if outcome.is_ok() { 204 } else { 404 };
706            self.record(&mut tx, &entry(status))?;
707            commit(tx)?;
708            outcome?;
709        }
710        // A version already as old as `retention` is erased now, not at
711        // the next sweep.
712        self.purge_hidden(Actor::Key(who.key), retention, Some(uuid))?;
713        Ok(())
714    }
715
716    /// Every version whose object is missing, or, for a packed version,
717    /// whose pack file is missing or not the length its row says. Such a
718    /// version answers 500 when read; it is reported, never dropped.
719    pub fn check(&self) -> Result<Vec<VersionId>, StoreError> {
720        let versions = self.catalog.snapshot()?.places()?;
721        let present: std::collections::BTreeSet<String> =
722            self.objects.list().map_err(io)?.into_iter().collect();
723        let mut whole = std::collections::HashMap::new();
724        let mut missing = Vec::new();
725        for (version, place) in versions {
726            let kept = match place {
727                Err(_) => false,
728                Ok(None) => present.contains(&version.to_string()),
729                Ok(Some(packed)) => match whole.get(&packed.file) {
730                    Some(&kept) => kept,
731                    None => {
732                        let kept = match &self.packs {
733                            None => false,
734                            Some(packs) => {
735                                let name = crate::backend::pack::name(&packed.date, packed.file);
736                                packs.size(&name).map_err(io)? == Some(packed.bytes)
737                            }
738                        };
739                        whole.insert(packed.file, kept);
740                        kept
741                    }
742                },
743            };
744            if !kept {
745                missing.push(version);
746            }
747        }
748        Ok(missing)
749    }
750
751    /// Seals `body` as a new version of `uuid` under a new data key, wraps
752    /// that key under the tenant key, and writes the object as `version`.
753    /// Returns the wrapped key.
754    fn write_version(
755        &self,
756        uuid: Uuid,
757        version: VersionId,
758        body: &[u8],
759    ) -> Result<Vec<u8>, StoreError> {
760        let ctx = Context::Version {
761            tenant: self.tenant,
762            uuid,
763            version,
764        };
765        let data_key = Key::generate().map_err(|_| StoreError::Io)?;
766        let blob = envelope::seal(&data_key, &ctx, body);
767        let wrapped = envelope::wrap(&self.tenant_key, &ctx, &data_key);
768        self.objects.put(version, &blob).map_err(io)?;
769        Ok(wrapped)
770    }
771
772    /// Removes a new version's object when the write failed and its rows
773    /// were surely not kept. After a commit whose outcome is unknown the
774    /// object stays: its rows may be kept, and a row without its object is
775    /// damage, while an object without a row is a leftover that start-up
776    /// recovery removes.
777    fn drop_unless_kept(&self, failed: bool, unknown: bool, version: VersionId) {
778        if failed && !unknown {
779            // Best effort: start-up recovery removes any object left over.
780            let _ = self.objects.remove(version);
781        }
782    }
783
784    /// In tests, runs the hook set for the gap between work done outside
785    /// the catalog lock and the transaction that confirms it.
786    fn pause(&self) {
787        #[cfg(test)]
788        {
789            let hook = self.hooks.between.lock().expect("hook").take();
790            if let Some(hook) = hook {
791                hook();
792            }
793        }
794    }
795
796    /// The plaintext of a stored version. A missing row or object, or one
797    /// that does not open, is damage; a read the storage fails is Io.
798    fn read_version(
799        &self,
800        tx: &mut Tx,
801        uuid: Uuid,
802        version: VersionId,
803    ) -> Result<Vec<u8>, StoreError> {
804        self.read_or_why(tx, uuid, version)
805            .map_err(Unopened::into_store)
806    }
807
808    /// `read_version`, keeping a storage failure as the storage's error.
809    fn read_or_why(
810        &self,
811        tx: &mut Tx,
812        uuid: Uuid,
813        version: VersionId,
814    ) -> Result<Vec<u8>, Unopened> {
815        let row = version_row(tx, version)?;
816        self.open_or_why(uuid, version, &row)
817    }
818
819    /// Opens a version's sealed blob, from its object or its pack file,
820    /// with its wrapped data key.
821    fn open_version(
822        &self,
823        uuid: Uuid,
824        version: VersionId,
825        row: &VersionRow,
826    ) -> Result<Vec<u8>, StoreError> {
827        self.open_or_why(uuid, version, row)
828            .map_err(Unopened::into_store)
829    }
830
831    /// `open_version`, keeping a storage failure as the storage's error,
832    /// for `examine`, which reports its kind.
833    fn open_or_why(
834        &self,
835        uuid: Uuid,
836        version: VersionId,
837        row: &VersionRow,
838    ) -> Result<Vec<u8>, Unopened> {
839        let ctx = Context::Version {
840            tenant: self.tenant,
841            uuid,
842            version,
843        };
844        let data_key =
845            envelope::unwrap(&self.tenant_key, &ctx, &row.wrapped).map_err(key_failed)?;
846        let blob = match self.sealed_blob(version, row.place.as_ref()) {
847            Ok(blob) => blob,
848            Err(packed::Unread::Object(ObjectError::Io(e))) => return Err(Unopened::Storage(e)),
849            Err(other) => return Err(Unopened::Store(other.into_store())),
850        };
851        Ok(envelope::open(&data_key, &ctx, &blob).map_err(|_| StoreError::Damaged)?)
852    }
853
854    /// How many versions are packed into pack files: once there are any,
855    /// the storage must keep Parquet storage on, since nothing turns them
856    /// back into objects.
857    pub fn packed_versions(&self) -> Result<u64, StoreError> {
858        self.catalog.snapshot()?.count_packed()
859    }
860
861    /// How many versions the Store keeps and how many uuids are held.
862    pub fn counts(&self) -> Result<Counts, StoreError> {
863        let mut tx = self.catalog.snapshot()?;
864        Ok(Counts {
865            versions: tx.count_versions()?,
866            held: tx.count_held()?,
867        })
868    }
869
870    /// Writes the tenant's log after `since` as JSON lines, oldest first.
871    /// Not recorded: reading the log changes nothing.
872    pub fn export(
873        &self,
874        since: Option<i64>,
875        out: &mut dyn std::io::Write,
876    ) -> Result<(), audit::AuditError> {
877        self.catalog.export(since.unwrap_or(0), out)
878    }
879
880    /// A page of the tenant's log as JSON lines, the lines `export` writes
881    /// for the same records. The read is recorded as audit_read in the same
882    /// log and transaction, after the page is read, so a page never holds
883    /// its own record.
884    pub fn audit_page(
885        &self,
886        who: &Caller,
887        query: &audit::AuditQuery,
888    ) -> Result<Vec<u8>, StoreError> {
889        let mut tx = self.catalog.immediate()?;
890        let mut out = Vec::new();
891        let read = tx.audit_lines(query.after, Some(query.limit), &mut out);
892        self.record(
893            &mut tx,
894            &Entry {
895                actor: Actor::Key(who.key),
896                action: Action::AuditRead,
897                target: None,
898                version: None,
899                status: if read.is_ok() { 200 } else { 500 },
900            },
901        )?;
902        commit(tx)?;
903        read.map(|()| out).map_err(io)
904    }
905
906    /// Records, in a transaction of its own, an action on the tenant taken
907    /// elsewhere, such as a change to its retention period.
908    pub fn log(&self, entry: &Entry) -> Result<(), StoreError> {
909        let mut tx = self.catalog.immediate()?;
910        self.record(&mut tx, entry)?;
911        commit(tx)
912    }
913
914    #[cfg(test)]
915    pub(crate) fn break_audit(&self) {
916        self.conn()
917            .execute_batch(
918                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
919                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
920            )
921            .expect("trigger");
922    }
923
924    /// For tests: after every write that adds a version, a pack run with
925    /// `plan`, so each version is packed before the next step. Pack
926    /// storage is S3's, so only an S3 build's harnesses call it.
927    #[cfg(all(test, feature = "s3"))]
928    pub(crate) fn pack_after_every_write(&mut self, plan: packer::PackPlan) {
929        *self.hooks.pack_always.lock().expect("hook") = Some(plan);
930    }
931
932    #[cfg(test)]
933    fn forced_pack(&self) {
934        let plan = *self.hooks.pack_always.lock().expect("hook");
935        if let Some(plan) = plan {
936            self.pack(&plan).expect("the forced pack run");
937        }
938    }
939
940    /// In tests, sets the hook every read runs after its first step and
941    /// before its last; None removes it. The live PostgreSQL read tests
942    /// use it.
943    #[cfg(all(test, feature = "postgres", feature = "backend-tests"))]
944    pub(crate) fn on_last_step(&self, hook: Option<Arc<dyn Fn() + Send + Sync>>) {
945        *self.hooks.before_confirm.lock().expect("hook") = hook;
946    }
947
948    /// In tests, sets the hook every read runs in its first step, after it
949    /// finds the vCon's current version and before it reads that
950    /// version's row; None removes it.
951    #[cfg(all(test, feature = "postgres", feature = "backend-tests"))]
952    pub(crate) fn in_first_step(&self, hook: Option<Arc<dyn Fn() + Send + Sync>>) {
953        *self.hooks.in_first_step.lock().expect("hook") = hook;
954    }
955
956    /// In tests, sets the hook the next read runs once, after its first
957    /// step and before it opens the version's body.
958    #[cfg(all(test, feature = "postgres", feature = "backend-tests"))]
959    pub(crate) fn once_before_open(&self, hook: Box<dyn FnOnce() + Send>) {
960        *self.hooks.before_read.lock().expect("hook") = Some(hook);
961    }
962
963    /// Sets the hook a write runs once, between its object and its last
964    /// transaction.
965    #[cfg(test)]
966    pub(crate) fn on_between(&self, hook: Box<dyn FnOnce() + Send>) {
967        *self.hooks.between.lock().expect("hook") = Some(hook);
968    }
969
970    /// The catalog's pending rows, for tests.
971    #[cfg(test)]
972    pub(crate) fn pending_writes(&self) -> Result<Vec<(VersionId, i64)>, StoreError> {
973        self.catalog.snapshot()?.pending()
974    }
975
976    #[cfg(test)]
977    pub(crate) fn on_backup_copied(&self, hook: tests::BackupHook) {
978        *self.hooks.copied.lock().expect("hook") = Some(hook);
979    }
980
981    #[cfg(test)]
982    pub(crate) fn conn_for_test(&self) -> MutexGuard<'_, LocalConn> {
983        self.conn()
984    }
985
986    #[cfg(test)]
987    pub(crate) fn records(&self) -> Vec<serde_json::Value> {
988        crate::audit::testing::exported(&self.conn(), None)
989    }
990
991    /// Counts, in a transaction of its own, an event the tenant's log
992    /// keeps one record per minute for, such as a failed check of one of
993    /// its keys.
994    pub fn count(&self, entry: &Entry) -> Result<(), StoreError> {
995        let mut tx = self.catalog.immediate()?;
996        tx.count(entry, self.clock.now())
997            .map_err(|_| StoreError::AuditFailed)?;
998        commit(tx)
999    }
1000
1001    /// Writes an audit record in `tx`; if it cannot, nothing is done.
1002    fn record(&self, tx: &mut Tx, entry: &Entry) -> Result<(), StoreError> {
1003        tx.record(entry, self.clock.now())
1004            .map_err(|_| StoreError::AuditFailed)
1005    }
1006
1007    /// The local catalog's connection, for tests.
1008    #[cfg(test)]
1009    fn conn(&self) -> MutexGuard<'_, LocalConn> {
1010        self.catalog.local_conn()
1011    }
1012}
1013
1014enum State {
1015    Absent,
1016    Live(VersionId),
1017    Gone,
1018}
1019
1020/// A uuid's state: purged or deleted is Gone. A row that is neither
1021/// deleted nor current is damage.
1022fn state(tx: &mut Tx, uuid: Uuid) -> Result<State, StoreError> {
1023    if tx.tombstoned(uuid)? {
1024        return Ok(State::Gone);
1025    }
1026    match tx.vcon_row(uuid)? {
1027        None => Ok(State::Absent),
1028        Some(row) if row.deleted_at.is_some() => Ok(State::Gone),
1029        Some(row) => row.current.map(State::Live).ok_or(StoreError::Damaged),
1030    }
1031}
1032
1033/// Whether a version row, with `place` as its place, names the version's
1034/// object: unless the row says the version is packed. A row whose place is
1035/// broken names its object, which is kept, since damage is reported and
1036/// never removed.
1037fn names_its_object(place: &Result<Option<Packed>, StoreError>) -> bool {
1038    !matches!(place, Ok(Some(_)))
1039}
1040
1041struct VersionRow {
1042    form: vcon::Form,
1043    gzip: bool,
1044    wrapped: Vec<u8>,
1045    place: Option<Packed>,
1046}
1047
1048/// A version's row; one missing, or with a form this build does not
1049/// know, is damage.
1050fn version_row(tx: &mut Tx, version: VersionId) -> Result<VersionRow, StoreError> {
1051    let row = tx.version_row(version)?.ok_or(StoreError::Damaged)?;
1052    let form = match row.form.as_str() {
1053        "unsigned" => vcon::Form::Unsigned,
1054        "signed" => vcon::Form::Signed,
1055        "encrypted" => vcon::Form::Encrypted,
1056        _ => return Err(StoreError::Damaged),
1057    };
1058    Ok(VersionRow {
1059        form,
1060        gzip: row.gzip,
1061        wrapped: row.wrapped,
1062        place: row.place,
1063    })
1064}
1065
1066fn commit(tx: Tx) -> Result<(), StoreError> {
1067    tx.commit().map_err(io)
1068}
1069
1070/// The commit that adds a version's rows: an error is Io, and one whose
1071/// outcome is unknown is noted in `unknown`, since its rows may be kept.
1072fn kept(
1073    outcome: Result<(), CommitError>,
1074    unknown: &std::cell::Cell<bool>,
1075) -> Result<(), StoreError> {
1076    outcome.map_err(|e| {
1077        unknown.set(e == CommitError::Unknown);
1078        StoreError::Io
1079    })
1080}
1081
1082/// A wrapped data key that did not open: damage if it does not open under
1083/// the tenant key, and Io if its memory could not be locked.
1084fn key_failed(e: envelope::KeyError) -> StoreError {
1085    match e {
1086        envelope::KeyError::Damaged => StoreError::Damaged,
1087        _ => StoreError::Io,
1088    }
1089}
1090
1091/// A read of the object a version row names that failed: an object the
1092/// storage does not hold is damage; any other failure (a disk error, a
1093/// refused key, no answer in time) says nothing about the stored data, so
1094/// it is Io and is logged by its kind. Its text is not logged: a service's
1095/// message may name the object's key.
1096fn read_failed(e: ObjectError) -> StoreError {
1097    match e {
1098        ObjectError::Missing => StoreError::Damaged,
1099        ObjectError::Io(e) => {
1100            storage_failed(&e);
1101            StoreError::Io
1102        }
1103    }
1104}
1105
1106/// Logs a read the storage failed by the error's kind and system error
1107/// number only: its text is not logged, since a service's message may name
1108/// the object's key.
1109fn storage_failed(e: &std::io::Error) {
1110    tracing::warn!(
1111        kind = %e.kind(),
1112        os_error = e.raw_os_error(),
1113        "a stored version's object could not be read"
1114    );
1115}
1116
1117/// Why a version's blob did not open: as a read answers it, or a failure
1118/// of the storage itself, kept so `examine` can report its kind.
1119#[derive(Debug)]
1120enum Unopened {
1121    Store(StoreError),
1122    Storage(std::io::Error),
1123}
1124
1125impl Unopened {
1126    /// How a read answers: a storage failure is logged by its kind and is
1127    /// Io, as `read_failed` has it.
1128    fn into_store(self) -> StoreError {
1129        match self {
1130            Unopened::Store(e) => e,
1131            Unopened::Storage(e) => read_failed(ObjectError::Io(e)),
1132        }
1133    }
1134}
1135
1136impl From<StoreError> for Unopened {
1137    fn from(e: StoreError) -> Unopened {
1138        Unopened::Store(e)
1139    }
1140}
1141
1142fn io<E>(_: E) -> StoreError {
1143    StoreError::Io
1144}
1145
1146/// The name the catalog stores for `form`.
1147fn form_name(form: vcon::Form) -> &'static str {
1148    form.as_str()
1149}
1150
1151impl From<ObjectError> for StoreError {
1152    fn from(_: ObjectError) -> StoreError {
1153        StoreError::Io
1154    }
1155}
1156
1157#[cfg(test)]
1158pub(crate) mod testing {
1159    use std::collections::BTreeSet;
1160
1161    use vcon::Form;
1162    use vcon::read::{Inspection, Limits, inspect};
1163
1164    /// An unsigned vCon with this uuid, and what `inspect` makes of it.
1165    pub(crate) fn vcon(uuid: &str, subject: &str) -> (Inspection, Vec<u8>) {
1166        let body = format!(
1167            r#"{{"uuid": "{uuid}", "created_at": "2026-10-23T12:00:00Z", "subject": "{subject}", "parties": []}}"#
1168        )
1169        .into_bytes();
1170        let found =
1171            inspect(&body, None, &Limits::new(1 << 20), &BTreeSet::new()).expect("a valid vCon");
1172        assert_eq!(found.form, Form::Unsigned);
1173        (found, body)
1174    }
1175}
1176
1177#[cfg(test)]
1178pub(crate) mod tests {
1179    use std::collections::BTreeSet;
1180
1181    use serde_json::Value;
1182    use time::macros::datetime;
1183    use vcon::read::{Limits, inspect};
1184
1185    use super::testing::vcon;
1186    use super::*;
1187    use crate::audit::testing::exported;
1188
1189    /// Each version is written into objects/: a Store that may not write
1190    /// there does not open, and says so with the path and the system's
1191    /// error, as it does for its catalog.
1192    #[test]
1193    fn an_objects_directory_the_process_may_not_write_is_named() {
1194        use std::os::unix::fs::PermissionsExt;
1195        let f = fixture();
1196        let objects = f.dir.path().join("objects");
1197        let mode = |m| {
1198            std::fs::set_permissions(&objects, std::fs::Permissions::from_mode(m)).expect("chmod")
1199        };
1200        mode(0o500);
1201        let refused = f.open_or_why();
1202        mode(0o700);
1203        match refused {
1204            Err(OpenError::Access { path, error }) => {
1205                assert_eq!(path, objects);
1206                assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1207            }
1208            other => panic!("{:?}", other.map(|_| "opened")),
1209        }
1210        assert!(f.open_or_why().is_ok(), "opens once allowed");
1211    }
1212    use crate::catalog::testing::columns_taking_null;
1213    use crate::clock::ManualClock;
1214    use rusqlite::{Connection, params};
1215
1216    use crate::catalog;
1217    use crate::fs::{CrashFs, Op};
1218
1219    const UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
1220
1221    /// What a backup runs at each try, after it copies the catalog.
1222    pub(crate) type BackupHook = Box<dyn FnMut(&Store) + Send>;
1223
1224    /// Test-only points where a test can step in.
1225    #[derive(Default)]
1226    pub(super) struct Hooks {
1227        /// Runs once, between work done outside the catalog lock (a
1228        /// write's files, a read's decryption) and the transaction that
1229        /// confirms it.
1230        pub(super) between: Mutex<Option<Box<dyn FnOnce() + Send>>>,
1231        /// Runs at each try of a backup, after the catalog is copied and
1232        /// before its versions' files are.
1233        pub(super) copied: Mutex<Option<BackupHook>>,
1234        /// Runs once, in a read, between the transaction that finds the
1235        /// version's place and the read of its blob.
1236        pub(super) before_read: Mutex<Option<Box<dyn FnOnce() + Send>>>,
1237        /// A pack run after every write that adds a version.
1238        pub(super) pack_always: Mutex<Option<super::packer::PackPlan>>,
1239        /// Runs in every read, after its body is read and before it joins
1240        /// the queue for its last step.
1241        pub(super) before_confirm: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
1242        /// Runs in every read's first step, between the read of the
1243        /// vCon's current version and the read of that version's row.
1244        pub(super) in_first_step: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
1245    }
1246
1247    pub(crate) struct Fixture {
1248        pub(crate) dir: tempfile::TempDir,
1249        pub(crate) fs: Arc<CrashFs>,
1250        pub(crate) clock: Arc<ManualClock>,
1251        /// The tenant key, wrapped under `master`, so a test can open the
1252        /// store again with the same key.
1253        master: Key,
1254        wrapped: Vec<u8>,
1255        pub(crate) store: Store,
1256        pub(crate) caller: Caller,
1257        /// The pack storage the Store is opened with, as an S3 store is;
1258        /// None, as a local one is.
1259        pub(crate) packs: Option<Arc<dyn Packs>>,
1260    }
1261
1262    pub(super) const TENANT: TenantId = TenantId([0x11; 16]);
1263
1264    impl Fixture {
1265        pub(super) fn open(&self) -> Result<Store, StoreError> {
1266            self.open_or_why().map_err(StoreError::from)
1267        }
1268
1269        /// `open`, saying why a Store that did not open did not.
1270        pub(super) fn open_or_why(&self) -> Result<Store, OpenError> {
1271            let ctx = Context::Tenant { tenant: TENANT };
1272            let tenant_key = envelope::unwrap(&self.master, &ctx, &self.wrapped).expect("unwraps");
1273            // As `Store::open` does, with the fixture's pack storage given
1274            // before recovery runs.
1275            let mut store = Store::open_beside(
1276                self.dir.path(),
1277                TENANT,
1278                tenant_key,
1279                self.fs.clone(),
1280                self.clock.clone(),
1281            )?;
1282            store.packs = self.packs.clone();
1283            store.recover(super::pending::Writers::None)?;
1284            Ok(store)
1285        }
1286
1287        /// The tenant key the Store was made under.
1288        pub(crate) fn tenant_key(&self) -> Key {
1289            let ctx = Context::Tenant { tenant: TENANT };
1290            envelope::unwrap(&self.master, &ctx, &self.wrapped).expect("unwraps")
1291        }
1292
1293        pub(crate) fn tenant(&self) -> TenantId {
1294            TENANT
1295        }
1296
1297        /// The directory of the Store's object files.
1298        pub(crate) fn store_objects_dir(&self) -> PathBuf {
1299            self.store.objects_dir.clone()
1300        }
1301
1302        /// A second Store on the same catalog and objects, opened as a
1303        /// command beside a server opens one: for a test that must hand a
1304        /// Store to another thread.
1305        pub(crate) fn open_beside_store(&self) -> Store {
1306            self.open_beside().expect("opens beside")
1307        }
1308
1309        /// Opens the store again as a command beside a server would.
1310        fn open_beside(&self) -> Result<Store, StoreError> {
1311            let ctx = Context::Tenant { tenant: TENANT };
1312            let tenant_key = envelope::unwrap(&self.master, &ctx, &self.wrapped).expect("unwraps");
1313            Store::open_beside(
1314                self.dir.path(),
1315                TENANT,
1316                tenant_key,
1317                self.fs.clone(),
1318                self.clock.clone(),
1319            )
1320            .map_err(StoreError::from)
1321        }
1322
1323        /// Closes the store and opens it again, as a restart would.
1324        pub(super) fn reopen(&mut self) {
1325            let placeholder = self.open().expect("opens");
1326            drop(std::mem::replace(&mut self.store, placeholder));
1327            self.store = self.open().expect("reopens");
1328        }
1329    }
1330
1331    pub(crate) fn fixture() -> Fixture {
1332        let dir = tempfile::tempdir().expect("temp dir");
1333        let fs = Arc::new(CrashFs::new(dir.path()));
1334        let clock = Arc::new(ManualClock::at(datetime!(2026-10-23 12:00 UTC)));
1335        let master = Key::generate().expect("master key");
1336        let tenant_key = Key::generate().expect("tenant key");
1337        let wrapped = envelope::wrap(&master, &Context::Tenant { tenant: TENANT }, &tenant_key);
1338        let store =
1339            Store::open(dir.path(), TENANT, tenant_key, fs.clone(), clock.clone()).expect("opens");
1340        let caller = Caller {
1341            key: Key::generate().expect("caller key").id(),
1342        };
1343        Fixture {
1344            dir,
1345            fs,
1346            clock,
1347            master,
1348            wrapped,
1349            store,
1350            caller,
1351            packs: None,
1352        }
1353    }
1354
1355    fn audit_log(store: &Store) -> Vec<Value> {
1356        exported(&store.conn(), None)
1357    }
1358
1359    fn count(store: &Store, sql: &str) -> i64 {
1360        store.conn().query_row(sql, [], |r| r.get(0)).expect(sql)
1361    }
1362
1363    fn wraps(store: &Store) -> i64 {
1364        store
1365            .conn()
1366            .query_row("SELECT coalesce(sum(wraps), 0) FROM key_use", [], |r| {
1367                r.get(0)
1368            })
1369            .expect("wraps")
1370    }
1371
1372    /// The body the store holds for `version`, opened as `get` will.
1373    fn stored_body(f: &Fixture, uuid: Uuid, version: VersionId) -> Vec<u8> {
1374        let wrapped: Vec<u8> = f
1375            .store
1376            .conn()
1377            .query_row(
1378                "SELECT wrapped_key FROM version WHERE version = ?1",
1379                [version.0],
1380                |r| r.get(0),
1381            )
1382            .expect("row");
1383        let ctx = Context::Version {
1384            tenant: f.store.tenant,
1385            uuid,
1386            version,
1387        };
1388        let data_key = envelope::unwrap(&f.store.tenant_key, &ctx, &wrapped).expect("unwraps");
1389        let blob =
1390            f.fs.read(&f.store.objects_dir.join(version.to_string()))
1391                .expect("file");
1392        envelope::open(&data_key, &ctx, &blob).expect("opens")
1393    }
1394
1395    fn audit_page(f: &Fixture, after: i64, limit: u32) -> Result<Vec<u8>, StoreError> {
1396        f.store
1397            .audit_page(&f.caller, &audit::AuditQuery { after, limit })
1398    }
1399
1400    fn export_text(store: &Store, since: Option<i64>) -> Vec<u8> {
1401        let mut out = Vec::new();
1402        store.export(since, &mut out).expect("export");
1403        out
1404    }
1405
1406    #[test]
1407    fn an_audit_page_is_export_s_lines_and_records_its_read_after_them() {
1408        let f = fixture();
1409        for n in 0..3 {
1410            let (found, body) = vcon(&format!("01a07da8-c2bb-83e5-b9a2-27900000000{n}"), "x");
1411            f.store.create(&f.caller, &found, &body).expect("stored");
1412        }
1413        let before = export_text(&f.store, None);
1414        assert_eq!(audit_page(&f, 0, 1000), Ok(before.clone()));
1415        let read = audit_log(&f.store);
1416        assert_eq!(read.len(), 4, "three creates and the read");
1417        assert_eq!(read[3]["action"], "audit_read");
1418        assert_eq!(read[3]["actor"], f.caller.key.to_string());
1419        assert_eq!(read[3]["status"], 200);
1420        assert_eq!(read[3]["seq"], 4);
1421        assert_eq!(read[3]["target"], Value::Null);
1422        // A page of two from seq 1: the second and third creates.
1423        let lines: Vec<&[u8]> = before.split_inclusive(|b| *b == b'\n').collect();
1424        assert_eq!(audit_page(&f, 1, 2), Ok(lines[1..3].concat()));
1425        // Past the end: nothing but the earlier reads' records.
1426        let tail = audit_page(&f, 4, 1000).expect("a page");
1427        assert_eq!(tail, export_text(&f.store, Some(4))[..tail.len()]);
1428        assert_eq!(String::from_utf8(tail).expect("UTF-8").lines().count(), 1);
1429    }
1430
1431    /// A record that cannot be read back (a status past any HTTP status)
1432    /// fails the page, and the read is still recorded, as 500.
1433    #[test]
1434    fn an_audit_page_that_cannot_be_read_is_a_failure_and_recorded() {
1435        let f = fixture();
1436        f.store
1437            .conn_for_test()
1438            .execute(
1439                "INSERT INTO audit (at, actor, action, status, count)
1440                 VALUES ('2026-10-23T12:00:00Z', 'cli', 'read', 70000, 1)",
1441                [],
1442            )
1443            .expect("damaged");
1444        assert_eq!(audit_page(&f, 0, 10), Err(StoreError::Io));
1445        let mut recorded = Vec::new();
1446        f.store.export(Some(1), &mut recorded).expect("export");
1447        let recorded: Value = serde_json::from_slice(&recorded).expect("one record");
1448        assert_eq!(recorded["action"], "audit_read");
1449        assert_eq!(recorded["status"], 500);
1450    }
1451
1452    #[test]
1453    fn an_audit_page_whose_record_fails_is_refused() {
1454        let f = fixture();
1455        f.store.break_audit();
1456        assert_eq!(audit_page(&f, 0, 10), Err(StoreError::AuditFailed));
1457    }
1458
1459    #[test]
1460    fn a_new_vcon_is_written_in_order_and_recorded() {
1461        let f = fixture();
1462        let (found, body) = vcon(UUID, "first");
1463        let ops = f.fs.log().len();
1464        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1465            panic!("a new vCon")
1466        };
1467        let (tmp, done) = (
1468            f.store.objects_dir.join(format!("{version}.tmp")),
1469            f.store.objects_dir.join(version.to_string()),
1470        );
1471        assert_eq!(
1472            f.fs.log()[ops..],
1473            [
1474                Op::Write(tmp.clone()),
1475                Op::SyncFile(tmp.clone()),
1476                Op::Rename(tmp, done),
1477                Op::SyncDir(f.store.objects_dir.clone()),
1478            ]
1479        );
1480        assert_eq!(stored_body(&f, found.uuid, version), body);
1481        assert_eq!(
1482            count(
1483                &f.store,
1484                "SELECT count(*) FROM version WHERE hidden_at IS NULL"
1485            ),
1486            1
1487        );
1488        let current: Vec<u8> = f
1489            .store
1490            .conn()
1491            .query_row(
1492                "SELECT current FROM vcon WHERE uuid = ?1",
1493                [found.uuid.as_bytes()],
1494                |r| r.get(0),
1495            )
1496            .expect("vcon row");
1497        assert_eq!(current, version.0);
1498        assert_eq!(wraps(&f.store), 1, "one data key wrapped");
1499        let log = audit_log(&f.store);
1500        assert_eq!(log.len(), 1);
1501        assert_eq!(log[0]["action"], "create");
1502        assert_eq!(log[0]["actor"], f.caller.key.to_string());
1503        assert_eq!(log[0]["target"], UUID);
1504        assert_eq!(log[0]["version"], version.to_string());
1505        assert_eq!(log[0]["status"], 201);
1506    }
1507
1508    #[test]
1509    fn the_same_body_again_is_same_and_writes_nothing() {
1510        let f = fixture();
1511        let (found, body) = vcon(UUID, "first");
1512        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1513            panic!("a new vCon")
1514        };
1515        let ops = f.fs.log().len();
1516        assert_eq!(
1517            f.store.create(&f.caller, &found, &body),
1518            Ok(Created::Same(version))
1519        );
1520        assert_eq!(f.fs.log().len(), ops, "no file written");
1521        assert_eq!(count(&f.store, "SELECT count(*) FROM version"), 1);
1522        assert_eq!(wraps(&f.store), 1, "nothing wrapped");
1523        let log = audit_log(&f.store);
1524        assert_eq!(
1525            (log[1]["status"].clone(), log[1]["version"].clone()),
1526            (200.into(), version.to_string().into())
1527        );
1528    }
1529
1530    #[test]
1531    fn another_body_for_a_stored_uuid_is_a_conflict_and_writes_nothing() {
1532        let f = fixture();
1533        let (found, body) = vcon(UUID, "first");
1534        f.store.create(&f.caller, &found, &body).expect("stored");
1535        let ops = f.fs.log().len();
1536        // The same length as the first body, so only the bytes differ.
1537        let (found, other) = vcon(UUID, "other");
1538        assert_eq!(
1539            f.store.create(&f.caller, &found, &other),
1540            Err(StoreError::Conflict)
1541        );
1542        assert_eq!(f.fs.log().len(), ops, "no file written");
1543        assert_eq!(wraps(&f.store), 1, "nothing wrapped");
1544        assert_eq!(audit_log(&f.store)[1]["status"], 409);
1545    }
1546
1547    #[test]
1548    fn a_deleted_or_purged_uuid_is_gone_and_writes_nothing() {
1549        for sql in [
1550            "INSERT INTO vcon (uuid, current, deleted_at) VALUES (?1, NULL, 1)",
1551            "INSERT INTO tombstone (uuid, purged_at) VALUES (?1, 1)",
1552        ] {
1553            let f = fixture();
1554            let (found, body) = vcon(UUID, "first");
1555            f.store
1556                .conn()
1557                .execute(sql, [found.uuid.as_bytes()])
1558                .expect(sql);
1559            let ops = f.fs.log().len();
1560            assert_eq!(
1561                f.store.create(&f.caller, &found, &body),
1562                Err(StoreError::Gone),
1563                "{sql}"
1564            );
1565            assert_eq!(f.fs.log().len(), ops, "no file written");
1566            assert_eq!(wraps(&f.store), 0, "nothing wrapped");
1567            assert_eq!(audit_log(&f.store)[0]["status"], 410);
1568        }
1569    }
1570
1571    #[test]
1572    fn counts_include_hidden_versions_and_held_uuids() {
1573        let f = fixture();
1574        let none = Counts {
1575            versions: 0,
1576            held: 0,
1577        };
1578        assert_eq!(f.store.counts(), Ok(none));
1579        let (found, old) = stored(&f, "first");
1580        let (_, newer) = vcon(UUID, "second");
1581        f.store
1582            .replace(&f.caller, old, &found, &newer)
1583            .expect("replaced");
1584        f.store
1585            .delete(&f.caller, found.uuid, Retention::Years(7))
1586            .expect("deleted");
1587        let (other, body) = vcon("01a07da8-c2bb-83e5-b9a2-279e0d16bc47", "other");
1588        f.store.create(&f.caller, &other, &body).expect("stored");
1589        assert_eq!(
1590            f.store.counts(),
1591            Ok(Counts {
1592                versions: 3,
1593                held: 0
1594            }),
1595            "two hidden versions and a live one"
1596        );
1597        f.store
1598            .conn()
1599            .execute(
1600                "UPDATE vcon SET hold = 1 WHERE uuid = ?1",
1601                [found.uuid.as_bytes()],
1602            )
1603            .expect("a hold");
1604        assert_eq!(f.store.counts().map(|c| c.held), Ok(1));
1605    }
1606
1607    #[test]
1608    fn a_negative_wrap_count_is_damage_and_stores_nothing() {
1609        let f = fixture();
1610        f.store
1611            .conn()
1612            .execute(
1613                "INSERT INTO key_use (tenant_key_id, wraps) VALUES (?1, -1)",
1614                [f.store.tenant_key.id().bytes()],
1615            )
1616            .expect("a damaged count");
1617        let (found, body) = vcon(UUID, "first");
1618        let ops = f.fs.log().len();
1619        assert_eq!(
1620            f.store.create(&f.caller, &found, &body),
1621            Err(StoreError::Io)
1622        );
1623        assert_eq!(f.fs.log().len(), ops, "no file written");
1624    }
1625
1626    #[test]
1627    fn a_tenant_key_at_its_wrap_limit_refuses_new_vcons() {
1628        let f = fixture();
1629        f.store
1630            .conn()
1631            .execute(
1632                "INSERT INTO key_use (tenant_key_id, wraps) VALUES (?1, ?2)",
1633                params![f.store.tenant_key.id().bytes(), 1_i64 << 32],
1634            )
1635            .expect("at the limit");
1636        let (found, body) = vcon(UUID, "first");
1637        let ops = f.fs.log().len();
1638        assert_eq!(
1639            f.store.create(&f.caller, &found, &body),
1640            Err(StoreError::LimitReached)
1641        );
1642        assert_eq!(f.fs.log().len(), ops, "no file written");
1643        assert_eq!(audit_log(&f.store)[0]["status"], 503);
1644    }
1645
1646    #[test]
1647    fn a_missing_current_file_is_damage_not_a_conflict() {
1648        let f = fixture();
1649        let (found, body) = vcon(UUID, "first");
1650        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1651            panic!("a new vCon")
1652        };
1653        f.fs.remove(&f.store.objects_dir.join(version.to_string()))
1654            .expect("remove");
1655        assert_eq!(
1656            f.store.create(&f.caller, &found, &body),
1657            Err(StoreError::Damaged)
1658        );
1659        assert_eq!(audit_log(&f.store)[1]["status"], 500);
1660    }
1661
1662    #[test]
1663    fn a_racing_create_that_loses_gets_a_conflict_and_leaves_no_file() {
1664        let f = Arc::new(fixture());
1665        let (found, body) = vcon(UUID, "first");
1666        let winner = f.clone();
1667        *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
1668            let (found, other) = vcon(UUID, "second");
1669            assert!(matches!(
1670                winner.store.create(&winner.caller, &found, &other),
1671                Ok(Created::New(_))
1672            ));
1673        }));
1674        assert_eq!(
1675            f.store.create(&f.caller, &found, &body),
1676            Err(StoreError::Conflict)
1677        );
1678        assert_eq!(
1679            count(&f.store, "SELECT count(*) FROM version"),
1680            1,
1681            "only the winner"
1682        );
1683        assert_eq!(
1684            f.fs.list(&f.store.objects_dir).expect("list").len(),
1685            1,
1686            "the loser's file is gone"
1687        );
1688        assert_eq!(wraps(&f.store), 2, "both wraps are counted");
1689        let statuses: Vec<_> = audit_log(&f.store)
1690            .iter()
1691            .map(|r| r["status"].clone())
1692            .collect();
1693        assert_eq!(statuses, [201, 409]);
1694    }
1695
1696    #[test]
1697    fn a_create_whose_audit_record_fails_leaves_no_row_and_no_file() {
1698        let f = fixture();
1699        // Every audit insert now fails, as a full disk or a broken log would.
1700        f.store
1701            .conn()
1702            .execute_batch(
1703                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
1704                 BEGIN SELECT RAISE(ABORT, 'audit fails'); END;",
1705            )
1706            .expect("trigger");
1707        let (found, body) = vcon(UUID, "first");
1708        assert_eq!(
1709            f.store.create(&f.caller, &found, &body),
1710            Err(StoreError::AuditFailed)
1711        );
1712        assert_eq!(count(&f.store, "SELECT count(*) FROM version"), 0);
1713        assert_eq!(count(&f.store, "SELECT count(*) FROM vcon"), 0);
1714        assert_eq!(
1715            f.fs.list(&f.store.objects_dir).expect("list"),
1716            Vec::<std::ffi::OsString>::new()
1717        );
1718    }
1719
1720    #[test]
1721    fn a_create_whose_commit_outcome_is_unknown_keeps_its_object() {
1722        let f = fixture();
1723        let (found, body) = vcon(UUID, "first");
1724        // The wrap count commits first; the second commit, which adds the
1725        // rows, is kept and then reported as failed, as a lost connection
1726        // reports a commit the database made.
1727        f.store.catalog.fail_commit(2, CommitError::Unknown);
1728        assert_eq!(
1729            f.store.create(&f.caller, &found, &body),
1730            Err(StoreError::Io),
1731            "a_create_whose_commit_outcome_is_unknown_keeps_its_object: f.store.create(&f.caller, &found, &body)"
1732        );
1733        let stored = f
1734            .store
1735            .get(&f.caller, found.uuid)
1736            .expect("the kept row reads");
1737        assert_eq!(
1738            stored.body, body,
1739            "a_create_whose_commit_outcome_is_unknown_keeps_its_object: stored.body"
1740        );
1741        assert_eq!(f.store.check(), Ok(Vec::new()), "no row without its object");
1742        drop(f.open().expect("reopens"));
1743        assert_eq!(
1744            f.store.get(&f.caller, found.uuid).map(|s| s.body),
1745            Ok(body),
1746            "recovery keeps an object a row names"
1747        );
1748    }
1749
1750    #[test]
1751    fn a_replace_whose_commit_outcome_is_unknown_keeps_its_object() {
1752        let f = fixture();
1753        let (found, body) = vcon(UUID, "first");
1754        let Ok(Created::New(first)) = f.store.create(&f.caller, &found, &body) else {
1755            panic!("a new vCon")
1756        };
1757        let (found, second) = vcon(UUID, "second");
1758        f.store.catalog.fail_commit(2, CommitError::Unknown);
1759        assert_eq!(
1760            f.store.replace(&f.caller, first, &found, &second),
1761            Err(StoreError::Io),
1762            "a_replace_whose_commit_outcome_is_unknown_keeps_its_object: f.store.replace(&f.caller, first, &found, &second)"
1763        );
1764        let stored = f
1765            .store
1766            .get(&f.caller, found.uuid)
1767            .expect("the kept row reads");
1768        assert_eq!(
1769            stored.body, second,
1770            "a_replace_whose_commit_outcome_is_unknown_keeps_its_object: stored.body"
1771        );
1772        assert_eq!(f.store.check(), Ok(Vec::new()), "no row without its object");
1773    }
1774
1775    #[test]
1776    fn a_create_whose_commit_rolls_back_leaves_no_object() {
1777        let f = fixture();
1778        let (found, body) = vcon(UUID, "first");
1779        f.store.catalog.fail_commit(2, CommitError::RolledBack);
1780        assert_eq!(
1781            f.store.create(&f.caller, &found, &body),
1782            Err(StoreError::Io),
1783            "a_create_whose_commit_rolls_back_leaves_no_object: f.store.create(&f.caller, &found, &body)"
1784        );
1785        assert_eq!(
1786            count(&f.store, "SELECT count(*) FROM version"),
1787            0,
1788            "a_create_whose_commit_rolls_back_leaves_no_object: count(&f.store, \"SELECT count(*) FROM version\")"
1789        );
1790        assert_eq!(
1791            f.fs.list(&f.store.objects_dir).expect("list"),
1792            Vec::<std::ffi::OsString>::new(),
1793            "a_create_whose_commit_rolls_back_leaves_no_object: f.fs.list(&f.store.objects_dir).expect(\"list\")"
1794        );
1795    }
1796
1797    fn get_entry_status(f: &Fixture) -> Value {
1798        audit_log(&f.store).last().expect("a record")["status"].clone()
1799    }
1800
1801    #[test]
1802    fn a_stored_vcon_reads_back_byte_for_byte_and_is_recorded() {
1803        let f = fixture();
1804        let (found, body) = vcon(UUID, "first");
1805        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1806            panic!("a new vCon")
1807        };
1808        let stored = f.store.get(&f.caller, found.uuid).expect("reads");
1809        assert_eq!(
1810            stored,
1811            Stored {
1812                version,
1813                form: vcon::Form::Unsigned,
1814                gzip: false,
1815                body
1816            }
1817        );
1818        let log = audit_log(&f.store);
1819        let read = log.last().expect("a record");
1820        assert_eq!(read["action"], "read");
1821        assert_eq!(read["status"], 200);
1822        assert_eq!(read["version"], version.to_string());
1823        assert_eq!(read["target"], UUID);
1824    }
1825
1826    #[test]
1827    fn a_uuid_never_stored_is_not_found() {
1828        let f = fixture();
1829        let (found, _) = vcon(UUID, "first");
1830        assert_eq!(
1831            f.store.get(&f.caller, found.uuid),
1832            Err(StoreError::NotFound)
1833        );
1834        assert_eq!(get_entry_status(&f), 404);
1835    }
1836
1837    #[test]
1838    fn a_deleted_or_purged_uuid_is_gone() {
1839        for sql in [
1840            "UPDATE vcon SET current = NULL, deleted_at = 1 WHERE uuid = ?1",
1841            "DELETE FROM vcon WHERE uuid = ?1; INSERT INTO tombstone (uuid, purged_at) VALUES (?1, 1)",
1842        ] {
1843            let f = fixture();
1844            let (found, body) = vcon(UUID, "first");
1845            f.store.create(&f.caller, &found, &body).expect("stored");
1846            for statement in sql.split("; ") {
1847                f.store
1848                    .conn()
1849                    .execute(statement, [found.uuid.as_bytes()])
1850                    .expect(statement);
1851            }
1852            assert_eq!(
1853                f.store.get(&f.caller, found.uuid),
1854                Err(StoreError::Gone),
1855                "{sql}"
1856            );
1857            assert_eq!(get_entry_status(&f), 410);
1858        }
1859    }
1860
1861    #[test]
1862    fn a_missing_or_damaged_file_is_a_500_never_an_empty_body() {
1863        let f = fixture();
1864        let (found, body) = vcon(UUID, "first");
1865        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1866            panic!("a new vCon")
1867        };
1868        let file = f.store.objects_dir.join(version.to_string());
1869        let blob = f.fs.read(&file).expect("file");
1870        f.fs.remove(&file).expect("remove");
1871        assert_eq!(
1872            f.store.get(&f.caller, found.uuid),
1873            Err(StoreError::Damaged),
1874            "missing"
1875        );
1876        assert_eq!(get_entry_status(&f), 500);
1877        let mut bad = blob.clone();
1878        let last = bad.len() - 1;
1879        bad[last] ^= 1;
1880        f.fs.write_new(&file, &bad).expect("write");
1881        assert_eq!(
1882            f.store.get(&f.caller, found.uuid),
1883            Err(StoreError::Damaged),
1884            "tampered"
1885        );
1886    }
1887
1888    /// Makes the failure a read gives.
1889    pub(super) type Fail = fn() -> ObjectError;
1890
1891    /// Objects whose every read fails as `fail` makes the failure, and
1892    /// whose other calls reach `inner`.
1893    pub(super) struct ReadsFail {
1894        pub(super) inner: Arc<dyn Objects>,
1895        pub(super) fail: Fail,
1896    }
1897
1898    impl Objects for ReadsFail {
1899        fn put(&self, version: VersionId, blob: &[u8]) -> Result<(), ObjectError> {
1900            self.inner.put(version, blob)
1901        }
1902
1903        fn get(&self, _: VersionId) -> Result<Vec<u8>, ObjectError> {
1904            Err((self.fail)())
1905        }
1906
1907        fn remove(&self, version: VersionId) -> Result<(), ObjectError> {
1908            self.inner.remove(version)
1909        }
1910
1911        fn list(&self) -> Result<Vec<String>, ObjectError> {
1912            self.inner.list()
1913        }
1914
1915        fn remove_name(&self, name: &str) -> Result<(), ObjectError> {
1916            self.inner.remove_name(name)
1917        }
1918
1919        fn sync(&self) -> Result<(), ObjectError> {
1920            self.inner.sync()
1921        }
1922    }
1923
1924    /// Objects that are read as stored, and a listing that fails.
1925    struct ListFails {
1926        inner: Arc<dyn Objects>,
1927        fail: Fail,
1928    }
1929
1930    impl Objects for ListFails {
1931        fn put(&self, version: VersionId, blob: &[u8]) -> Result<(), ObjectError> {
1932            self.inner.put(version, blob)
1933        }
1934
1935        fn get(&self, version: VersionId) -> Result<Vec<u8>, ObjectError> {
1936            self.inner.get(version)
1937        }
1938
1939        fn remove(&self, version: VersionId) -> Result<(), ObjectError> {
1940            self.inner.remove(version)
1941        }
1942
1943        fn list(&self) -> Result<Vec<String>, ObjectError> {
1944            Err((self.fail)())
1945        }
1946
1947        fn remove_name(&self, name: &str) -> Result<(), ObjectError> {
1948            self.inner.remove_name(name)
1949        }
1950
1951        fn sync(&self) -> Result<(), ObjectError> {
1952            self.inner.sync()
1953        }
1954    }
1955
1956    /// A listing of the objects that the storage fails is the storage's
1957    /// failure, with its kind, as a read's is; a listing that says no
1958    /// object has the name, which no listing means, is a failed
1959    /// examination, not a storage error.
1960    #[test]
1961    fn a_listing_the_storage_fails_is_reported_with_its_kind() {
1962        let cases: [(Fail, ExamineError); 2] = [
1963            (
1964                || storage_failed(std::io::ErrorKind::PermissionDenied),
1965                ExamineError::Objects {
1966                    kind: std::io::ErrorKind::PermissionDenied,
1967                    os_error: None,
1968                },
1969            ),
1970            (
1971                || ObjectError::Missing,
1972                ExamineError::Failed(StoreError::Io),
1973            ),
1974        ];
1975        for (fail, expected) in cases {
1976            let mut f = fixture();
1977            let (found, body) = vcon(UUID, "first");
1978            f.store.create(&f.caller, &found, &body).expect("stored");
1979            f.store.objects = Arc::new(ListFails {
1980                inner: f.store.objects.clone(),
1981                fail,
1982            });
1983            assert_eq!(
1984                f.store
1985                    .examine(
1986                        Retention::Years(7),
1987                        datetime!(2026-10-23 12:00 UTC),
1988                        datetime!(2026-10-23 12:00 UTC),
1989                    )
1990                    .err(),
1991                Some(expected),
1992                "examine fails with the listing's failure"
1993            );
1994        }
1995    }
1996
1997    /// A storage failure, of the kind the system or the S3 backend gives.
1998    fn storage_failed(kind: std::io::ErrorKind) -> ObjectError {
1999        ObjectError::Io(std::io::Error::from(kind))
2000    }
2001
2002    /// Only an object the storage says is not there is damage: a read the
2003    /// storage fails (a disk error, a refused key, no answer in time) is
2004    /// a failure of the server, in every read that opens a version.
2005    #[test]
2006    fn a_read_the_storage_fails_is_io_and_only_a_missing_object_is_damage() {
2007        let cases: [(Fail, StoreError, &str); 5] = [
2008            (|| ObjectError::Missing, StoreError::Damaged, "missing"),
2009            (
2010                || ObjectError::Io(std::io::Error::from_raw_os_error(libc::EIO)),
2011                StoreError::Io,
2012                "EIO",
2013            ),
2014            (
2015                || storage_failed(std::io::ErrorKind::PermissionDenied),
2016                StoreError::Io,
2017                "permission denied",
2018            ),
2019            (
2020                || storage_failed(std::io::ErrorKind::ConnectionRefused),
2021                StoreError::Io,
2022                "connection refused",
2023            ),
2024            (
2025                || storage_failed(std::io::ErrorKind::TimedOut),
2026                StoreError::Io,
2027                "timed out",
2028            ),
2029        ];
2030        for (fail, expected, why) in cases {
2031            let mut f = fixture();
2032            let (found, body) = vcon(UUID, "first");
2033            let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
2034                panic!("a new vCon")
2035            };
2036            f.store.objects = Arc::new(ReadsFail {
2037                inner: f.store.objects.clone(),
2038                fail,
2039            });
2040            assert_eq!(
2041                f.store.get(&f.caller, found.uuid),
2042                Err(expected),
2043                "{why}: get"
2044            );
2045            assert_eq!(get_entry_status(&f), 500, "{why}: get is recorded");
2046            assert_eq!(
2047                f.store.create(&f.caller, &found, &body),
2048                Err(expected),
2049                "{why}: create of the same body"
2050            );
2051            for asked in [None, Some(version)] {
2052                assert_eq!(
2053                    f.store.legal_get(&f.caller, found.uuid, asked).err(),
2054                    Some(expected),
2055                    "{why}: legal_get {asked:?}"
2056                );
2057            }
2058            let examined = f.store.examine(
2059                Retention::Years(7),
2060                datetime!(2026-10-23 12:00 UTC),
2061                datetime!(2026-10-23 12:00 UTC),
2062            );
2063            match expected {
2064                StoreError::Damaged => assert_eq!(
2065                    examined.map(|e| e.damaged),
2066                    Ok(vec![version]),
2067                    "{why}: examine lists the version"
2068                ),
2069                _ => {
2070                    let ObjectError::Io(failed) = fail() else {
2071                        panic!("{why}: a storage failure")
2072                    };
2073                    assert_eq!(
2074                        examined.err(),
2075                        Some(ExamineError::Objects {
2076                            kind: failed.kind(),
2077                            os_error: failed.raw_os_error(),
2078                        }),
2079                        "{why}: examine fails with the storage's error kind, listing nothing as damaged"
2080                    );
2081                }
2082            }
2083        }
2084    }
2085
2086    /// Collects what the log writes.
2087    #[derive(Clone, Default)]
2088    pub(super) struct Capture(pub(super) Arc<Mutex<Vec<u8>>>);
2089
2090    impl std::io::Write for Capture {
2091        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
2092            self.0.lock().expect("lock").extend_from_slice(bytes);
2093            Ok(bytes.len())
2094        }
2095
2096        fn flush(&mut self) -> std::io::Result<()> {
2097            Ok(())
2098        }
2099    }
2100
2101    impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Capture {
2102        type Writer = Capture;
2103
2104        fn make_writer(&'a self) -> Capture {
2105            self.clone()
2106        }
2107    }
2108
2109    /// The text of a storage failure that names the object's key and a
2110    /// credential, as a service's message might.
2111    const LEAKY: &str = "tenants/1111/objects/0e0e AKIAIOSFODNN7EXAMPLE wJalrXUtnFEMI";
2112
2113    /// A failed read is logged with the failure's kind, and nothing of its
2114    /// text, the tenant, the uuid or the version, which may name an
2115    /// object's key or a credential.
2116    #[test]
2117    fn a_failed_read_is_logged_by_its_kind_only() {
2118        let mut f = fixture();
2119        let (found, body) = vcon(UUID, "first");
2120        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
2121            panic!("a new vCon")
2122        };
2123        f.store.objects = Arc::new(ReadsFail {
2124            inner: f.store.objects.clone(),
2125            fail: || {
2126                ObjectError::Io(std::io::Error::new(
2127                    std::io::ErrorKind::PermissionDenied,
2128                    LEAKY,
2129                ))
2130            },
2131        });
2132        let capture = Capture::default();
2133        let subscriber = tracing_subscriber::fmt()
2134            .with_writer(capture.clone())
2135            .with_ansi(false)
2136            .log_internal_errors(false)
2137            .finish();
2138        let read =
2139            tracing::subscriber::with_default(subscriber, || f.store.get(&f.caller, found.uuid));
2140        assert_eq!(read, Err(StoreError::Io), "the read fails as Io");
2141        let log = String::from_utf8(capture.0.lock().expect("lock").clone()).expect("UTF-8");
2142        assert!(log.contains("WARN"), "a warning: {log}");
2143        assert!(
2144            log.contains("kind=permission denied"),
2145            "the kind is logged: {log}"
2146        );
2147        // Each value is named by what it is, so a failure prints no value.
2148        let version = version.to_string();
2149        let tenant = TENANT.to_string();
2150        for (what, value) in [
2151            ("the error's text", LEAKY),
2152            ("the object's key", "tenants/1111"),
2153            ("the access key id", "AKIAIOSFODNN7EXAMPLE"),
2154            ("the secret key", "wJalrXUtnFEMI"),
2155            ("the uuid", UUID),
2156            ("the version id", version.as_str()),
2157            ("the tenant id", tenant.as_str()),
2158        ] {
2159            assert!(!log.contains(value), "{what} is logged");
2160        }
2161
2162        // A file's failure carries the system's error number too.
2163        f.store.objects = Arc::new(ReadsFail {
2164            inner: f.store.objects.clone(),
2165            fail: || ObjectError::Io(std::io::Error::from_raw_os_error(libc::EIO)),
2166        });
2167        let capture = Capture::default();
2168        let subscriber = tracing_subscriber::fmt()
2169            .with_writer(capture.clone())
2170            .with_ansi(false)
2171            .log_internal_errors(false)
2172            .finish();
2173        tracing::subscriber::with_default(subscriber, || f.store.get(&f.caller, found.uuid))
2174            .expect_err("fails");
2175        let log = String::from_utf8(capture.0.lock().expect("lock").clone()).expect("UTF-8");
2176        assert!(
2177            log.contains(&format!("os_error={}", libc::EIO)),
2178            "the error number is logged: {log}"
2179        );
2180    }
2181
2182    /// A data key that does not open is damage; a key page the system will
2183    /// not lock is a failure of the server, not of the stored data.
2184    #[test]
2185    fn only_a_wrapped_key_that_does_not_open_is_damage() {
2186        assert_eq!(
2187            key_failed(envelope::KeyError::Damaged),
2188            StoreError::Damaged,
2189            "a key that does not open"
2190        );
2191        assert_eq!(
2192            key_failed(envelope::KeyError::Memory(
2193                std::io::Error::from_raw_os_error(libc::ENOMEM)
2194            )),
2195            StoreError::Io,
2196            "a key page that cannot be locked"
2197        );
2198    }
2199
2200    #[test]
2201    fn a_read_racing_a_delete_never_returns_the_body() {
2202        let f = Arc::new(fixture());
2203        let (found, body) = vcon(UUID, "first");
2204        f.store.create(&f.caller, &found, &body).expect("stored");
2205        let deleter = f.clone();
2206        *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2207            deleter
2208                .store
2209                .conn()
2210                .execute(
2211                    "UPDATE vcon SET current = NULL, deleted_at = 1 WHERE uuid = ?1",
2212                    [found.uuid.as_bytes()],
2213                )
2214                .expect("delete");
2215        }));
2216        assert_eq!(f.store.get(&f.caller, found.uuid), Err(StoreError::Gone));
2217        assert_eq!(get_entry_status(&f), 410);
2218    }
2219
2220    #[test]
2221    fn a_read_racing_a_new_version_starts_again_and_returns_the_new_one() {
2222        let f = Arc::new(fixture());
2223        let (found, body) = vcon(UUID, "first");
2224        f.store.create(&f.caller, &found, &body).expect("stored");
2225        let (_, newer) = vcon(UUID, "newer");
2226        let version = VersionId::generate();
2227        let wrapped = f
2228            .store
2229            .write_version(found.uuid, version, &newer)
2230            .expect("written");
2231        let writer = f.clone();
2232        *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2233            let conn = writer.store.conn();
2234            conn.execute(
2235                "INSERT INTO version
2236                     (version, uuid, form, gzip, size, stored_at, tenant_key_id, wrapped_key)
2237                 VALUES (?1, ?2, 'unsigned', 0, 0, 0, ?3, ?4)",
2238                params![
2239                    version.0,
2240                    found.uuid.as_bytes(),
2241                    writer.store.tenant_key.id().bytes(),
2242                    wrapped
2243                ],
2244            )
2245            .expect("new version");
2246            conn.execute(
2247                "UPDATE vcon SET current = ?1 WHERE uuid = ?2",
2248                params![version.0, found.uuid.as_bytes()],
2249            )
2250            .expect("made current");
2251        }));
2252        let stored = f.store.get(&f.caller, found.uuid).expect("reads");
2253        assert_eq!((stored.version, stored.body), (version, newer));
2254        let reads = audit_log(&f.store)
2255            .iter()
2256            .filter(|r| r["action"] == "read")
2257            .count();
2258        assert_eq!(reads, 1, "one record for the one request");
2259    }
2260
2261    #[test]
2262    fn every_form_and_the_gzip_flag_read_back_as_stored() {
2263        use base64::Engine;
2264        use std::io::Write;
2265        let f = fixture();
2266        let uuids = [
2267            "01a07da8-c2bb-83e5-b9a2-279e0d16bc01",
2268            "01a07da8-c2bb-83e5-b9a2-279e0d16bc02",
2269            "01a07da8-c2bb-83e5-b9a2-279e0d16bc03",
2270        ];
2271        let (_, unsigned) = vcon(uuids[0], "plain");
2272        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
2273        gz.write_all(&unsigned).expect("gzip");
2274        let gzipped = gz.finish().expect("gzip");
2275        let (_, inner) = vcon(uuids[1], "signed");
2276        let signed = format!(
2277            r#"{{"payload": "{}", "signatures": [{{"header": {{}}}}]}}"#,
2278            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(inner)
2279        )
2280        .into_bytes();
2281        let encrypted = format!(
2282            r#"{{"unprotected": {{"uuid": "{}"}}, "ciphertext": "x", "recipients": []}}"#,
2283            uuids[2]
2284        )
2285        .into_bytes();
2286        let cases = [
2287            (gzipped, vcon::Form::Unsigned, true),
2288            (signed, vcon::Form::Signed, false),
2289            (encrypted, vcon::Form::Encrypted, false),
2290        ];
2291        for (body, form, gzip) in cases {
2292            let found = inspect(&body, None, &Limits::new(1 << 20), &BTreeSet::new())
2293                .expect("a valid vCon");
2294            assert_eq!((found.form, found.gzip), (form, gzip));
2295            f.store.create(&f.caller, &found, &body).expect("stored");
2296            let stored = f.store.get(&f.caller, found.uuid).expect("reads");
2297            assert_eq!((stored.form, stored.gzip, stored.body), (form, gzip, body));
2298        }
2299    }
2300
2301    /// Stores `subject` under UUID and returns its version.
2302    fn stored(f: &Fixture, subject: &str) -> (Inspection, VersionId) {
2303        let (found, body) = vcon(UUID, subject);
2304        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
2305            panic!("a new vCon")
2306        };
2307        (found, version)
2308    }
2309
2310    #[test]
2311    fn a_replace_makes_a_new_current_version_and_hides_the_old_one() {
2312        let f = fixture();
2313        let (found, old) = stored(&f, "first");
2314        let (_, newer) = vcon(UUID, "second");
2315        let version = f
2316            .store
2317            .replace(&f.caller, old, &found, &newer)
2318            .expect("replaced");
2319        assert_ne!(version, old);
2320        let stored = f.store.get(&f.caller, found.uuid).expect("reads");
2321        assert_eq!((stored.version, stored.body), (version, newer));
2322        let hidden: Option<i64> = f
2323            .store
2324            .conn()
2325            .query_row(
2326                "SELECT hidden_at FROM version WHERE version = ?1",
2327                [old.0],
2328                |r| r.get(0),
2329            )
2330            .expect("the old row is kept");
2331        assert_eq!(
2332            hidden,
2333            Some(crate::clock::nanos(datetime!(2026-10-23 12:00 UTC))),
2334            "the old version is hidden at the replace's time"
2335        );
2336        assert!(
2337            f.fs.read(&f.store.objects_dir.join(old.to_string()))
2338                .is_ok(),
2339            "its file is kept"
2340        );
2341        let record = audit_log(&f.store)
2342            .into_iter()
2343            .find(|r| r["action"] == "replace")
2344            .expect("a replace record");
2345        assert_eq!(
2346            (record["status"].clone(), record["version"].clone()),
2347            (200.into(), version.to_string().into())
2348        );
2349    }
2350
2351    #[test]
2352    fn a_replace_of_a_missing_or_gone_uuid_is_refused() {
2353        let f = fixture();
2354        let (found, body) = vcon(UUID, "first");
2355        let any = VersionId([7; 16]);
2356        assert_eq!(
2357            f.store.replace(&f.caller, any, &found, &body),
2358            Err(StoreError::NotFound)
2359        );
2360        assert_eq!(get_entry_status(&f), 404);
2361        let (found, old) = stored(&f, "first");
2362        f.store
2363            .conn()
2364            .execute(
2365                "UPDATE vcon SET current = NULL, deleted_at = 1 WHERE uuid = ?1",
2366                [found.uuid.as_bytes()],
2367            )
2368            .expect("delete");
2369        assert_eq!(
2370            f.store.replace(&f.caller, old, &found, &body),
2371            Err(StoreError::Gone)
2372        );
2373        assert_eq!(get_entry_status(&f), 410);
2374    }
2375
2376    #[test]
2377    fn a_stale_if_match_is_refused_and_writes_nothing() {
2378        let f = fixture();
2379        let (found, _) = stored(&f, "first");
2380        let ops = f.fs.log().len();
2381        let (_, newer) = vcon(UUID, "second");
2382        assert_eq!(
2383            f.store
2384                .replace(&f.caller, VersionId([7; 16]), &found, &newer),
2385            Err(StoreError::PreconditionFailed)
2386        );
2387        assert_eq!(f.fs.log().len(), ops, "no file written");
2388        assert_eq!(wraps(&f.store), 1, "nothing wrapped");
2389        assert_eq!(get_entry_status(&f), 412);
2390    }
2391
2392    #[test]
2393    fn a_signed_or_encrypted_current_version_is_immutable() {
2394        use base64::Engine;
2395        let f = fixture();
2396        let (found, old) = stored(&f, "first");
2397        let (_, inner) = vcon(UUID, "signed");
2398        let signed = format!(
2399            r#"{{"payload": "{}", "signatures": [{{"header": {{}}}}]}}"#,
2400            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(inner)
2401        )
2402        .into_bytes();
2403        let signed_found =
2404            inspect(&signed, None, &Limits::new(1 << 20), &BTreeSet::new()).expect("a signed vCon");
2405        let version = f
2406            .store
2407            .replace(&f.caller, old, &signed_found, &signed)
2408            .expect("an unsigned vCon may be replaced by a signed one");
2409        let (_, newer) = vcon(UUID, "second");
2410        let ops = f.fs.log().len();
2411        assert_eq!(
2412            f.store.replace(&f.caller, version, &found, &newer),
2413            Err(StoreError::Immutable)
2414        );
2415        assert_eq!(f.fs.log().len(), ops, "no file written");
2416        assert_eq!(get_entry_status(&f), 409);
2417
2418        let g = fixture();
2419        let encrypted = format!(
2420            r#"{{"unprotected": {{"uuid": "{UUID}"}}, "ciphertext": "x", "recipients": []}}"#
2421        )
2422        .into_bytes();
2423        let enc_found = inspect(&encrypted, None, &Limits::new(1 << 20), &BTreeSet::new())
2424            .expect("an encrypted vCon");
2425        let Ok(Created::New(enc_version)) = g.store.create(&g.caller, &enc_found, &encrypted)
2426        else {
2427            panic!("stored")
2428        };
2429        assert_eq!(
2430            g.store.replace(&g.caller, enc_version, &found, &newer),
2431            Err(StoreError::Immutable)
2432        );
2433    }
2434
2435    #[test]
2436    fn a_replace_at_the_wrap_limit_is_refused() {
2437        let f = fixture();
2438        let (found, old) = stored(&f, "first");
2439        f.store
2440            .conn()
2441            .execute("UPDATE key_use SET wraps = ?1", [1_i64 << 32])
2442            .expect("at the limit");
2443        let (_, newer) = vcon(UUID, "second");
2444        assert_eq!(
2445            f.store.replace(&f.caller, old, &found, &newer),
2446            Err(StoreError::LimitReached)
2447        );
2448        assert_eq!(get_entry_status(&f), 503);
2449    }
2450
2451    #[test]
2452    fn of_two_replaces_racing_on_one_version_the_second_to_commit_loses() {
2453        let f = Arc::new(fixture());
2454        let (found, old) = stored(&f, "first");
2455        let winner = f.clone();
2456        let racer = found;
2457        *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2458            let (_, body) = vcon(UUID, "winner");
2459            winner
2460                .store
2461                .replace(&winner.caller, old, &racer, &body)
2462                .expect("wins");
2463        }));
2464        let (_, body) = vcon(UUID, "loser");
2465        assert_eq!(
2466            f.store.replace(&f.caller, old, &found, &body),
2467            Err(StoreError::PreconditionFailed)
2468        );
2469        assert_eq!(
2470            f.fs.list(&f.store.objects_dir).expect("list").len(),
2471            2,
2472            "first and winner only"
2473        );
2474        assert_eq!(wraps(&f.store), 3, "every wrap counted");
2475        assert_eq!(get_entry_status(&f), 412);
2476    }
2477
2478    #[test]
2479    fn two_threads_replacing_with_the_same_if_match_one_wins() {
2480        let f = Arc::new(fixture());
2481        let (_, old) = stored(&f, "first");
2482        let threads: Vec<_> = ["one", "two"]
2483            .into_iter()
2484            .map(|subject| {
2485                let f = f.clone();
2486                std::thread::spawn(move || {
2487                    let (found, body) = vcon(UUID, subject);
2488                    f.store.replace(&f.caller, old, &found, &body)
2489                })
2490            })
2491            .collect();
2492        let results: Vec<_> = threads
2493            .into_iter()
2494            .map(|t| t.join().expect("thread"))
2495            .collect();
2496        assert_eq!(
2497            results.iter().filter(|r| r.is_ok()).count(),
2498            1,
2499            "{results:?}"
2500        );
2501        assert!(
2502            results.contains(&Err(StoreError::PreconditionFailed)),
2503            "{results:?}"
2504        );
2505    }
2506
2507    #[test]
2508    fn a_replace_whose_audit_record_fails_changes_nothing() {
2509        let f = fixture();
2510        let (found, old) = stored(&f, "first");
2511        f.store
2512            .conn()
2513            .execute_batch(
2514                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
2515                 BEGIN SELECT RAISE(ABORT, 'audit fails'); END;",
2516            )
2517            .expect("trigger");
2518        let (_, newer) = vcon(UUID, "second");
2519        assert_eq!(
2520            f.store.replace(&f.caller, old, &found, &newer),
2521            Err(StoreError::AuditFailed)
2522        );
2523        f.store
2524            .conn()
2525            .execute_batch("DROP TRIGGER no_audit")
2526            .expect("drop trigger");
2527        assert_eq!(
2528            f.store.get(&f.caller, found.uuid).expect("reads").version,
2529            old
2530        );
2531        assert_eq!(
2532            f.fs.list(&f.store.objects_dir).expect("list").len(),
2533            1,
2534            "only the first file"
2535        );
2536    }
2537
2538    fn hidden_versions(f: &Fixture) -> i64 {
2539        count(
2540            &f.store,
2541            "SELECT count(*) FROM version WHERE hidden_at IS NOT NULL",
2542        )
2543    }
2544
2545    #[test]
2546    fn a_deleted_uuid_answers_gone_and_keeps_its_versions_hidden() {
2547        let f = fixture();
2548        let (found, old) = stored(&f, "first");
2549        let (_, newer) = vcon(UUID, "second");
2550        f.clock.set(datetime!(2026-10-23 13:00 UTC));
2551        let current = f
2552            .store
2553            .replace(&f.caller, old, &found, &newer)
2554            .expect("replaced");
2555        f.clock.set(datetime!(2026-10-23 14:00 UTC));
2556        assert_eq!(
2557            f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2558            Ok(())
2559        );
2560        let record = audit_log(&f.store).pop().expect("a record");
2561        assert_eq!(
2562            (record["action"].clone(), record["status"].clone()),
2563            ("delete".into(), 204.into())
2564        );
2565        let hidden_at = |version: VersionId| -> i64 {
2566            f.store
2567                .conn()
2568                .query_row(
2569                    "SELECT hidden_at FROM version WHERE version = ?1",
2570                    [version.0],
2571                    |r| r.get(0),
2572                )
2573                .expect("hidden")
2574        };
2575        assert_eq!(
2576            hidden_at(old),
2577            nanos(datetime!(2026-10-23 13:00 UTC)),
2578            "hidden by the replace"
2579        );
2580        assert_eq!(
2581            hidden_at(current),
2582            nanos(datetime!(2026-10-23 14:00 UTC)),
2583            "hidden by the delete"
2584        );
2585        assert_eq!(f.store.get(&f.caller, found.uuid), Err(StoreError::Gone));
2586        let (_, body) = vcon(UUID, "third");
2587        assert_eq!(
2588            f.store.create(&f.caller, &found, &body),
2589            Err(StoreError::Gone)
2590        );
2591        assert_eq!(hidden_versions(&f), 2, "both versions hidden");
2592        assert_eq!(
2593            f.fs.list(&f.store.objects_dir).expect("list").len(),
2594            2,
2595            "files kept for legal reads"
2596        );
2597        let (current, deleted_at): (Option<Vec<u8>>, Option<i64>) = f
2598            .store
2599            .conn()
2600            .query_row(
2601                "SELECT current, deleted_at FROM vcon WHERE uuid = ?1",
2602                [found.uuid.as_bytes()],
2603                |r| Ok((r.get(0)?, r.get(1)?)),
2604            )
2605            .expect("row");
2606        assert_eq!(current, None);
2607        assert_eq!(deleted_at, Some(nanos(datetime!(2026-10-23 14:00 UTC))));
2608    }
2609
2610    #[test]
2611    fn deleting_a_deleted_or_purged_uuid_succeeds_again() {
2612        let f = fixture();
2613        let (found, _) = stored(&f, "first");
2614        f.store
2615            .delete(&f.caller, found.uuid, Retention::Years(7))
2616            .expect("deleted");
2617        assert_eq!(
2618            f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2619            Ok(())
2620        );
2621        assert_eq!(get_entry_status(&f), 204);
2622        let g = fixture();
2623        g.store
2624            .conn()
2625            .execute(
2626                "INSERT INTO tombstone (uuid, purged_at) VALUES (?1, 1)",
2627                [found.uuid.as_bytes()],
2628            )
2629            .expect("purged");
2630        assert_eq!(
2631            g.store.delete(&g.caller, found.uuid, Retention::Years(7)),
2632            Ok(())
2633        );
2634        assert_eq!(get_entry_status(&g), 204);
2635    }
2636
2637    #[test]
2638    fn deleting_a_uuid_never_stored_is_not_found() {
2639        let f = fixture();
2640        let (found, _) = vcon(UUID, "first");
2641        assert_eq!(
2642            f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2643            Err(StoreError::NotFound)
2644        );
2645        assert_eq!(get_entry_status(&f), 404);
2646    }
2647
2648    #[test]
2649    fn a_hold_does_not_stop_a_delete() {
2650        let f = fixture();
2651        let (found, _) = stored(&f, "first");
2652        f.store
2653            .conn()
2654            .execute(
2655                "UPDATE vcon SET hold = 1 WHERE uuid = ?1",
2656                [found.uuid.as_bytes()],
2657            )
2658            .expect("hold");
2659        assert_eq!(
2660            f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2661            Ok(())
2662        );
2663        assert_eq!(f.store.get(&f.caller, found.uuid), Err(StoreError::Gone));
2664    }
2665
2666    #[test]
2667    fn a_delete_whose_audit_record_fails_changes_nothing() {
2668        let f = fixture();
2669        let (found, version) = stored(&f, "first");
2670        f.store
2671            .conn()
2672            .execute_batch(
2673                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
2674                 BEGIN SELECT RAISE(ABORT, 'audit fails'); END;",
2675            )
2676            .expect("trigger");
2677        assert_eq!(
2678            f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2679            Err(StoreError::AuditFailed)
2680        );
2681        f.store
2682            .conn()
2683            .execute_batch("DROP TRIGGER no_audit")
2684            .expect("drop trigger");
2685        assert_eq!(
2686            f.store
2687                .get(&f.caller, found.uuid)
2688                .expect("still live")
2689                .version,
2690            version
2691        );
2692        assert_eq!(hidden_versions(&f), 0);
2693    }
2694
2695    #[test]
2696    fn only_the_optional_catalog_columns_may_be_empty() {
2697        let f = fixture();
2698        let conn = f.store.conn();
2699        let tables: [(&str, &[(&str, &str)]); 8] = [
2700            (
2701                "vcon",
2702                &[
2703                    ("uuid", "x'01'"),
2704                    ("current", "x'02'"),
2705                    ("deleted_at", "1"),
2706                    ("hold", "0"),
2707                ],
2708            ),
2709            (
2710                "version",
2711                &[
2712                    ("version", "x'02'"),
2713                    ("uuid", "x'01'"),
2714                    ("form", "'unsigned'"),
2715                    ("gzip", "0"),
2716                    ("size", "1"),
2717                    ("stored_at", "1"),
2718                    ("hidden_at", "1"),
2719                    ("tenant_key_id", "x'03'"),
2720                    ("wrapped_key", "x'04'"),
2721                    ("place_file", "x'05'"),
2722                    ("place_group", "0"),
2723                    ("place_row", "0"),
2724                ],
2725            ),
2726            (
2727                "parquet_file",
2728                &[
2729                    ("file_id", "x'05'"),
2730                    ("date", "'2026-10-23'"),
2731                    ("rows", "1"),
2732                    ("live_rows", "1"),
2733                    ("bytes", "1"),
2734                    ("created_at", "1"),
2735                    ("unnamed_at", "1"),
2736                ],
2737            ),
2738            ("purge_pending", &[("file_id", "x'05'")]),
2739            ("manifest", &[("seq", "1"), ("published_at", "1")]),
2740            ("tombstone", &[("uuid", "x'01'"), ("purged_at", "1")]),
2741            ("key_use", &[("tenant_key_id", "x'03'"), ("wraps", "1")]),
2742            (
2743                "audit",
2744                &[
2745                    ("at", "'2026-10-23T12:00Z'"),
2746                    ("actor", "'cli'"),
2747                    ("action", "'create'"),
2748                    ("target", "'x'"),
2749                    ("version", "'y'"),
2750                    ("status", "201"),
2751                    ("count", "1"),
2752                ],
2753            ),
2754        ];
2755        let may_be_empty: Vec<String> = tables
2756            .iter()
2757            .flat_map(|(table, row)| columns_taking_null(&conn, table, row))
2758            .collect();
2759        assert_eq!(
2760            may_be_empty,
2761            [
2762                "vcon.current",
2763                "vcon.deleted_at",
2764                "version.hidden_at",
2765                "version.place_file",
2766                "version.place_group",
2767                "version.place_row",
2768                "parquet_file.unnamed_at",
2769                // A rowid: NULL takes the next number, never a used one.
2770                "manifest.seq",
2771                "manifest.published_at",
2772                "audit.target",
2773                "audit.version",
2774                // A record that answers no request has no status.
2775                "audit.status"
2776            ]
2777        );
2778    }
2779
2780    #[test]
2781    fn a_new_stores_objects_directory_survives_a_crash() {
2782        let f = fixture();
2783        f.fs.crash();
2784        assert_eq!(
2785            f.fs.list(f.dir.path()).expect("list"),
2786            [std::ffi::OsString::from("objects")]
2787        );
2788    }
2789
2790    #[test]
2791    fn opening_removes_temporary_and_orphaned_files_and_nothing_else() {
2792        let mut f = fixture();
2793        let (found, version) = stored(&f, "first");
2794        let orphan = VersionId([0x0e; 16]);
2795        let objects = f.store.objects_dir.clone();
2796        for name in [
2797            format!("{orphan}"),
2798            format!("{orphan}.tmp"),
2799            format!("{version}.tmp"),
2800            "notes.txt".to_owned(),
2801        ] {
2802            f.fs.write_new(&objects.join(name), b"x").expect("write");
2803        }
2804        f.reopen();
2805        let names: Vec<String> =
2806            f.fs.list(&objects)
2807                .expect("list")
2808                .into_iter()
2809                .map(|n| n.to_string_lossy().into_owned())
2810                .collect();
2811        assert_eq!(names, [version.to_string(), "notes.txt".to_owned()]);
2812        assert_eq!(
2813            f.store
2814                .get(&f.caller, found.uuid)
2815                .expect("still reads")
2816                .version,
2817            version
2818        );
2819        let log = f.fs.log();
2820        let last_removal = log
2821            .iter()
2822            .rposition(|op| matches!(op, Op::Remove(_)))
2823            .expect("files were removed");
2824        assert!(
2825            log[last_removal..].contains(&Op::SyncDir(objects)),
2826            "the removals are synced"
2827        );
2828    }
2829
2830    /// A command beside a running server must not take the server's
2831    /// writes in progress for a crash's leftovers.
2832    #[test]
2833    fn opening_beside_a_server_removes_nothing() {
2834        let f = fixture();
2835        let (found, version) = stored(&f, "first");
2836        let orphan = VersionId([0x0e; 16]);
2837        let objects = f.store.objects_dir.clone();
2838        let mut written = vec![version.to_string()];
2839        for name in [
2840            format!("{orphan}"),
2841            format!("{orphan}.tmp"),
2842            format!("{version}.tmp"),
2843        ] {
2844            f.fs.write_new(&objects.join(&name), b"x").expect("write");
2845            written.push(name);
2846        }
2847        written.sort();
2848        let ops = f.fs.log().len();
2849        let beside = f.open_beside().expect("opens beside");
2850        let mut names: Vec<String> =
2851            f.fs.list(&objects)
2852                .expect("list")
2853                .into_iter()
2854                .map(|n| n.to_string_lossy().into_owned())
2855                .collect();
2856        names.sort();
2857        assert_eq!(names, written);
2858        assert!(
2859            !f.fs.log()[ops..]
2860                .iter()
2861                .any(|op| matches!(op, Op::Remove(_))),
2862            "nothing removed"
2863        );
2864        assert_eq!(
2865            beside.get(&f.caller, found.uuid).expect("reads").version,
2866            version
2867        );
2868    }
2869
2870    #[test]
2871    fn opening_checkpoints_the_wal_with_truncation() {
2872        let mut f = fixture();
2873        stored(&f, "first");
2874        let wal = f.dir.path().join("catalog.sqlite-wal");
2875        assert!(
2876            std::fs::metadata(&wal).expect("a WAL").len() > 0,
2877            "the WAL holds the write"
2878        );
2879        f.reopen();
2880        assert_eq!(std::fs::metadata(&wal).expect("a WAL").len(), 0);
2881    }
2882
2883    #[test]
2884    fn check_reports_a_version_whose_file_is_missing() {
2885        let f = fixture();
2886        let (_, version) = stored(&f, "first");
2887        assert_eq!(f.store.check(), Ok(vec![]));
2888        f.fs.remove(&f.store.objects_dir.join(version.to_string()))
2889            .expect("remove");
2890        assert_eq!(f.store.check(), Ok(vec![version]));
2891    }
2892
2893    #[test]
2894    fn opening_refuses_while_a_reader_stops_the_wal_from_being_truncated() {
2895        let f = fixture();
2896        stored(&f, "first");
2897        let ctx = Context::Tenant { tenant: TENANT };
2898        let tenant_key = envelope::unwrap(&f.master, &ctx, &f.wrapped).expect("unwraps");
2899        let catalog_key = envelope::catalog_key(&tenant_key).expect("catalog key");
2900        let mut reader = catalog::open(&f.dir.path().join("catalog.sqlite"), &catalog_key, "")
2901            .expect("a second connection");
2902        let read = reader.transaction().expect("read transaction");
2903        let _: i64 = read
2904            .query_row("SELECT count(*) FROM vcon", [], |r| r.get(0))
2905            .expect("a read holds a snapshot");
2906        assert!(matches!(f.open(), Err(StoreError::Io)));
2907        drop(read);
2908        assert!(f.open().is_ok(), "opens once the reader is done");
2909    }
2910
2911    /// The filesystem changes a create or replace makes when nothing
2912    /// fails: write, sync, rename, sync the directory.
2913    const WRITE_STEPS: usize = 4;
2914
2915    /// After a restart, no row lacks its file and every file has a row.
2916    fn assert_whole(f: &Fixture, step: usize) {
2917        assert_eq!(
2918            f.store.check(),
2919            Ok(vec![]),
2920            "a row without its file at step {step}"
2921        );
2922        for name in f.fs.list(&f.store.objects_dir).expect("list") {
2923            let name = name.to_string_lossy().into_owned();
2924            let version = VersionId::parse(&name)
2925                .unwrap_or_else(|| panic!("{name} left over at step {step}"));
2926            let rows = count(
2927                &f.store,
2928                &format!("SELECT count(*) FROM version WHERE hex(version) = upper('{version}')"),
2929            );
2930            assert_eq!(rows, 1, "{name} has no row at step {step}");
2931        }
2932    }
2933
2934    /// A second connection to the store's catalog, outside the store, on
2935    /// which a test makes a trigger that every connection then meets (a
2936    /// TEMP trigger would hold only for this one).
2937    pub(super) fn second_connection(f: &Fixture) -> Connection {
2938        let ctx = Context::Tenant { tenant: TENANT };
2939        let tenant_key = envelope::unwrap(&f.master, &ctx, &f.wrapped).expect("unwraps");
2940        let catalog_key = envelope::catalog_key(&tenant_key).expect("catalog key");
2941        catalog::open(&f.dir.path().join("catalog.sqlite"), &catalog_key, "")
2942            .expect("second connection")
2943    }
2944
2945    fn die_before_commit(f: &Fixture) {
2946        let other = second_connection(f);
2947        let fs = f.fs.clone();
2948        *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2949            fs.fail_from(0);
2950            other
2951                .execute_batch(
2952                    "CREATE TRIGGER dead BEFORE INSERT ON audit
2953                     BEGIN SELECT RAISE(ABORT, 'the process has died'); END;",
2954                )
2955                .expect("trigger");
2956        }));
2957    }
2958
2959    pub(super) fn restart(f: &mut Fixture) {
2960        f.fs.crash();
2961        f.store
2962            .conn()
2963            .execute_batch("DROP TRIGGER IF EXISTS dead")
2964            .expect("drop trigger");
2965        f.reopen();
2966    }
2967
2968    #[test]
2969    fn a_create_cut_off_at_any_step_leaves_no_vcon_or_the_whole_vcon() {
2970        let (found, body) = vcon(UUID, "first");
2971        for step in 0..=WRITE_STEPS {
2972            let mut f = fixture();
2973            f.fs.fail_from(f.fs.log().len() + step);
2974            let result = f.store.create(&f.caller, &found, &body);
2975            assert_eq!(
2976                result.is_ok(),
2977                step == WRITE_STEPS,
2978                "step {step}: {result:?}"
2979            );
2980            restart(&mut f);
2981            match f.store.get(&f.caller, found.uuid) {
2982                Ok(stored) => assert_eq!(stored.body, body, "step {step}"),
2983                Err(StoreError::NotFound) => {
2984                    assert!(result.is_err(), "acknowledged, then lost, at step {step}")
2985                }
2986                other => panic!("half a vCon at step {step}: {other:?}"),
2987            }
2988            assert_whole(&f, step);
2989        }
2990    }
2991
2992    #[test]
2993    fn a_create_cut_off_between_its_file_and_its_commit_leaves_nothing() {
2994        let mut f = fixture();
2995        let (found, body) = vcon(UUID, "first");
2996        die_before_commit(&f);
2997        assert!(f.store.create(&f.caller, &found, &body).is_err());
2998        restart(&mut f);
2999        assert_eq!(
3000            f.store.get(&f.caller, found.uuid),
3001            Err(StoreError::NotFound)
3002        );
3003        assert_whole(&f, WRITE_STEPS);
3004    }
3005
3006    #[test]
3007    fn a_replace_cut_off_at_any_step_leaves_the_old_version_or_the_new() {
3008        let (found, old_body) = vcon(UUID, "first");
3009        let (_, new_body) = vcon(UUID, "second");
3010        for step in 0..=WRITE_STEPS {
3011            let mut f = fixture();
3012            let Ok(Created::New(old)) = f.store.create(&f.caller, &found, &old_body) else {
3013                panic!("stored")
3014            };
3015            f.fs.fail_from(f.fs.log().len() + step);
3016            let result = f.store.replace(&f.caller, old, &found, &new_body);
3017            assert_eq!(
3018                result.is_ok(),
3019                step == WRITE_STEPS,
3020                "step {step}: {result:?}"
3021            );
3022            restart(&mut f);
3023            let stored = f
3024                .store
3025                .get(&f.caller, found.uuid)
3026                .unwrap_or_else(|e| panic!("step {step}: {e:?}"));
3027            match result {
3028                Ok(new) => assert_eq!(
3029                    (stored.version, stored.body),
3030                    (new, new_body.clone()),
3031                    "step {step}"
3032                ),
3033                Err(_) => assert_eq!(
3034                    (stored.version, stored.body),
3035                    (old, old_body.clone()),
3036                    "step {step}"
3037                ),
3038            }
3039            assert_whole(&f, step);
3040        }
3041    }
3042
3043    #[test]
3044    fn a_replace_cut_off_between_its_file_and_its_commit_keeps_the_old_version() {
3045        let mut f = fixture();
3046        let (found, old) = stored(&f, "first");
3047        let (_, newer) = vcon(UUID, "second");
3048        die_before_commit(&f);
3049        assert!(f.store.replace(&f.caller, old, &found, &newer).is_err());
3050        restart(&mut f);
3051        assert_eq!(
3052            f.store.get(&f.caller, found.uuid).expect("reads").version,
3053            old
3054        );
3055        assert_eq!(hidden_versions(&f), 0);
3056        assert_whole(&f, WRITE_STEPS);
3057    }
3058
3059    #[test]
3060    fn a_delete_cut_off_before_its_commit_leaves_the_vcon_live() {
3061        let mut f = fixture();
3062        let (found, version) = stored(&f, "first");
3063        let other = second_connection(&f);
3064        other
3065            .execute_batch(
3066                "CREATE TRIGGER dead BEFORE INSERT ON audit
3067                 BEGIN SELECT RAISE(ABORT, 'the process has died'); END;",
3068            )
3069            .expect("trigger");
3070        assert!(
3071            f.store
3072                .delete(&f.caller, found.uuid, Retention::Years(7))
3073                .is_err()
3074        );
3075        drop(other);
3076        restart(&mut f);
3077        assert_eq!(
3078            f.store
3079                .get(&f.caller, found.uuid)
3080                .expect("still live")
3081                .version,
3082            version
3083        );
3084        assert_eq!(hidden_versions(&f), 0);
3085    }
3086
3087    /// The record of the last request, without its seq and time.
3088    fn last_record(f: &Fixture) -> (String, Value, Value, Value) {
3089        let log = audit_log(&f.store);
3090        let last = log.last().expect("a record");
3091        (
3092            last["action"].as_str().expect("an action").to_owned(),
3093            last["status"].clone(),
3094            last["version"].clone(),
3095            last["target"].clone(),
3096        )
3097    }
3098
3099    #[test]
3100    fn a_reveal_reads_what_a_read_does_and_is_recorded_under_its_part() {
3101        let f = fixture();
3102        let (found, body) = vcon(UUID, "first");
3103        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
3104            panic!("a new vCon")
3105        };
3106        let read = f.store.get(&f.caller, found.uuid).expect("reads");
3107        for part in Part::ALL {
3108            let revealed = f.store.reveal(&f.caller, found.uuid, part).expect("reads");
3109            assert_eq!(revealed, read, "{part:?}");
3110            assert_eq!(
3111                last_record(&f),
3112                (
3113                    format!("reveal_{}", part.name()),
3114                    200.into(),
3115                    version.to_string().into(),
3116                    UUID.into()
3117                ),
3118                "{part:?}"
3119            );
3120        }
3121    }
3122
3123    #[test]
3124    fn a_reveal_of_a_uuid_never_stored_is_not_found_and_recorded_as_the_reveal() {
3125        let f = fixture();
3126        let (found, _) = vcon(UUID, "first");
3127        assert_eq!(
3128            f.store.reveal(&f.caller, found.uuid, Part::Dialog),
3129            Err(StoreError::NotFound),
3130            "the answer"
3131        );
3132        assert_eq!(
3133            last_record(&f),
3134            (
3135                "reveal_dialog".to_owned(),
3136                404.into(),
3137                Value::Null,
3138                UUID.into()
3139            ),
3140            "the record"
3141        );
3142    }
3143
3144    #[test]
3145    fn a_reveal_of_a_deleted_vcon_is_gone_and_recorded_as_the_reveal() {
3146        let f = fixture();
3147        let (found, body) = vcon(UUID, "first");
3148        f.store.create(&f.caller, &found, &body).expect("stored");
3149        f.store
3150            .delete(&f.caller, found.uuid, Retention::Years(7))
3151            .expect("deleted");
3152        assert_eq!(
3153            f.store.reveal(&f.caller, found.uuid, Part::Parties),
3154            Err(StoreError::Gone),
3155            "the answer"
3156        );
3157        assert_eq!(
3158            last_record(&f),
3159            (
3160                "reveal_parties".to_owned(),
3161                410.into(),
3162                Value::Null,
3163                UUID.into()
3164            ),
3165            "the record"
3166        );
3167    }
3168
3169    #[test]
3170    fn a_reveal_of_a_version_whose_file_is_missing_is_damage_recorded_as_the_reveal() {
3171        let f = fixture();
3172        let (found, body) = vcon(UUID, "first");
3173        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
3174            panic!("a new vCon")
3175        };
3176        f.fs.remove(&f.store.objects_dir.join(version.to_string()))
3177            .expect("remove");
3178        assert_eq!(
3179            f.store.reveal(&f.caller, found.uuid, Part::All),
3180            Err(StoreError::Damaged),
3181            "the answer"
3182        );
3183        assert_eq!(
3184            last_record(&f),
3185            (
3186                "reveal_all".to_owned(),
3187                500.into(),
3188                version.to_string().into(),
3189                UUID.into()
3190            ),
3191            "the record"
3192        );
3193    }
3194
3195    /// The marker changes one record's action: the reads before and after
3196    /// a reveal are recorded as the reads they are.
3197    #[test]
3198    fn a_read_before_and_after_a_reveal_is_still_recorded_as_a_read() {
3199        let f = fixture();
3200        let (found, body) = vcon(UUID, "first");
3201        f.store.create(&f.caller, &found, &body).expect("stored");
3202        f.store.get(&f.caller, found.uuid).expect("reads");
3203        f.store
3204            .reveal(&f.caller, found.uuid, Part::Subject)
3205            .expect("reads");
3206        f.store.get(&f.caller, found.uuid).expect("reads");
3207        let actions: Vec<String> = audit_log(&f.store)
3208            .iter()
3209            .map(|r| r["action"].as_str().expect("an action").to_owned())
3210            .collect();
3211        assert_eq!(
3212            actions,
3213            ["create", "read", "reveal_subject", "read"],
3214            "the record"
3215        );
3216    }
3217}