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