Skip to main content

vcon_server/
store.rs

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