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;
36pub(crate) mod 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            .log_internal_errors(false)
2023            .finish();
2024        let read =
2025            tracing::subscriber::with_default(subscriber, || f.store.get(&f.caller, found.uuid));
2026        assert_eq!(read, Err(StoreError::Io), "the read fails as Io");
2027        let log = String::from_utf8(capture.0.lock().expect("lock").clone()).expect("UTF-8");
2028        assert!(log.contains("WARN"), "a warning: {log}");
2029        assert!(
2030            log.contains("kind=permission denied"),
2031            "the kind is logged: {log}"
2032        );
2033        // Each value is named by what it is, so a failure prints no value.
2034        let version = version.to_string();
2035        let tenant = TENANT.to_string();
2036        for (what, value) in [
2037            ("the error's text", LEAKY),
2038            ("the object's key", "tenants/1111"),
2039            ("the access key id", "AKIAIOSFODNN7EXAMPLE"),
2040            ("the secret key", "wJalrXUtnFEMI"),
2041            ("the uuid", UUID),
2042            ("the version id", version.as_str()),
2043            ("the tenant id", tenant.as_str()),
2044        ] {
2045            assert!(!log.contains(value), "{what} is logged");
2046        }
2047
2048        // A file's failure carries the system's error number too.
2049        f.store.objects = Arc::new(ReadsFail {
2050            inner: f.store.objects.clone(),
2051            fail: || ObjectError::Io(std::io::Error::from_raw_os_error(libc::EIO)),
2052        });
2053        let capture = Capture::default();
2054        let subscriber = tracing_subscriber::fmt()
2055            .with_writer(capture.clone())
2056            .with_ansi(false)
2057            .log_internal_errors(false)
2058            .finish();
2059        tracing::subscriber::with_default(subscriber, || f.store.get(&f.caller, found.uuid))
2060            .expect_err("fails");
2061        let log = String::from_utf8(capture.0.lock().expect("lock").clone()).expect("UTF-8");
2062        assert!(
2063            log.contains(&format!("os_error={}", libc::EIO)),
2064            "the error number is logged: {log}"
2065        );
2066    }
2067
2068    /// A data key that does not open is damage; a key page the system will
2069    /// not lock is a failure of the server, not of the stored data.
2070    #[test]
2071    fn only_a_wrapped_key_that_does_not_open_is_damage() {
2072        assert_eq!(
2073            key_failed(envelope::KeyError::Damaged),
2074            StoreError::Damaged,
2075            "a key that does not open"
2076        );
2077        assert_eq!(
2078            key_failed(envelope::KeyError::Memory(
2079                std::io::Error::from_raw_os_error(libc::ENOMEM)
2080            )),
2081            StoreError::Io,
2082            "a key page that cannot be locked"
2083        );
2084    }
2085
2086    #[test]
2087    fn a_read_racing_a_delete_never_returns_the_body() {
2088        let f = Arc::new(fixture());
2089        let (found, body) = vcon(UUID, "first");
2090        f.store.create(&f.caller, &found, &body).expect("stored");
2091        let deleter = f.clone();
2092        *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2093            deleter
2094                .store
2095                .conn()
2096                .execute(
2097                    "UPDATE vcon SET current = NULL, deleted_at = 1 WHERE uuid = ?1",
2098                    [found.uuid.as_bytes()],
2099                )
2100                .expect("delete");
2101        }));
2102        assert_eq!(f.store.get(&f.caller, found.uuid), Err(StoreError::Gone));
2103        assert_eq!(get_entry_status(&f), 410);
2104    }
2105
2106    #[test]
2107    fn a_read_racing_a_new_version_starts_again_and_returns_the_new_one() {
2108        let f = Arc::new(fixture());
2109        let (found, body) = vcon(UUID, "first");
2110        f.store.create(&f.caller, &found, &body).expect("stored");
2111        let (_, newer) = vcon(UUID, "newer");
2112        let (version, wrapped) = f.store.write_version(found.uuid, &newer).expect("written");
2113        let writer = f.clone();
2114        *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2115            let conn = writer.store.conn();
2116            conn.execute(
2117                "INSERT INTO version
2118                     (version, uuid, form, gzip, size, stored_at, tenant_key_id, wrapped_key)
2119                 VALUES (?1, ?2, 'unsigned', 0, 0, 0, ?3, ?4)",
2120                params![
2121                    version.0,
2122                    found.uuid.as_bytes(),
2123                    writer.store.tenant_key.id().bytes(),
2124                    wrapped
2125                ],
2126            )
2127            .expect("new version");
2128            conn.execute(
2129                "UPDATE vcon SET current = ?1 WHERE uuid = ?2",
2130                params![version.0, found.uuid.as_bytes()],
2131            )
2132            .expect("made current");
2133        }));
2134        let stored = f.store.get(&f.caller, found.uuid).expect("reads");
2135        assert_eq!((stored.version, stored.body), (version, newer));
2136        let reads = audit_log(&f.store)
2137            .iter()
2138            .filter(|r| r["action"] == "read")
2139            .count();
2140        assert_eq!(reads, 1, "one record for the one request");
2141    }
2142
2143    #[test]
2144    fn every_form_and_the_gzip_flag_read_back_as_stored() {
2145        use base64::Engine;
2146        use std::io::Write;
2147        let f = fixture();
2148        let uuids = [
2149            "01a07da8-c2bb-83e5-b9a2-279e0d16bc01",
2150            "01a07da8-c2bb-83e5-b9a2-279e0d16bc02",
2151            "01a07da8-c2bb-83e5-b9a2-279e0d16bc03",
2152        ];
2153        let (_, unsigned) = vcon(uuids[0], "plain");
2154        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
2155        gz.write_all(&unsigned).expect("gzip");
2156        let gzipped = gz.finish().expect("gzip");
2157        let (_, inner) = vcon(uuids[1], "signed");
2158        let signed = format!(
2159            r#"{{"payload": "{}", "signatures": [{{"header": {{}}}}]}}"#,
2160            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(inner)
2161        )
2162        .into_bytes();
2163        let encrypted = format!(
2164            r#"{{"unprotected": {{"uuid": "{}"}}, "ciphertext": "x", "recipients": []}}"#,
2165            uuids[2]
2166        )
2167        .into_bytes();
2168        let cases = [
2169            (gzipped, vcon::Form::Unsigned, true),
2170            (signed, vcon::Form::Signed, false),
2171            (encrypted, vcon::Form::Encrypted, false),
2172        ];
2173        for (body, form, gzip) in cases {
2174            let found = inspect(&body, None, &Limits::new(1 << 20), &BTreeSet::new())
2175                .expect("a valid vCon");
2176            assert_eq!((found.form, found.gzip), (form, gzip));
2177            f.store.create(&f.caller, &found, &body).expect("stored");
2178            let stored = f.store.get(&f.caller, found.uuid).expect("reads");
2179            assert_eq!((stored.form, stored.gzip, stored.body), (form, gzip, body));
2180        }
2181    }
2182
2183    /// Stores `subject` under UUID and returns its version.
2184    fn stored(f: &Fixture, subject: &str) -> (Inspection, VersionId) {
2185        let (found, body) = vcon(UUID, subject);
2186        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
2187            panic!("a new vCon")
2188        };
2189        (found, version)
2190    }
2191
2192    #[test]
2193    fn a_replace_makes_a_new_current_version_and_hides_the_old_one() {
2194        let f = fixture();
2195        let (found, old) = stored(&f, "first");
2196        let (_, newer) = vcon(UUID, "second");
2197        let version = f
2198            .store
2199            .replace(&f.caller, old, &found, &newer)
2200            .expect("replaced");
2201        assert_ne!(version, old);
2202        let stored = f.store.get(&f.caller, found.uuid).expect("reads");
2203        assert_eq!((stored.version, stored.body), (version, newer));
2204        let hidden: Option<i64> = f
2205            .store
2206            .conn()
2207            .query_row(
2208                "SELECT hidden_at FROM version WHERE version = ?1",
2209                [old.0],
2210                |r| r.get(0),
2211            )
2212            .expect("the old row is kept");
2213        assert_eq!(
2214            hidden,
2215            Some(crate::clock::nanos(datetime!(2026-10-23 12:00 UTC))),
2216            "the old version is hidden at the replace's time"
2217        );
2218        assert!(
2219            f.fs.read(&f.store.objects_dir.join(old.to_string()))
2220                .is_ok(),
2221            "its file is kept"
2222        );
2223        let record = audit_log(&f.store)
2224            .into_iter()
2225            .find(|r| r["action"] == "replace")
2226            .expect("a replace record");
2227        assert_eq!(
2228            (record["status"].clone(), record["version"].clone()),
2229            (200.into(), version.to_string().into())
2230        );
2231    }
2232
2233    #[test]
2234    fn a_replace_of_a_missing_or_gone_uuid_is_refused() {
2235        let f = fixture();
2236        let (found, body) = vcon(UUID, "first");
2237        let any = VersionId([7; 16]);
2238        assert_eq!(
2239            f.store.replace(&f.caller, any, &found, &body),
2240            Err(StoreError::NotFound)
2241        );
2242        assert_eq!(get_entry_status(&f), 404);
2243        let (found, old) = stored(&f, "first");
2244        f.store
2245            .conn()
2246            .execute(
2247                "UPDATE vcon SET current = NULL, deleted_at = 1 WHERE uuid = ?1",
2248                [found.uuid.as_bytes()],
2249            )
2250            .expect("delete");
2251        assert_eq!(
2252            f.store.replace(&f.caller, old, &found, &body),
2253            Err(StoreError::Gone)
2254        );
2255        assert_eq!(get_entry_status(&f), 410);
2256    }
2257
2258    #[test]
2259    fn a_stale_if_match_is_refused_and_writes_nothing() {
2260        let f = fixture();
2261        let (found, _) = stored(&f, "first");
2262        let ops = f.fs.log().len();
2263        let (_, newer) = vcon(UUID, "second");
2264        assert_eq!(
2265            f.store
2266                .replace(&f.caller, VersionId([7; 16]), &found, &newer),
2267            Err(StoreError::PreconditionFailed)
2268        );
2269        assert_eq!(f.fs.log().len(), ops, "no file written");
2270        assert_eq!(wraps(&f.store), 1, "nothing wrapped");
2271        assert_eq!(get_entry_status(&f), 412);
2272    }
2273
2274    #[test]
2275    fn a_signed_or_encrypted_current_version_is_immutable() {
2276        use base64::Engine;
2277        let f = fixture();
2278        let (found, old) = stored(&f, "first");
2279        let (_, inner) = vcon(UUID, "signed");
2280        let signed = format!(
2281            r#"{{"payload": "{}", "signatures": [{{"header": {{}}}}]}}"#,
2282            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(inner)
2283        )
2284        .into_bytes();
2285        let signed_found =
2286            inspect(&signed, None, &Limits::new(1 << 20), &BTreeSet::new()).expect("a signed vCon");
2287        let version = f
2288            .store
2289            .replace(&f.caller, old, &signed_found, &signed)
2290            .expect("an unsigned vCon may be replaced by a signed one");
2291        let (_, newer) = vcon(UUID, "second");
2292        let ops = f.fs.log().len();
2293        assert_eq!(
2294            f.store.replace(&f.caller, version, &found, &newer),
2295            Err(StoreError::Immutable)
2296        );
2297        assert_eq!(f.fs.log().len(), ops, "no file written");
2298        assert_eq!(get_entry_status(&f), 409);
2299
2300        let g = fixture();
2301        let encrypted = format!(
2302            r#"{{"unprotected": {{"uuid": "{UUID}"}}, "ciphertext": "x", "recipients": []}}"#
2303        )
2304        .into_bytes();
2305        let enc_found = inspect(&encrypted, None, &Limits::new(1 << 20), &BTreeSet::new())
2306            .expect("an encrypted vCon");
2307        let Ok(Created::New(enc_version)) = g.store.create(&g.caller, &enc_found, &encrypted)
2308        else {
2309            panic!("stored")
2310        };
2311        assert_eq!(
2312            g.store.replace(&g.caller, enc_version, &found, &newer),
2313            Err(StoreError::Immutable)
2314        );
2315    }
2316
2317    #[test]
2318    fn a_replace_at_the_wrap_limit_is_refused() {
2319        let f = fixture();
2320        let (found, old) = stored(&f, "first");
2321        f.store
2322            .conn()
2323            .execute("UPDATE key_use SET wraps = ?1", [1_i64 << 32])
2324            .expect("at the limit");
2325        let (_, newer) = vcon(UUID, "second");
2326        assert_eq!(
2327            f.store.replace(&f.caller, old, &found, &newer),
2328            Err(StoreError::LimitReached)
2329        );
2330        assert_eq!(get_entry_status(&f), 503);
2331    }
2332
2333    #[test]
2334    fn of_two_replaces_racing_on_one_version_the_second_to_commit_loses() {
2335        let f = Arc::new(fixture());
2336        let (found, old) = stored(&f, "first");
2337        let winner = f.clone();
2338        let racer = found;
2339        *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2340            let (_, body) = vcon(UUID, "winner");
2341            winner
2342                .store
2343                .replace(&winner.caller, old, &racer, &body)
2344                .expect("wins");
2345        }));
2346        let (_, body) = vcon(UUID, "loser");
2347        assert_eq!(
2348            f.store.replace(&f.caller, old, &found, &body),
2349            Err(StoreError::PreconditionFailed)
2350        );
2351        assert_eq!(
2352            f.fs.list(&f.store.objects_dir).expect("list").len(),
2353            2,
2354            "first and winner only"
2355        );
2356        assert_eq!(wraps(&f.store), 3, "every wrap counted");
2357        assert_eq!(get_entry_status(&f), 412);
2358    }
2359
2360    #[test]
2361    fn two_threads_replacing_with_the_same_if_match_one_wins() {
2362        let f = Arc::new(fixture());
2363        let (_, old) = stored(&f, "first");
2364        let threads: Vec<_> = ["one", "two"]
2365            .into_iter()
2366            .map(|subject| {
2367                let f = f.clone();
2368                std::thread::spawn(move || {
2369                    let (found, body) = vcon(UUID, subject);
2370                    f.store.replace(&f.caller, old, &found, &body)
2371                })
2372            })
2373            .collect();
2374        let results: Vec<_> = threads
2375            .into_iter()
2376            .map(|t| t.join().expect("thread"))
2377            .collect();
2378        assert_eq!(
2379            results.iter().filter(|r| r.is_ok()).count(),
2380            1,
2381            "{results:?}"
2382        );
2383        assert!(
2384            results.contains(&Err(StoreError::PreconditionFailed)),
2385            "{results:?}"
2386        );
2387    }
2388
2389    #[test]
2390    fn a_replace_whose_audit_record_fails_changes_nothing() {
2391        let f = fixture();
2392        let (found, old) = stored(&f, "first");
2393        f.store
2394            .conn()
2395            .execute_batch(
2396                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
2397                 BEGIN SELECT RAISE(ABORT, 'audit fails'); END;",
2398            )
2399            .expect("trigger");
2400        let (_, newer) = vcon(UUID, "second");
2401        assert_eq!(
2402            f.store.replace(&f.caller, old, &found, &newer),
2403            Err(StoreError::AuditFailed)
2404        );
2405        f.store
2406            .conn()
2407            .execute_batch("DROP TRIGGER no_audit")
2408            .expect("drop trigger");
2409        assert_eq!(
2410            f.store.get(&f.caller, found.uuid).expect("reads").version,
2411            old
2412        );
2413        assert_eq!(
2414            f.fs.list(&f.store.objects_dir).expect("list").len(),
2415            1,
2416            "only the first file"
2417        );
2418    }
2419
2420    fn hidden_versions(f: &Fixture) -> i64 {
2421        count(
2422            &f.store,
2423            "SELECT count(*) FROM version WHERE hidden_at IS NOT NULL",
2424        )
2425    }
2426
2427    #[test]
2428    fn a_deleted_uuid_answers_gone_and_keeps_its_versions_hidden() {
2429        let f = fixture();
2430        let (found, old) = stored(&f, "first");
2431        let (_, newer) = vcon(UUID, "second");
2432        f.clock.set(datetime!(2026-10-23 13:00 UTC));
2433        let current = f
2434            .store
2435            .replace(&f.caller, old, &found, &newer)
2436            .expect("replaced");
2437        f.clock.set(datetime!(2026-10-23 14:00 UTC));
2438        assert_eq!(
2439            f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2440            Ok(())
2441        );
2442        let record = audit_log(&f.store).pop().expect("a record");
2443        assert_eq!(
2444            (record["action"].clone(), record["status"].clone()),
2445            ("delete".into(), 204.into())
2446        );
2447        let hidden_at = |version: VersionId| -> i64 {
2448            f.store
2449                .conn()
2450                .query_row(
2451                    "SELECT hidden_at FROM version WHERE version = ?1",
2452                    [version.0],
2453                    |r| r.get(0),
2454                )
2455                .expect("hidden")
2456        };
2457        assert_eq!(
2458            hidden_at(old),
2459            nanos(datetime!(2026-10-23 13:00 UTC)),
2460            "hidden by the replace"
2461        );
2462        assert_eq!(
2463            hidden_at(current),
2464            nanos(datetime!(2026-10-23 14:00 UTC)),
2465            "hidden by the delete"
2466        );
2467        assert_eq!(f.store.get(&f.caller, found.uuid), Err(StoreError::Gone));
2468        let (_, body) = vcon(UUID, "third");
2469        assert_eq!(
2470            f.store.create(&f.caller, &found, &body),
2471            Err(StoreError::Gone)
2472        );
2473        assert_eq!(hidden_versions(&f), 2, "both versions hidden");
2474        assert_eq!(
2475            f.fs.list(&f.store.objects_dir).expect("list").len(),
2476            2,
2477            "files kept for legal reads"
2478        );
2479        let (current, deleted_at): (Option<Vec<u8>>, Option<i64>) = f
2480            .store
2481            .conn()
2482            .query_row(
2483                "SELECT current, deleted_at FROM vcon WHERE uuid = ?1",
2484                [found.uuid.as_bytes()],
2485                |r| Ok((r.get(0)?, r.get(1)?)),
2486            )
2487            .expect("row");
2488        assert_eq!(current, None);
2489        assert_eq!(deleted_at, Some(nanos(datetime!(2026-10-23 14:00 UTC))));
2490    }
2491
2492    #[test]
2493    fn deleting_a_deleted_or_purged_uuid_succeeds_again() {
2494        let f = fixture();
2495        let (found, _) = stored(&f, "first");
2496        f.store
2497            .delete(&f.caller, found.uuid, Retention::Years(7))
2498            .expect("deleted");
2499        assert_eq!(
2500            f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2501            Ok(())
2502        );
2503        assert_eq!(get_entry_status(&f), 204);
2504        let g = fixture();
2505        g.store
2506            .conn()
2507            .execute(
2508                "INSERT INTO tombstone (uuid, purged_at) VALUES (?1, 1)",
2509                [found.uuid.as_bytes()],
2510            )
2511            .expect("purged");
2512        assert_eq!(
2513            g.store.delete(&g.caller, found.uuid, Retention::Years(7)),
2514            Ok(())
2515        );
2516        assert_eq!(get_entry_status(&g), 204);
2517    }
2518
2519    #[test]
2520    fn deleting_a_uuid_never_stored_is_not_found() {
2521        let f = fixture();
2522        let (found, _) = vcon(UUID, "first");
2523        assert_eq!(
2524            f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2525            Err(StoreError::NotFound)
2526        );
2527        assert_eq!(get_entry_status(&f), 404);
2528    }
2529
2530    #[test]
2531    fn a_hold_does_not_stop_a_delete() {
2532        let f = fixture();
2533        let (found, _) = stored(&f, "first");
2534        f.store
2535            .conn()
2536            .execute(
2537                "UPDATE vcon SET hold = 1 WHERE uuid = ?1",
2538                [found.uuid.as_bytes()],
2539            )
2540            .expect("hold");
2541        assert_eq!(
2542            f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2543            Ok(())
2544        );
2545        assert_eq!(f.store.get(&f.caller, found.uuid), Err(StoreError::Gone));
2546    }
2547
2548    #[test]
2549    fn a_delete_whose_audit_record_fails_changes_nothing() {
2550        let f = fixture();
2551        let (found, version) = stored(&f, "first");
2552        f.store
2553            .conn()
2554            .execute_batch(
2555                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
2556                 BEGIN SELECT RAISE(ABORT, 'audit fails'); END;",
2557            )
2558            .expect("trigger");
2559        assert_eq!(
2560            f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2561            Err(StoreError::AuditFailed)
2562        );
2563        f.store
2564            .conn()
2565            .execute_batch("DROP TRIGGER no_audit")
2566            .expect("drop trigger");
2567        assert_eq!(
2568            f.store
2569                .get(&f.caller, found.uuid)
2570                .expect("still live")
2571                .version,
2572            version
2573        );
2574        assert_eq!(hidden_versions(&f), 0);
2575    }
2576
2577    #[test]
2578    fn only_the_optional_catalog_columns_may_be_empty() {
2579        let f = fixture();
2580        let conn = f.store.conn();
2581        let tables: [(&str, &[(&str, &str)]); 8] = [
2582            (
2583                "vcon",
2584                &[
2585                    ("uuid", "x'01'"),
2586                    ("current", "x'02'"),
2587                    ("deleted_at", "1"),
2588                    ("hold", "0"),
2589                ],
2590            ),
2591            (
2592                "version",
2593                &[
2594                    ("version", "x'02'"),
2595                    ("uuid", "x'01'"),
2596                    ("form", "'unsigned'"),
2597                    ("gzip", "0"),
2598                    ("size", "1"),
2599                    ("stored_at", "1"),
2600                    ("hidden_at", "1"),
2601                    ("tenant_key_id", "x'03'"),
2602                    ("wrapped_key", "x'04'"),
2603                    ("place_file", "x'05'"),
2604                    ("place_group", "0"),
2605                    ("place_row", "0"),
2606                ],
2607            ),
2608            (
2609                "parquet_file",
2610                &[
2611                    ("file_id", "x'05'"),
2612                    ("date", "'2026-10-23'"),
2613                    ("rows", "1"),
2614                    ("live_rows", "1"),
2615                    ("bytes", "1"),
2616                    ("created_at", "1"),
2617                    ("unnamed_at", "1"),
2618                ],
2619            ),
2620            ("purge_pending", &[("file_id", "x'05'")]),
2621            ("manifest", &[("seq", "1"), ("published_at", "1")]),
2622            ("tombstone", &[("uuid", "x'01'"), ("purged_at", "1")]),
2623            ("key_use", &[("tenant_key_id", "x'03'"), ("wraps", "1")]),
2624            (
2625                "audit",
2626                &[
2627                    ("at", "'2026-10-23T12:00Z'"),
2628                    ("actor", "'cli'"),
2629                    ("action", "'create'"),
2630                    ("target", "'x'"),
2631                    ("version", "'y'"),
2632                    ("status", "201"),
2633                    ("count", "1"),
2634                ],
2635            ),
2636        ];
2637        let may_be_empty: Vec<String> = tables
2638            .iter()
2639            .flat_map(|(table, row)| columns_taking_null(&conn, table, row))
2640            .collect();
2641        assert_eq!(
2642            may_be_empty,
2643            [
2644                "vcon.current",
2645                "vcon.deleted_at",
2646                "version.hidden_at",
2647                "version.place_file",
2648                "version.place_group",
2649                "version.place_row",
2650                "parquet_file.unnamed_at",
2651                // A rowid: NULL takes the next number, never a used one.
2652                "manifest.seq",
2653                "manifest.published_at",
2654                "audit.target",
2655                "audit.version",
2656                // A record that answers no request has no status.
2657                "audit.status"
2658            ]
2659        );
2660    }
2661
2662    #[test]
2663    fn a_new_stores_objects_directory_survives_a_crash() {
2664        let f = fixture();
2665        f.fs.crash();
2666        assert_eq!(
2667            f.fs.list(f.dir.path()).expect("list"),
2668            [std::ffi::OsString::from("objects")]
2669        );
2670    }
2671
2672    #[test]
2673    fn opening_removes_temporary_and_orphaned_files_and_nothing_else() {
2674        let mut f = fixture();
2675        let (found, version) = stored(&f, "first");
2676        let orphan = VersionId([0x0e; 16]);
2677        let objects = f.store.objects_dir.clone();
2678        for name in [
2679            format!("{orphan}"),
2680            format!("{orphan}.tmp"),
2681            format!("{version}.tmp"),
2682            "notes.txt".to_owned(),
2683        ] {
2684            f.fs.write_new(&objects.join(name), b"x").expect("write");
2685        }
2686        f.reopen();
2687        let names: Vec<String> =
2688            f.fs.list(&objects)
2689                .expect("list")
2690                .into_iter()
2691                .map(|n| n.to_string_lossy().into_owned())
2692                .collect();
2693        assert_eq!(names, [version.to_string(), "notes.txt".to_owned()]);
2694        assert_eq!(
2695            f.store
2696                .get(&f.caller, found.uuid)
2697                .expect("still reads")
2698                .version,
2699            version
2700        );
2701        let log = f.fs.log();
2702        let last_removal = log
2703            .iter()
2704            .rposition(|op| matches!(op, Op::Remove(_)))
2705            .expect("files were removed");
2706        assert!(
2707            log[last_removal..].contains(&Op::SyncDir(objects)),
2708            "the removals are synced"
2709        );
2710    }
2711
2712    /// A command beside a running server must not take the server's
2713    /// writes in progress for a crash's leftovers.
2714    #[test]
2715    fn opening_beside_a_server_removes_nothing() {
2716        let f = fixture();
2717        let (found, version) = stored(&f, "first");
2718        let orphan = VersionId([0x0e; 16]);
2719        let objects = f.store.objects_dir.clone();
2720        let mut written = vec![version.to_string()];
2721        for name in [
2722            format!("{orphan}"),
2723            format!("{orphan}.tmp"),
2724            format!("{version}.tmp"),
2725        ] {
2726            f.fs.write_new(&objects.join(&name), b"x").expect("write");
2727            written.push(name);
2728        }
2729        written.sort();
2730        let ops = f.fs.log().len();
2731        let beside = f.open_beside().expect("opens beside");
2732        let mut names: Vec<String> =
2733            f.fs.list(&objects)
2734                .expect("list")
2735                .into_iter()
2736                .map(|n| n.to_string_lossy().into_owned())
2737                .collect();
2738        names.sort();
2739        assert_eq!(names, written);
2740        assert!(
2741            !f.fs.log()[ops..]
2742                .iter()
2743                .any(|op| matches!(op, Op::Remove(_))),
2744            "nothing removed"
2745        );
2746        assert_eq!(
2747            beside.get(&f.caller, found.uuid).expect("reads").version,
2748            version
2749        );
2750    }
2751
2752    #[test]
2753    fn opening_checkpoints_the_wal_with_truncation() {
2754        let mut f = fixture();
2755        stored(&f, "first");
2756        let wal = f.dir.path().join("catalog.sqlite-wal");
2757        assert!(
2758            std::fs::metadata(&wal).expect("a WAL").len() > 0,
2759            "the WAL holds the write"
2760        );
2761        f.reopen();
2762        assert_eq!(std::fs::metadata(&wal).expect("a WAL").len(), 0);
2763    }
2764
2765    #[test]
2766    fn check_reports_a_version_whose_file_is_missing() {
2767        let f = fixture();
2768        let (_, version) = stored(&f, "first");
2769        assert_eq!(f.store.check(), Ok(vec![]));
2770        f.fs.remove(&f.store.objects_dir.join(version.to_string()))
2771            .expect("remove");
2772        assert_eq!(f.store.check(), Ok(vec![version]));
2773    }
2774
2775    #[test]
2776    fn opening_refuses_while_a_reader_stops_the_wal_from_being_truncated() {
2777        let f = fixture();
2778        stored(&f, "first");
2779        let ctx = Context::Tenant { tenant: TENANT };
2780        let tenant_key = envelope::unwrap(&f.master, &ctx, &f.wrapped).expect("unwraps");
2781        let catalog_key = envelope::catalog_key(&tenant_key).expect("catalog key");
2782        let mut reader = catalog::open(&f.dir.path().join("catalog.sqlite"), &catalog_key, "")
2783            .expect("a second connection");
2784        let read = reader.transaction().expect("read transaction");
2785        let _: i64 = read
2786            .query_row("SELECT count(*) FROM vcon", [], |r| r.get(0))
2787            .expect("a read holds a snapshot");
2788        assert!(matches!(f.open(), Err(StoreError::Io)));
2789        drop(read);
2790        assert!(f.open().is_ok(), "opens once the reader is done");
2791    }
2792
2793    /// The filesystem changes a create or replace makes when nothing
2794    /// fails: write, sync, rename, sync the directory.
2795    const WRITE_STEPS: usize = 4;
2796
2797    /// After a restart, no row lacks its file and every file has a row.
2798    fn assert_whole(f: &Fixture, step: usize) {
2799        assert_eq!(
2800            f.store.check(),
2801            Ok(vec![]),
2802            "a row without its file at step {step}"
2803        );
2804        for name in f.fs.list(&f.store.objects_dir).expect("list") {
2805            let name = name.to_string_lossy().into_owned();
2806            let version = VersionId::parse(&name)
2807                .unwrap_or_else(|| panic!("{name} left over at step {step}"));
2808            let rows = count(
2809                &f.store,
2810                &format!("SELECT count(*) FROM version WHERE hex(version) = upper('{version}')"),
2811            );
2812            assert_eq!(rows, 1, "{name} has no row at step {step}");
2813        }
2814    }
2815
2816    /// A second connection to the store's catalog, outside the store, on
2817    /// which a test makes a trigger that every connection then meets (a
2818    /// TEMP trigger would hold only for this one).
2819    pub(super) fn second_connection(f: &Fixture) -> Connection {
2820        let ctx = Context::Tenant { tenant: TENANT };
2821        let tenant_key = envelope::unwrap(&f.master, &ctx, &f.wrapped).expect("unwraps");
2822        let catalog_key = envelope::catalog_key(&tenant_key).expect("catalog key");
2823        catalog::open(&f.dir.path().join("catalog.sqlite"), &catalog_key, "")
2824            .expect("second connection")
2825    }
2826
2827    fn die_before_commit(f: &Fixture) {
2828        let other = second_connection(f);
2829        let fs = f.fs.clone();
2830        *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2831            fs.fail_from(0);
2832            other
2833                .execute_batch(
2834                    "CREATE TRIGGER dead BEFORE INSERT ON audit
2835                     BEGIN SELECT RAISE(ABORT, 'the process has died'); END;",
2836                )
2837                .expect("trigger");
2838        }));
2839    }
2840
2841    pub(super) fn restart(f: &mut Fixture) {
2842        f.fs.crash();
2843        f.store
2844            .conn()
2845            .execute_batch("DROP TRIGGER IF EXISTS dead")
2846            .expect("drop trigger");
2847        f.reopen();
2848    }
2849
2850    #[test]
2851    fn a_create_cut_off_at_any_step_leaves_no_vcon_or_the_whole_vcon() {
2852        let (found, body) = vcon(UUID, "first");
2853        for step in 0..=WRITE_STEPS {
2854            let mut f = fixture();
2855            f.fs.fail_from(f.fs.log().len() + step);
2856            let result = f.store.create(&f.caller, &found, &body);
2857            assert_eq!(
2858                result.is_ok(),
2859                step == WRITE_STEPS,
2860                "step {step}: {result:?}"
2861            );
2862            restart(&mut f);
2863            match f.store.get(&f.caller, found.uuid) {
2864                Ok(stored) => assert_eq!(stored.body, body, "step {step}"),
2865                Err(StoreError::NotFound) => {
2866                    assert!(result.is_err(), "acknowledged, then lost, at step {step}")
2867                }
2868                other => panic!("half a vCon at step {step}: {other:?}"),
2869            }
2870            assert_whole(&f, step);
2871        }
2872    }
2873
2874    #[test]
2875    fn a_create_cut_off_between_its_file_and_its_commit_leaves_nothing() {
2876        let mut f = fixture();
2877        let (found, body) = vcon(UUID, "first");
2878        die_before_commit(&f);
2879        assert!(f.store.create(&f.caller, &found, &body).is_err());
2880        restart(&mut f);
2881        assert_eq!(
2882            f.store.get(&f.caller, found.uuid),
2883            Err(StoreError::NotFound)
2884        );
2885        assert_whole(&f, WRITE_STEPS);
2886    }
2887
2888    #[test]
2889    fn a_replace_cut_off_at_any_step_leaves_the_old_version_or_the_new() {
2890        let (found, old_body) = vcon(UUID, "first");
2891        let (_, new_body) = vcon(UUID, "second");
2892        for step in 0..=WRITE_STEPS {
2893            let mut f = fixture();
2894            let Ok(Created::New(old)) = f.store.create(&f.caller, &found, &old_body) else {
2895                panic!("stored")
2896            };
2897            f.fs.fail_from(f.fs.log().len() + step);
2898            let result = f.store.replace(&f.caller, old, &found, &new_body);
2899            assert_eq!(
2900                result.is_ok(),
2901                step == WRITE_STEPS,
2902                "step {step}: {result:?}"
2903            );
2904            restart(&mut f);
2905            let stored = f
2906                .store
2907                .get(&f.caller, found.uuid)
2908                .unwrap_or_else(|e| panic!("step {step}: {e:?}"));
2909            match result {
2910                Ok(new) => assert_eq!(
2911                    (stored.version, stored.body),
2912                    (new, new_body.clone()),
2913                    "step {step}"
2914                ),
2915                Err(_) => assert_eq!(
2916                    (stored.version, stored.body),
2917                    (old, old_body.clone()),
2918                    "step {step}"
2919                ),
2920            }
2921            assert_whole(&f, step);
2922        }
2923    }
2924
2925    #[test]
2926    fn a_replace_cut_off_between_its_file_and_its_commit_keeps_the_old_version() {
2927        let mut f = fixture();
2928        let (found, old) = stored(&f, "first");
2929        let (_, newer) = vcon(UUID, "second");
2930        die_before_commit(&f);
2931        assert!(f.store.replace(&f.caller, old, &found, &newer).is_err());
2932        restart(&mut f);
2933        assert_eq!(
2934            f.store.get(&f.caller, found.uuid).expect("reads").version,
2935            old
2936        );
2937        assert_eq!(hidden_versions(&f), 0);
2938        assert_whole(&f, WRITE_STEPS);
2939    }
2940
2941    #[test]
2942    fn a_delete_cut_off_before_its_commit_leaves_the_vcon_live() {
2943        let mut f = fixture();
2944        let (found, version) = stored(&f, "first");
2945        let other = second_connection(&f);
2946        other
2947            .execute_batch(
2948                "CREATE TRIGGER dead BEFORE INSERT ON audit
2949                 BEGIN SELECT RAISE(ABORT, 'the process has died'); END;",
2950            )
2951            .expect("trigger");
2952        assert!(
2953            f.store
2954                .delete(&f.caller, found.uuid, Retention::Years(7))
2955                .is_err()
2956        );
2957        drop(other);
2958        restart(&mut f);
2959        assert_eq!(
2960            f.store
2961                .get(&f.caller, found.uuid)
2962                .expect("still live")
2963                .version,
2964            version
2965        );
2966        assert_eq!(hidden_versions(&f), 0);
2967    }
2968
2969    /// The record of the last request, without its seq and time.
2970    fn last_record(f: &Fixture) -> (String, Value, Value, Value) {
2971        let log = audit_log(&f.store);
2972        let last = log.last().expect("a record");
2973        (
2974            last["action"].as_str().expect("an action").to_owned(),
2975            last["status"].clone(),
2976            last["version"].clone(),
2977            last["target"].clone(),
2978        )
2979    }
2980
2981    #[test]
2982    fn a_reveal_reads_what_a_read_does_and_is_recorded_under_its_part() {
2983        let f = fixture();
2984        let (found, body) = vcon(UUID, "first");
2985        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
2986            panic!("a new vCon")
2987        };
2988        let read = f.store.get(&f.caller, found.uuid).expect("reads");
2989        for part in Part::ALL {
2990            let revealed = f.store.reveal(&f.caller, found.uuid, part).expect("reads");
2991            assert_eq!(revealed, read, "{part:?}");
2992            assert_eq!(
2993                last_record(&f),
2994                (
2995                    format!("reveal_{}", part.name()),
2996                    200.into(),
2997                    version.to_string().into(),
2998                    UUID.into()
2999                ),
3000                "{part:?}"
3001            );
3002        }
3003    }
3004
3005    #[test]
3006    fn a_reveal_of_a_uuid_never_stored_is_not_found_and_recorded_as_the_reveal() {
3007        let f = fixture();
3008        let (found, _) = vcon(UUID, "first");
3009        assert_eq!(
3010            f.store.reveal(&f.caller, found.uuid, Part::Dialog),
3011            Err(StoreError::NotFound),
3012            "the answer"
3013        );
3014        assert_eq!(
3015            last_record(&f),
3016            (
3017                "reveal_dialog".to_owned(),
3018                404.into(),
3019                Value::Null,
3020                UUID.into()
3021            ),
3022            "the record"
3023        );
3024    }
3025
3026    #[test]
3027    fn a_reveal_of_a_deleted_vcon_is_gone_and_recorded_as_the_reveal() {
3028        let f = fixture();
3029        let (found, body) = vcon(UUID, "first");
3030        f.store.create(&f.caller, &found, &body).expect("stored");
3031        f.store
3032            .delete(&f.caller, found.uuid, Retention::Years(7))
3033            .expect("deleted");
3034        assert_eq!(
3035            f.store.reveal(&f.caller, found.uuid, Part::Parties),
3036            Err(StoreError::Gone),
3037            "the answer"
3038        );
3039        assert_eq!(
3040            last_record(&f),
3041            (
3042                "reveal_parties".to_owned(),
3043                410.into(),
3044                Value::Null,
3045                UUID.into()
3046            ),
3047            "the record"
3048        );
3049    }
3050
3051    #[test]
3052    fn a_reveal_of_a_version_whose_file_is_missing_is_damage_recorded_as_the_reveal() {
3053        let f = fixture();
3054        let (found, body) = vcon(UUID, "first");
3055        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
3056            panic!("a new vCon")
3057        };
3058        f.fs.remove(&f.store.objects_dir.join(version.to_string()))
3059            .expect("remove");
3060        assert_eq!(
3061            f.store.reveal(&f.caller, found.uuid, Part::All),
3062            Err(StoreError::Damaged),
3063            "the answer"
3064        );
3065        assert_eq!(
3066            last_record(&f),
3067            (
3068                "reveal_all".to_owned(),
3069                500.into(),
3070                version.to_string().into(),
3071                UUID.into()
3072            ),
3073            "the record"
3074        );
3075    }
3076
3077    /// The marker changes one record's action: the reads before and after
3078    /// a reveal are recorded as the reads they are.
3079    #[test]
3080    fn a_read_before_and_after_a_reveal_is_still_recorded_as_a_read() {
3081        let f = fixture();
3082        let (found, body) = vcon(UUID, "first");
3083        f.store.create(&f.caller, &found, &body).expect("stored");
3084        f.store.get(&f.caller, found.uuid).expect("reads");
3085        f.store
3086            .reveal(&f.caller, found.uuid, Part::Subject)
3087            .expect("reads");
3088        f.store.get(&f.caller, found.uuid).expect("reads");
3089        let actions: Vec<String> = audit_log(&f.store)
3090            .iter()
3091            .map(|r| r["action"].as_str().expect("an action").to_owned())
3092            .collect();
3093        assert_eq!(
3094            actions,
3095            ["create", "read", "reveal_subject", "read"],
3096            "the record"
3097        );
3098    }
3099}