Skip to main content

vcon_server/
tenants.rs

1//! The registry of tenants: each one's id, name, retention period and
2//! wrapped tenant key, kept in `server.sqlite` under a catalog key derived
3//! from the master key, with the admin audit log beside them. Each tenant's
4//! vCons live in `tenants/<id>/`, in a Store of their own.
5
6use std::collections::HashMap;
7use std::path::{Path, PathBuf};
8use std::sync::{Arc, Mutex, MutexGuard};
9
10use time::OffsetDateTime;
11
12use crate::audit::{self, Action, Actor, Entry};
13#[cfg(test)]
14use crate::backend::local::LocalConn;
15use crate::backend::local::{LocalRegistry, LocalTenantSpace};
16use crate::backend::{
17    Catalogs, CommitError, Job, ObjectPlace, Registry, RegistryTx, TenantRow, TenantSpace,
18};
19use crate::clock::{Clock, from_nanos, nanos};
20use crate::envelope::{self, Key, WrapLimit};
21use crate::export::Metadata;
22use crate::fs::Fs;
23use crate::ids::TenantId;
24use crate::key_wrap::blob::{BackendKind, Blob};
25use crate::key_wrap::{FileWrap, KeyWrap};
26use crate::retention::Retention;
27use crate::store::pending::{self, Writers};
28use crate::store::{OpenError, Store};
29
30#[cfg(test)]
31mod backend_wrap_tests;
32mod backup;
33mod examine;
34pub(crate) mod key_life;
35#[cfg(test)]
36mod key_order_tests;
37#[cfg(test)]
38mod key_wrap_tests;
39mod keys;
40mod rekey;
41#[cfg(test)]
42mod rekey_root_tests;
43mod role_cap;
44mod sessions;
45#[cfg(test)]
46mod statement_tests;
47mod tenant_admin;
48mod users;
49
50pub use backup::{Backup, BackupError, NO_FILE_BACKUP};
51pub use examine::{KeyOrder, RegistryExamination, RotationBacklog, TenantExamination, Unexamined};
52pub use key_life::KeyLife;
53pub use keys::{KeyInfo, NewKey};
54pub use rekey::rekey_master;
55pub(crate) use rekey::{MasterStep, Moved, rekey_root};
56pub use sessions::{Proof, SessionError, SessionInfo, Started};
57pub use tenant_admin::MemberInfo;
58#[cfg(test)]
59pub(crate) use tests::{Fixture, fixture};
60pub use users::{Identity, MembershipInfo, UserError, UserInfo};
61
62/// A tenant's metadata column as read: NULL is `none`, and a level this
63/// build does not know is damage.
64fn stored_metadata(text: Option<String>) -> Result<Metadata, TenantError> {
65    match text {
66        None => Ok(Metadata::None),
67        Some(text) => Metadata::parse(&text).ok_or(TenantError::Io),
68    }
69}
70
71/// A tenant's retention column as read: None is the server default. A
72/// period that does not read back is damage, not the server default.
73fn stored_retention(text: Option<String>) -> Result<Option<Retention>, TenantError> {
74    text.map(|text| Retention::parse(&text).ok_or(TenantError::Io))
75        .transpose()
76}
77
78/// Why a Tenants call was refused or failed.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub enum TenantError {
81    /// No tenant has the id.
82    NotFound,
83    /// Another tenant has the name.
84    NameTaken,
85    /// The name breaks the naming rule (`good_name`).
86    BadName,
87    /// `Removal::Empty` was asked of a tenant that keeps versions.
88    HoldsVcons,
89    /// `Removal::Force` was asked of a tenant with a uuid under a legal
90    /// hold.
91    UnderHold,
92    /// The master key is at its wrap limit and must be rotated.
93    LimitReached,
94    /// The audit record could not be written, so nothing was done.
95    AuditFailed,
96    /// The tenant is being removed.
97    Closing,
98    /// Only the command line may do this: make an operator key.
99    CliOnly,
100    /// Scopes a key of its kind, or made by this caller, cannot hold.
101    BadScopes,
102    /// An expiry a new key cannot have: a number of days outside 1 to
103    /// 365, days and no expiry asked together, or no expiry where the
104    /// configuration refuses it (`keys.no_expiry`).
105    BadExpiry,
106    /// A change to a tenant's settings that the list of settings refuses.
107    BadSetting(crate::settings::SettingError),
108    /// server.sqlite was made under another master key.
109    WrongKey,
110    /// A copy of the registry into a local file was asked of a registry
111    /// kept in PostgreSQL, which is backed up with the database's own
112    /// tools (`pg_dump`).
113    NoFileBackup,
114    Io,
115}
116
117/// Why the registry did not open: the key it was made under, or the step
118/// that failed, on which file, with the error underneath as its source, so
119/// a failure says its cause.
120#[derive(Debug)]
121#[non_exhaustive]
122pub enum RegistryError {
123    /// server.sqlite was made under another master key.
124    WrongKey,
125    /// `step` failed on `path`.
126    Failed {
127        /// What was being done.
128        step: OpenStep,
129        /// The file or directory it was done to.
130        path: PathBuf,
131        /// The error underneath.
132        source: Box<dyn std::error::Error + Send + Sync>,
133    },
134    /// Start-up recovery failed.
135    Recovery(TenantError),
136    /// The registry in the catalog database was made under another master
137    /// key.
138    WrongDatabaseKey,
139    /// The registry in the catalog database could not be opened, and why.
140    Database(String),
141    /// The registry's root key is wrapped by a key backend, of the kind
142    /// its `key-wrap` blob names (None when the blob does not name one this
143    /// build knows), where the second names it is kept, and the master key
144    /// file was given to open it.
145    RootWrapped(Option<BackendKind>, &'static str),
146}
147
148/// What a start says when the catalog database names another master key.
149/// The file of a data directory that holds the registry root's `key-wrap`
150/// blob when a key backend wraps the root. With the master key file as the
151/// root there is none.
152pub(crate) const ROOT_FILE: &str = "registry.key";
153
154pub(crate) const WRONG_DATABASE_KEY: &str = "the master key is not the one the registry in the \
155                                             catalog database was made under";
156
157/// A step of opening the registry.
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159#[non_exhaustive]
160pub enum OpenStep {
161    /// Deriving server.sqlite's key from the master key.
162    CatalogKey,
163    /// Opening, or making, server.sqlite.
164    OpenCatalog,
165    /// Making the tenants/ directory.
166    MakeTenantsDir,
167    /// Syncing the data directory.
168    SyncDataDir,
169    /// Reading the registry root's `key-wrap` blob, registry.key.
170    RootKey,
171}
172
173impl RegistryError {
174    pub(crate) fn failed(
175        step: OpenStep,
176        path: PathBuf,
177        source: impl std::error::Error + Send + Sync + 'static,
178    ) -> RegistryError {
179        RegistryError::Failed {
180            step,
181            path,
182            source: Box::new(source),
183        }
184    }
185}
186
187impl std::fmt::Display for RegistryError {
188    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
189        match self {
190            RegistryError::WrongKey => {
191                f.write_str("the master key is not the one server.sqlite was made under")
192            }
193            RegistryError::Failed { step, path, .. } => {
194                let doing = match step {
195                    OpenStep::CatalogKey => "the catalog key for",
196                    OpenStep::OpenCatalog => "opening",
197                    OpenStep::MakeTenantsDir => "making",
198                    OpenStep::SyncDataDir => "syncing",
199                    OpenStep::RootKey => "reading",
200                };
201                write!(f, "{doing} {} failed", path.display())
202            }
203            RegistryError::Recovery(e) => write!(f, "start-up recovery failed: {e:?}"),
204            RegistryError::WrongDatabaseKey => f.write_str(WRONG_DATABASE_KEY),
205            RegistryError::Database(why) => write!(
206                f,
207                "the registry in the PostgreSQL database cannot be opened: {why}"
208            ),
209            RegistryError::RootWrapped(Some(kind), place) => write!(
210                f,
211                "the registry's root key is wrapped by the key backend {kind} ({place}), not \
212                 by the master key file"
213            ),
214            RegistryError::RootWrapped(None, place) => write!(
215                f,
216                "the registry's root key is wrapped by a key backend this build does not know \
217                 ({place}), not by the master key file"
218            ),
219        }
220    }
221}
222
223impl std::error::Error for RegistryError {
224    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
225        match self {
226            RegistryError::Failed { source, .. } => Some(source.as_ref()),
227            RegistryError::WrongKey
228            | RegistryError::Recovery(_)
229            | RegistryError::WrongDatabaseKey
230            | RegistryError::Database(_)
231            | RegistryError::RootWrapped(..) => None,
232        }
233    }
234}
235
236/// `error` and each error under it, as their Displays joined by ": ", for
237/// a report that gives the whole cause.
238pub(crate) fn with_causes(error: &dyn std::error::Error) -> String {
239    let mut text = error.to_string();
240    let mut under = error.source();
241    while let Some(cause) = under {
242        text.push_str(": ");
243        text.push_str(&cause.to_string());
244        under = cause.source();
245    }
246    text
247}
248
249/// The master key file's backend over `master`, for a registry whose root
250/// no key backend wraps. A registry whose root a key backend wraps is
251/// refused, naming the backend, before anything is opened or made.
252fn file_wrap(
253    dir: &Path,
254    master: Key,
255    catalogs: &Catalogs,
256) -> Result<Box<dyn KeyWrap>, RegistryError> {
257    refuse_wrapped_root(dir, catalogs)?;
258    Ok(Box::new(FileWrap::new(master)))
259}
260
261/// Refuses a registry whose root a key backend wraps, naming the backend
262/// and where the root is kept: the master key file does not open it.
263pub(crate) fn refuse_wrapped_root(dir: &Path, catalogs: &Catalogs) -> Result<(), RegistryError> {
264    match stored_root(dir, catalogs)? {
265        Some((blob, place)) => {
266            let kind = Blob::decode(&blob).ok().map(|b| b.reference().kind());
267            Err(RegistryError::RootWrapped(kind, place))
268        }
269        None => Ok(()),
270    }
271}
272
273/// The registry root's `key-wrap` blob and where it is kept, when a key
274/// backend wraps the root: registry.key in `dir` for a local registry,
275/// the row of `vcon.registry_key` in the database. A file that is there is
276/// a blob, even an empty one.
277fn stored_root(
278    dir: &Path,
279    catalogs: &Catalogs,
280) -> Result<Option<(Vec<u8>, &'static str)>, RegistryError> {
281    match catalogs {
282        Catalogs::Local => {
283            let path = dir.join(ROOT_FILE);
284            match std::fs::read(&path) {
285                Ok(blob) => Ok(Some((blob, ROOT_FILE))),
286                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
287                Err(e) => Err(RegistryError::failed(OpenStep::RootKey, path, e)),
288            }
289        }
290        #[cfg(feature = "postgres")]
291        Catalogs::Postgres(database) => Ok(crate::backend::postgres::wrapped_root(database)?
292            .map(|blob| (blob, "vcon.registry_key"))),
293    }
294}
295
296/// Every caller but the two that report it sees what TenantError can say.
297impl From<RegistryError> for TenantError {
298    fn from(e: RegistryError) -> TenantError {
299        match e {
300            RegistryError::WrongKey
301            | RegistryError::WrongDatabaseKey
302            | RegistryError::RootWrapped(..) => TenantError::WrongKey,
303            RegistryError::Failed { .. } | RegistryError::Database(_) => TenantError::Io,
304            RegistryError::Recovery(e) => e,
305        }
306    }
307}
308
309/// Why a tenant's Store could not be had: the registry refused, its
310/// catalog does not open under its key, or this process may not use one of
311/// its files. Only `check` and `serve`'s start-up check tell these apart;
312/// every other caller sees `TenantError` (`From` below).
313#[derive(Debug)]
314pub enum OpenFailure {
315    Refused(TenantError),
316    WrongKey,
317    Access {
318        path: PathBuf,
319        error: std::io::Error,
320    },
321}
322
323impl From<OpenFailure> for TenantError {
324    fn from(f: OpenFailure) -> TenantError {
325        match f {
326            OpenFailure::Refused(e) => e,
327            OpenFailure::WrongKey | OpenFailure::Access { .. } => TenantError::Io,
328        }
329    }
330}
331
332impl From<TenantError> for OpenFailure {
333    fn from(e: TenantError) -> OpenFailure {
334        OpenFailure::Refused(e)
335    }
336}
337
338impl From<OpenError> for OpenFailure {
339    fn from(e: OpenError) -> OpenFailure {
340        match e {
341            OpenError::WrongKey => OpenFailure::WrongKey,
342            OpenError::Access { path, error } => OpenFailure::Access { path, error },
343            OpenError::Store(_) => OpenFailure::Refused(TenantError::Io),
344        }
345    }
346}
347
348/// A tenant as `list` shows it.
349#[derive(Debug, Clone, PartialEq, Eq)]
350pub struct TenantInfo {
351    pub id: TenantId,
352    pub name: String,
353    /// The tenant's own retention period, if it set one.
354    pub retention: Option<Retention>,
355    /// Which clear columns its Parquet files carry.
356    pub metadata: Metadata,
357    pub created_at: OffsetDateTime,
358}
359
360impl TenantInfo {
361    /// The tenant as the admin API and the command line show it: id, name,
362    /// its own retention period, null for the server default, and its
363    /// metadata level.
364    pub fn to_json(&self) -> serde_json::Value {
365        serde_json::json!({
366            "id": self.id.to_string(),
367            "name": self.name,
368            "retention": self.retention.map(|r| r.to_string()),
369            "metadata": self.metadata.as_str(),
370        })
371    }
372
373    /// How long the tenant's vCons are kept: its own period, else the
374    /// server's `default`.
375    pub fn kept_for(&self, default: Retention) -> Retention {
376        kept_for(self.retention, default)
377    }
378}
379
380/// How long a tenant's vCons are kept: its own period `own`, else the
381/// server's `default`. The one rule the sweep, `check` and TenantInfo use.
382pub(crate) fn kept_for(own: Option<Retention>, default: Retention) -> Retention {
383    own.unwrap_or(default)
384}
385
386/// How far `remove` may go.
387#[derive(Debug, Clone, Copy, PartialEq, Eq)]
388pub enum Removal {
389    /// Only a tenant that keeps no version.
390    Empty,
391    /// Its vCons too, unless a uuid is under a legal hold.
392    Force,
393    /// Even held vCons; only from the command line, with the server stopped.
394    ForceOverridingHolds,
395}
396
397/// A tenant's Store as the registry holds it.
398enum Slot {
399    Open(Arc<Store>),
400    /// Being removed: no new handle is handed out.
401    Closing,
402}
403
404/// The registry of tenants.
405pub struct Tenants {
406    /// Where each tenant's catalog and objects are kept.
407    space: Box<dyn TenantSpace>,
408    /// What holds the root server.sqlite's key is derived from, and wraps
409    /// and unwraps each tenant key.
410    wrap: Box<dyn KeyWrap>,
411    registry: Box<dyn Registry>,
412    /// Each tenant's Store, once a request has opened it.
413    stores: Mutex<HashMap<TenantId, Slot>>,
414    /// The recovery its Stores are opened with, and who else that
415    /// recovery assumes may be writing; none for a process opened beside
416    /// a server, whose recovery would take the server's work under way
417    /// for a crash's leftovers.
418    recovery: Option<Writers>,
419    fs: Arc<dyn Fs>,
420    clock: Arc<dyn Clock>,
421    /// Whether a key may be made with no expiry (`keys.no_expiry`).
422    no_expiry: std::sync::atomic::AtomicBool,
423    /// How many tenant keys `key_order` unwraps at once
424    /// (`key_wrap.start_parallel`).
425    start_parallel: std::sync::atomic::AtomicUsize,
426    #[cfg(test)]
427    hooks: tests::Hooks,
428}
429
430impl Tenants {
431    /// Opens `<dir>/server.sqlite` under the master key's catalog key,
432    /// making it if new, and removes any tenant directory a crash left
433    /// without its row.
434    pub fn open(
435        dir: &Path,
436        master: Key,
437        fs: Arc<dyn Fs>,
438        clock: Arc<dyn Clock>,
439    ) -> Result<Tenants, RegistryError> {
440        Tenants::open_in(dir, master, fs, clock, ObjectPlace::Local, &Catalogs::Local)
441    }
442
443    /// Opens the registry as `open` does, with each tenant's objects kept
444    /// in `objects` and the registry and the tenants' catalogs kept in
445    /// `catalogs`: in `dir`, or in a database, where start-up recovery
446    /// removes the catalog rows and the bucket's objects of a tenant with
447    /// no row.
448    pub(crate) fn open_in(
449        dir: &Path,
450        master: Key,
451        fs: Arc<dyn Fs>,
452        clock: Arc<dyn Clock>,
453        objects: ObjectPlace,
454        catalogs: &Catalogs,
455    ) -> Result<Tenants, RegistryError> {
456        let registry = Tenants::opened(
457            dir,
458            file_wrap(dir, master, catalogs)?,
459            fs,
460            clock,
461            false,
462            objects,
463            catalogs,
464        )?;
465        // A process that opens the registry this way holds the data
466        // directory alone, or the database alone as a command alone does;
467        // a server on a database shares it with the other servers, whose
468        // work under way its recovery keeps.
469        registry
470            .recover(catalogs.writers())
471            .map_err(RegistryError::Recovery)?;
472        Ok(registry)
473    }
474
475    /// Opens the registry as a command running beside a server does:
476    /// without start-up recovery, here or in any Store it opens, which
477    /// would take the server's creates and writes in progress for a
478    /// crash's leftovers.
479    pub fn open_beside(
480        dir: &Path,
481        master: Key,
482        fs: Arc<dyn Fs>,
483        clock: Arc<dyn Clock>,
484    ) -> Result<Tenants, RegistryError> {
485        Tenants::opened(
486            dir,
487            file_wrap(dir, master, &Catalogs::Local)?,
488            fs,
489            clock,
490            true,
491            ObjectPlace::Local,
492            &Catalogs::Local,
493        )
494    }
495
496    /// Opens the registry as `open_beside` does, with each tenant's objects
497    /// kept in `objects` and the catalogs in `catalogs`.
498    pub(crate) fn open_beside_in(
499        dir: &Path,
500        master: Key,
501        fs: Arc<dyn Fs>,
502        clock: Arc<dyn Clock>,
503        objects: ObjectPlace,
504        catalogs: &Catalogs,
505    ) -> Result<Tenants, RegistryError> {
506        Tenants::opened(
507            dir,
508            file_wrap(dir, master, catalogs)?,
509            fs,
510            clock,
511            true,
512            objects,
513            catalogs,
514        )
515    }
516
517    /// The one opener: the registry and the tenants' space of `catalogs`,
518    /// the files of `dir` or the rows of a database, behind the same
519    /// `Tenants`.
520    fn opened(
521        dir: &Path,
522        wrap: Box<dyn KeyWrap>,
523        fs: Arc<dyn Fs>,
524        clock: Arc<dyn Clock>,
525        beside: bool,
526        objects: ObjectPlace,
527        catalogs: &Catalogs,
528    ) -> Result<Tenants, RegistryError> {
529        let catalog_key = envelope::catalog_key(wrap.root()).map_err(|e| {
530            RegistryError::failed(OpenStep::CatalogKey, dir.join("server.sqlite"), e)
531        })?;
532        let (registry, space): crate::backend::Backends = match catalogs {
533            Catalogs::Local => (
534                Box::new(LocalRegistry::open(dir, catalog_key)?),
535                Box::new(LocalTenantSpace::open(dir, fs.clone(), objects)?),
536            ),
537            #[cfg(feature = "postgres")]
538            Catalogs::Postgres(database) => {
539                crate::backend::postgres::open(database, &catalog_key, objects, fs.clone())?
540            }
541        };
542        let recovery = (!beside).then(|| catalogs.writers());
543        Ok(Tenants::with_backends(
544            registry, space, wrap, fs, clock, recovery,
545        ))
546    }
547
548    /// The registry over the given backends, opened as `open_beside` opens
549    /// one when `recovery` is none, else without its start-up recovery
550    /// yet, which assumes the writers `recovery` names.
551    pub(crate) fn with_backends(
552        registry: Box<dyn Registry>,
553        space: Box<dyn TenantSpace>,
554        wrap: Box<dyn KeyWrap>,
555        fs: Arc<dyn Fs>,
556        clock: Arc<dyn Clock>,
557        recovery: Option<Writers>,
558    ) -> Tenants {
559        Tenants {
560            space,
561            wrap,
562            registry,
563            stores: Mutex::new(HashMap::new()),
564            recovery,
565            fs,
566            clock,
567            no_expiry: std::sync::atomic::AtomicBool::new(true),
568            start_parallel: std::sync::atomic::AtomicUsize::new(8),
569            #[cfg(test)]
570            hooks: tests::Hooks::default(),
571        }
572    }
573
574    /// Runs `hook` once in the next create, between its space and the
575    /// transaction that adds its row: where another server's recovery
576    /// would find the create under way.
577    #[cfg(all(test, feature = "postgres", feature = "backend-tests"))]
578    pub(crate) fn between_create(&self, hook: tests::CreateHook) {
579        *self.hooks.between.lock().expect("hook") = Some(hook);
580    }
581
582    /// Takes or renews the lease of `job` for `ttl` ([`Registry::lead`]):
583    /// true when this process holds it now. The catalogs' clock decides,
584    /// never this process's.
585    pub(crate) fn lead(&self, job: Job, ttl: std::time::Duration) -> Result<bool, TenantError> {
586        self.registry.lead(job, ttl)
587    }
588
589    /// Gives up the lease of `job` when this process holds it
590    /// ([`Registry::step_down`]).
591    pub(crate) fn step_down(&self, job: Job) -> Result<(), TenantError> {
592        self.registry.step_down(job)
593    }
594
595    /// The recovery a running server repeats at each of its sweeps
596    /// (design 7.4): the registry's, then each tenant's Store's, all with
597    /// other writers possibly at work, since this process writes while it
598    /// runs and other servers may too. A tenant whose Store cannot be
599    /// opened or recovered, such as one being removed, is counted and left
600    /// for the next sweep; the answer is how many were.
601    pub(crate) fn recover_all(&self) -> Result<u64, TenantError> {
602        self.recover(Writers::Maybe)?;
603        let mut failed = 0;
604        for id in self.ids()? {
605            let recovered = self
606                .store(id)
607                .map_err(|_| ())
608                .and_then(|store| store.recover(Writers::Maybe).map_err(|_| ()));
609            if recovered.is_err() {
610                failed += 1;
611            }
612        }
613        Ok(failed)
614    }
615
616    /// The registry's clock in `tx` ([`RegistryTx::clock_now`]), `host`
617    /// being this process's.
618    fn registry_now(&self, tx: &mut dyn RegistryTx, host: i64) -> Result<i64, TenantError> {
619        let now = tx.clock_now(host)?;
620        #[cfg(test)]
621        let now = {
622            let mut steps = self.hooks.clock_steps.lock().expect("hook");
623            if steps.is_empty() {
624                now
625            } else {
626                now + steps.remove(0)
627            }
628        };
629        Ok(now)
630    }
631
632    /// The time in `tx` by the registry's clock: what the transaction
633    /// writes as a time another server judges, and judges such a time by.
634    /// On a database it is the database's clock, so the host clocks of
635    /// the servers on it do not matter; on a data directory, this
636    /// process's.
637    pub(crate) fn now_in(&self, tx: &mut dyn RegistryTx) -> Result<i64, TenantError> {
638        self.registry_now(tx, nanos(self.clock.now()))
639    }
640
641    /// Removes each tenant space with no row: a create cut off before its
642    /// commit. A name that is not a tenant id is not ours and is left
643    /// alone. A removal a crash undoes is made again at the next start, so
644    /// none is synced.
645    ///
646    /// With other writers possibly at work (`writers`), a space whose
647    /// create is under way (store/pending.rs) is kept, by the order that
648    /// keeps a write's object: a creating row no create can still be under
649    /// way for is deleted first, so that create's last transaction refuses
650    /// to add its row; the spaces are listed next, and the rows read after:
651    /// a create adds its creating row before it makes its space, so every
652    /// space listed has its creating row or its tenant's row in that read.
653    pub(crate) fn recover(&self, writers: Writers) -> Result<(), TenantError> {
654        let host = nanos(self.clock.now());
655        let now = {
656            let mut tx = self.registry.immediate()?;
657            let now = self.registry_now(tx.as_mut(), host)?;
658            for (id, started_at) in tx.creating()? {
659                if !pending::under_way(writers, started_at, now) {
660                    tx.drop_creating(id)?;
661                }
662            }
663            commit(tx)?;
664            now
665        };
666        let present = self.space.present()?;
667        let (tenants, creating) = {
668            let mut tx = self.registry.snapshot()?;
669            let tenants: std::collections::HashSet<TenantId> =
670                tx.tenants()?.into_iter().map(|row| row.id).collect();
671            let creating: std::collections::HashSet<TenantId> = tx
672                .creating()?
673                .into_iter()
674                .filter(|(_, started_at)| pending::under_way(writers, *started_at, now))
675                .map(|(id, _)| id)
676                .collect();
677            (tenants, creating)
678        };
679        for id in present {
680            if pending::leftover(tenants.contains(&id), false, creating.contains(&id)) {
681                self.space.remove(id)?;
682            }
683        }
684        Ok(())
685    }
686
687    /// Makes a tenant: a new tenant key wrapped by the key-wrapping backend, the
688    /// tenant's directory and catalog, and then its row. A create that
689    /// fails after making its directory removes it if it can; any directory
690    /// left without a row, by a crash or a failed removal, goes at the next
691    /// start.
692    pub fn create(
693        &self,
694        who: Actor,
695        name: &str,
696        retention: Option<Retention>,
697    ) -> Result<TenantId, TenantError> {
698        let id = TenantId::generate();
699        let entry = |status, target: Option<TenantId>| Entry {
700            actor: who,
701            action: Action::TenantCreate,
702            target: target.map(|t| t.to_string()),
703            version: None,
704            status,
705        };
706        let master_id = self.wrap.key_id();
707        {
708            let mut tx = self.registry.immediate()?;
709            let refused = if !good_name(name) {
710                Some((422, TenantError::BadName))
711            } else if tx.name_taken(name)? {
712                Some((409, TenantError::NameTaken))
713            } else if envelope::wrap_limit(tx.master_wraps(master_id)?) == WrapLimit::Refuse {
714                Some((503, TenantError::LimitReached))
715            } else {
716                None
717            };
718            if let Some((status, error)) = refused {
719                self.record(&mut tx, &entry(status, None))?;
720                commit(tx)?;
721                return Err(error);
722            }
723            // The wrap is counted before it is made, so every wrap is
724            // counted once whether this create wins or loses.
725            let now = self.now_in(tx.as_mut())?;
726            tx.add_master_wrap(master_id, now)?;
727            // Before the space is made: until the row, recovery on another
728            // server keeps the space of a create under way.
729            tx.add_creating(id, now)?;
730            commit(tx)?;
731        }
732
733        let tenant_key = Key::generate().map_err(|_| TenantError::Io)?;
734        let key_id = tenant_key.id();
735        let wrapped = self.wrap.wrap(id, &tenant_key).map_err(io)?;
736        // The directory and its catalog are made before the row, and made
737        // durable: the directory's entry in `tenants/` by syncing it. Any
738        // step that fails once the directory may exist removes it.
739        let unknown = std::cell::Cell::new(false);
740        let made = (|| {
741            self.space
742                .make(id, tenant_key, self.clock.clone())
743                .map_err(|_| TenantError::Io)?;
744            #[cfg(test)]
745            {
746                let hook = self.hooks.between.lock().expect("hook").take();
747                if let Some(hook) = hook {
748                    hook(self);
749                }
750            }
751
752            let mut tx = self.registry.immediate()?;
753            if !tx.drop_creating(id)? {
754                // Recovery took this create for a leftover, and its space
755                // is removed or going: no row may name it.
756                return Err(TenantError::Io);
757            }
758            if tx.name_taken(name)? {
759                // A refusal's record commits.
760                self.record(&mut tx, &entry(409, None))?;
761                commit(tx)?;
762                return Err(TenantError::NameTaken);
763            }
764            let now = self.now_in(tx.as_mut())?;
765            tx.insert_tenant(&TenantRow {
766                id,
767                name: name.to_owned(),
768                retention: retention.map(|r| r.to_string()),
769                metadata: None,
770                role_cap: None,
771                created_at: now,
772                tenant_key_id: key_id,
773                wrapped: wrapped.key.clone(),
774                pending: None,
775                key_since: now,
776                kek: wrapped.kek.clone(),
777                pending_kek: None,
778            })?;
779            self.record(&mut tx, &entry(201, Some(id)))?;
780            tx.commit().map_err(|e| {
781                unknown.set(e == CommitError::Unknown);
782                TenantError::Io
783            })?;
784            Ok(id)
785        })();
786        // After a commit whose outcome is unknown the directory stays: the
787        // row may be kept, and a row without its directory is a tenant
788        // that cannot open, while a directory without a row is removed at
789        // the next start.
790        if made.is_err() && !unknown.get() {
791            let _ = self.space.remove(id);
792            // The creating row goes after the space, so recovery never
793            // finds the space without it; a row left here is a leftover
794            // that recovery drops once its lease passes.
795            let begun = self.registry.immediate();
796            if let Ok(mut tx) = begun
797                && tx.drop_creating(id).is_ok()
798            {
799                let _ = tx.commit();
800            }
801        }
802        made
803    }
804
805    /// Every tenant, by name.
806    pub fn list(&self, who: Actor) -> Result<Vec<TenantInfo>, TenantError> {
807        let mut tx = self.registry.immediate()?;
808        let tenants = tx
809            .tenants()?
810            .into_iter()
811            .map(|row| {
812                Ok(TenantInfo {
813                    id: row.id,
814                    name: row.name,
815                    retention: stored_retention(row.retention)?,
816                    metadata: stored_metadata(row.metadata)?,
817                    created_at: from_nanos(row.created_at).ok_or(TenantError::Io)?,
818                })
819            })
820            .collect::<Result<Vec<_>, TenantError>>()?;
821        let entry = Entry {
822            actor: who,
823            action: Action::TenantList,
824            target: None,
825            version: None,
826            status: 200,
827        };
828        self.record(&mut tx, &entry)?;
829        commit(tx)?;
830        Ok(tenants)
831    }
832
833    /// Sets the tenant's retention period, or with None returns it to the
834    /// server default.
835    pub fn set_retention(
836        &self,
837        who: Actor,
838        id: TenantId,
839        retention: Option<Retention>,
840    ) -> Result<(), TenantError> {
841        let entry = |action, status| Entry {
842            actor: who,
843            action,
844            target: Some(id.to_string()),
845            version: None,
846            status,
847        };
848        let closing = matches!(self.stores().get(&id), Some(Slot::Closing));
849        {
850            let mut tx = self.registry.immediate()?;
851            let text = retention.map(|r| r.to_string());
852            let refused = if closing {
853                Some((503, TenantError::Closing))
854            } else if !tx.set_retention(id, text.as_deref())? {
855                Some((404, TenantError::NotFound))
856            } else {
857                None
858            };
859            let status = refused.map_or(200, |(status, _)| status);
860            self.record(&mut tx, &entry(Action::TenantRetention, status))?;
861            commit(tx)?;
862            if let Some((_, error)) = refused {
863                return Err(error);
864            }
865        }
866        self.copy_to_tenant(id, &entry(Action::Retention, 200))
867    }
868
869    /// Sets which clear columns the tenant's Parquet files carry.
870    pub fn set_metadata(
871        &self,
872        who: Actor,
873        id: TenantId,
874        level: Metadata,
875    ) -> Result<(), TenantError> {
876        let entry = |action, status| Entry {
877            actor: who,
878            action,
879            target: Some(id.to_string()),
880            version: None,
881            status,
882        };
883        let closing = matches!(self.stores().get(&id), Some(Slot::Closing));
884        {
885            let mut tx = self.registry.immediate()?;
886            let text = (level != Metadata::None).then(|| level.as_str());
887            let refused = if closing {
888                Some((503, TenantError::Closing))
889            } else if !tx.set_metadata(id, text)? {
890                Some((404, TenantError::NotFound))
891            } else {
892                None
893            };
894            let status = refused.map_or(200, |(status, _)| status);
895            self.record(&mut tx, &entry(Action::TenantMetadata, status))?;
896            commit(tx)?;
897            if let Some((_, error)) = refused {
898                return Err(error);
899            }
900        }
901        self.copy_to_tenant(id, &entry(Action::Metadata, 200))
902    }
903
904    /// The tenant's metadata level.
905    pub fn metadata(&self, id: TenantId) -> Result<Metadata, TenantError> {
906        let row = self.registry.snapshot()?.tenant(id)?;
907        stored_metadata(row.ok_or(TenantError::NotFound)?.metadata)
908    }
909
910    /// Writes the copy of an admin record that a tenant's own log keeps
911    /// too. The change it records has already committed with its admin
912    /// record, so a crash or failure here can lose only the copy; the
913    /// caller then answers that the audit failed, though the change
914    /// stands.
915    fn copy_to_tenant(&self, tenant: TenantId, entry: &Entry) -> Result<(), TenantError> {
916        let store = self.store(tenant).map_err(|_| TenantError::AuditFailed)?;
917        store.log(entry).map_err(|_| TenantError::AuditFailed)
918    }
919
920    /// Removes the tenant: its row and wrapped key, then its directory.
921    ///
922    /// The tenant is drained before it is looked at, so a write that lands
923    /// meanwhile counts: an `Empty` removal is then refused rather than
924    /// losing it. A refused or failed removal leaves the tenant served
925    /// again.
926    pub fn remove(&self, who: Actor, id: TenantId, removal: Removal) -> Result<(), TenantError> {
927        let entry = |status| Entry {
928            actor: who,
929            action: Action::TenantRemove,
930            target: Some(id.to_string()),
931            version: None,
932            status,
933        };
934        let drained = match self.drain(id) {
935            Ok(drained) => drained,
936            Err(error) => {
937                self.record_alone(&entry(503))?;
938                return Err(error);
939            }
940        };
941        let result = self.remove_drained(id, removal, drained, entry);
942        if result.is_err() {
943            self.stores().remove(&id);
944        }
945        result
946    }
947
948    fn remove_drained(
949        &self,
950        id: TenantId,
951        removal: Removal,
952        drained: Option<Store>,
953        entry: impl Fn(u16) -> Entry,
954    ) -> Result<(), TenantError> {
955        let store = match drained {
956            Some(store) => store,
957            None => match self.open_store(id).map_err(TenantError::from) {
958                Err(TenantError::NotFound) => {
959                    self.record_alone(&entry(404))?;
960                    return Err(TenantError::NotFound);
961                }
962                other => other?,
963            },
964        };
965        let counts = store.counts().map_err(io)?;
966        let refused = match removal {
967            Removal::Empty if counts.versions > 0 => Some(TenantError::HoldsVcons),
968            Removal::Force if counts.held > 0 => Some(TenantError::UnderHold),
969            _ => None,
970        };
971        if let Some(error) = refused {
972            self.record_alone(&entry(409))?;
973            return Err(error);
974        }
975        {
976            let mut tx = self.registry.immediate()?;
977            tx.delete_tenant(id, nanos(self.clock.now()))?;
978            // A membership, a setting and a session are in a tenant: none
979            // outlives its tenant.
980            tx.delete_memberships_in(id)?;
981            tx.delete_settings_in(id)?;
982            tx.delete_sessions_in(id)?;
983            self.record(&mut tx, &entry(204))?;
984            commit(tx)?;
985        }
986        // The removal stands with its commit. The Store is closed before
987        // its directory goes; a directory left here, by a crash or a
988        // failed removal, goes at the next start.
989        drop(store);
990        let _ = self.space.remove(id);
991        self.stores().remove(&id);
992        Ok(())
993    }
994
995    /// The tenant's Store, shared by every request to it.
996    pub fn store(&self, id: TenantId) -> Result<Arc<Store>, TenantError> {
997        self.store_or_why(id).map_err(TenantError::from)
998    }
999
1000    /// `store`, saying why a Store that did not open did not.
1001    pub fn store_or_why(&self, id: TenantId) -> Result<Arc<Store>, OpenFailure> {
1002        // The Store is opened under this lock, so it is opened once: a
1003        // second open's recovery could remove a write's temporary file.
1004        let mut stores = self.stores();
1005        match stores.get(&id) {
1006            Some(Slot::Open(store)) => return Ok(store.clone()),
1007            Some(Slot::Closing) => return Err(TenantError::Closing.into()),
1008            None => {}
1009        }
1010        let store = Arc::new(self.open_store(id)?);
1011        stores.insert(id, Slot::Open(store.clone()));
1012        Ok(store)
1013    }
1014
1015    /// Opens the tenant's Store under the key its row holds. Its callers
1016    /// make sure no other Store of the tenant is open: `store` holds the
1017    /// lock, and `remove` has drained the tenant.
1018    fn open_store(&self, id: TenantId) -> Result<Store, OpenFailure> {
1019        let row = self
1020            .registry
1021            .snapshot()?
1022            .tenant(id)?
1023            .ok_or(TenantError::NotFound)?;
1024        let tenant_key = self
1025            .wrap
1026            .unwrap(id, &row.wrapped, row.kek.as_ref())
1027            .map_err(io)?;
1028        #[cfg(test)]
1029        {
1030            let hook = self.hooks.opening.lock().expect("hook").take();
1031            if let Some(hook) = hook {
1032                hook();
1033            }
1034        }
1035        self.space
1036            .open(id, tenant_key, self.recovery, self.clock.clone())
1037            .map_err(OpenFailure::from)
1038    }
1039
1040    /// Marks the tenant closing, so no new handle is handed out, and waits
1041    /// until every handle given out before is dropped. Handles are plain
1042    /// `Arc`s, so the wait watches the count; requests are short and
1043    /// removal is rare. A tenant already closing is refused, so two
1044    /// removals never both hold its Store.
1045    ///
1046    /// Returns the tenant's Store if a request had opened it, now held
1047    /// only here.
1048    fn drain(&self, id: TenantId) -> Result<Option<Store>, TenantError> {
1049        let slot = {
1050            let mut stores = self.stores();
1051            if matches!(stores.get(&id), Some(Slot::Closing)) {
1052                return Err(TenantError::Closing);
1053            }
1054            stores.insert(id, Slot::Closing)
1055        };
1056        let Some(Slot::Open(mut store)) = slot else {
1057            return Ok(None);
1058        };
1059        loop {
1060            match Arc::try_unwrap(store) {
1061                Ok(store) => return Ok(Some(store)),
1062                Err(shared) => {
1063                    store = shared;
1064                    std::thread::sleep(std::time::Duration::from_millis(1));
1065                }
1066            }
1067        }
1068    }
1069
1070    fn stores(&self) -> MutexGuard<'_, HashMap<TenantId, Slot>> {
1071        self.stores
1072            .lock()
1073            .expect("no thread panicked holding the stores")
1074    }
1075
1076    /// Makes every audit insert on server.sqlite fail, for tests.
1077    #[cfg(test)]
1078    pub(crate) fn break_audit(&self) {
1079        self.conn()
1080            .execute_batch(
1081                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
1082                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
1083            )
1084            .expect("trigger");
1085    }
1086
1087    /// Runs `hook`, with the job's name, as each of the server's background
1088    /// jobs (the purge sweep, the pack run) begins its step for a tenant,
1089    /// for tests that hold a job inside that step.
1090    #[cfg(test)]
1091    pub(crate) fn when_a_job_steps_for_test(&self, hook: tests::JobHook) {
1092        *self.hooks.job_step.lock().expect("hook") = Some(hook);
1093    }
1094
1095    /// Where a background job begins its step for a tenant: runs the hook
1096    /// a test set with `when_a_job_steps_for_test`.
1097    #[cfg(test)]
1098    pub(crate) fn job_steps_for_test(&self, job: &'static str) {
1099        let hook = self.hooks.job_step.lock().expect("hook").clone();
1100        if let Some(hook) = hook {
1101            hook(job);
1102        }
1103    }
1104
1105    /// server.sqlite's connection, for tests that damage it.
1106    #[cfg(test)]
1107    pub(crate) fn conn_for_test(&self) -> MutexGuard<'_, LocalConn> {
1108        self.conn()
1109    }
1110
1111    /// The id of the tenant's current key, for tests.
1112    #[cfg(test)]
1113    pub(crate) fn tenant_key_id_for_test(&self, id: TenantId) -> Vec<u8> {
1114        let row = self.registry.snapshot().expect("reads").tenant(id);
1115        let row = row.expect("reads").expect("the tenant's row");
1116        row.tenant_key_id.bytes().to_vec()
1117    }
1118
1119    /// The admin log as `export` writes it, for tests.
1120    #[cfg(test)]
1121    pub(crate) fn admin_records(&self) -> Vec<serde_json::Value> {
1122        crate::audit::testing::exported(&self.conn(), None)
1123    }
1124
1125    /// Marks the tenant closing, as a removal does, for tests that need a
1126    /// closing tenant without removing it.
1127    #[cfg(test)]
1128    pub(crate) fn close(&self, id: TenantId) {
1129        self.drain(id).expect("not closing yet");
1130    }
1131
1132    /// A tenant's own retention period, None when it uses the server
1133    /// default, read afresh so a change counts from the next call. It is
1134    /// read for the server's own use, such as a delete's purge, so nothing
1135    /// is recorded.
1136    pub fn retention(&self, id: TenantId) -> Result<Option<Retention>, TenantError> {
1137        let row = self.registry.snapshot()?.tenant(id)?;
1138        stored_retention(row.ok_or(TenantError::NotFound)?.retention)
1139    }
1140
1141    /// Every tenant's id, read for the server's own use, such as the purge
1142    /// sweep, so nothing is recorded.
1143    pub fn ids(&self) -> Result<Vec<TenantId>, TenantError> {
1144        Ok(self
1145            .registry
1146            .snapshot()?
1147            .tenants()?
1148            .into_iter()
1149            .map(|row| row.id)
1150            .collect())
1151    }
1152
1153    /// Writes the admin log after `since` as JSON lines, oldest first.
1154    /// Not recorded: reading the log changes nothing.
1155    pub fn export_admin(
1156        &self,
1157        since: Option<i64>,
1158        out: &mut dyn std::io::Write,
1159    ) -> Result<(), audit::AuditError> {
1160        self.registry.export(since.unwrap_or(0), out)
1161    }
1162
1163    /// A page of the admin log as JSON lines, the lines `export_admin`
1164    /// writes for the same records. The read is recorded as audit_read in
1165    /// the admin log, in the same transaction, after the page is read.
1166    pub fn audit_page(
1167        &self,
1168        who: Actor,
1169        query: &audit::AuditQuery,
1170    ) -> Result<Vec<u8>, TenantError> {
1171        let mut tx = self.registry.immediate()?;
1172        let mut out = Vec::new();
1173        let read = tx.audit_lines(query.after, Some(query.limit), &mut out);
1174        self.record(
1175            &mut tx,
1176            &Entry {
1177                actor: who,
1178                action: Action::AuditRead,
1179                target: None,
1180                version: None,
1181                status: if read.is_ok() { 200 } else { 500 },
1182            },
1183        )?;
1184        commit(tx)?;
1185        read.map(|()| out).map_err(io)
1186    }
1187
1188    /// Whether server.sqlite answers a query, for the health route.
1189    pub fn check(&self) -> Result<(), TenantError> {
1190        self.registry.snapshot()?.tenants().map(|_| ())
1191    }
1192
1193    /// Records an event in the admin log, in a transaction of its own.
1194    pub(crate) fn record_alone(&self, entry: &Entry) -> Result<(), TenantError> {
1195        let mut tx = self.registry.immediate()?;
1196        self.record(&mut tx, entry)?;
1197        commit(tx)
1198    }
1199
1200    /// Counts an event in the admin log, in a transaction of its own.
1201    pub(crate) fn count_admin(&self, entry: &Entry) -> Result<(), TenantError> {
1202        let mut tx = self.registry.immediate()?;
1203        tx.count(entry, self.clock.now())
1204            .map_err(|_| TenantError::AuditFailed)?;
1205        commit(tx)
1206    }
1207
1208    /// Counts `times` events of the minute of `at` in the admin log, in
1209    /// one transaction: what was added up in memory, written once.
1210    pub(crate) fn count_admin_many(
1211        &self,
1212        entry: &Entry,
1213        at: OffsetDateTime,
1214        times: u64,
1215    ) -> Result<(), TenantError> {
1216        let mut tx = self.registry.immediate()?;
1217        tx.count_many(entry, at, times)
1218            .map_err(|_| TenantError::AuditFailed)?;
1219        commit(tx)
1220    }
1221
1222    /// The time on the clock the registry and the stores read.
1223    pub(crate) fn now(&self) -> OffsetDateTime {
1224        self.clock.now()
1225    }
1226
1227    /// The time given is this process's clock, as for a Store's record:
1228    /// a database's log writes the transaction's reading of its own clock
1229    /// instead. A removal's record is judged against the time the master
1230    /// key's use began, which another server may have written.
1231    fn record(&self, tx: &mut RTx, entry: &Entry) -> Result<(), TenantError> {
1232        tx.record(entry, self.clock.now())
1233            .map_err(|_| TenantError::AuditFailed)
1234    }
1235
1236    /// The local registry's connection, for tests.
1237    #[cfg(test)]
1238    fn conn(&self) -> MutexGuard<'_, LocalConn> {
1239        self.registry
1240            .as_any()
1241            .downcast_ref::<LocalRegistry>()
1242            .expect("the test's registry is the local one")
1243            .local_conn()
1244    }
1245}
1246
1247/// A tenant's name is a label for people: 1 to 128 characters, none of
1248/// them a control character, and no white space at either end, so two
1249/// names that look alike are alike.
1250fn good_name(name: &str) -> bool {
1251    (1..=128).contains(&name.chars().count())
1252        && !name.chars().any(char::is_control)
1253        && name.trim() == name
1254}
1255
1256/// A registry transaction.
1257pub(crate) type RTx<'a> = Box<dyn RegistryTx + 'a>;
1258
1259pub(crate) fn commit(tx: RTx) -> Result<(), TenantError> {
1260    tx.commit().map_err(io)
1261}
1262
1263pub(crate) fn io<E>(_: E) -> TenantError {
1264    TenantError::Io
1265}
1266
1267#[cfg(test)]
1268mod tests {
1269    use std::ffi::OsString;
1270
1271    use rusqlite::{Connection, OptionalExtension, params};
1272
1273    use serde_json::Value;
1274    use time::macros::datetime;
1275
1276    use super::*;
1277    use crate::audit::testing::exported;
1278    use crate::catalog;
1279    use crate::catalog::testing::columns_taking_null;
1280    use crate::clock::ManualClock;
1281    use crate::envelope::Context;
1282    use crate::fs::{CrashFs, Op};
1283    use crate::ids::VersionId;
1284    use crate::store::testing::vcon;
1285    use crate::store::{Caller, Created, StoreError};
1286
1287    const MARKER: &str = "plain-record-marker-8d21e4";
1288    const UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
1289
1290    fn caller() -> Caller {
1291        Caller {
1292            key: Key::generate().expect("key").id(),
1293        }
1294    }
1295
1296    /// What a create runs between its space and its row, given the
1297    /// `Tenants` creating.
1298    pub(crate) type CreateHook = Box<dyn FnOnce(&Tenants) + Send>;
1299
1300    /// What a backup runs at each try, after it copies server.sqlite.
1301    pub(super) type RegistryHook = Box<dyn FnMut(&Tenants) + Send>;
1302
1303    #[derive(Default)]
1304    pub(super) struct Hooks {
1305        /// Runs once, between a create's directory and catalog and the
1306        /// transaction that commits its row, given the `Tenants` creating.
1307        pub(super) between: Mutex<Option<CreateHook>>,
1308        /// Runs once, as `store` opens a tenant's Store.
1309        pub(super) opening: Mutex<Option<Box<dyn FnOnce() + Send>>>,
1310        /// Stops a key rotation, as a failure, after this step.
1311        pub(crate) rekey_stop: Mutex<Option<super::rekey::RekeyStep>>,
1312        /// Runs at each try of a backup, after server.sqlite is copied and
1313        /// before the tenants it lists are.
1314        pub(super) registry_copied: Mutex<Option<RegistryHook>>,
1315        /// Runs as a background job begins its step for a tenant.
1316        pub(super) job_step: Mutex<Option<JobHook>>,
1317        /// Nanoseconds added to the next readings of the registry's clock
1318        /// ([`Tenants::now_in`], recovery's too), one per reading, in
1319        /// order, as for a Store.
1320        pub(super) clock_steps: Mutex<Vec<i64>>,
1321    }
1322
1323    /// What a background job runs as it begins its step for a tenant, with
1324    /// the job's name.
1325    pub(crate) type JobHook = std::sync::Arc<dyn Fn(&'static str) + Send + Sync>;
1326
1327    impl Tenants {
1328        /// Adds `steps` to the next readings of the registry's clock, one
1329        /// per reading, in order ([`Hooks::clock_steps`]).
1330        pub(crate) fn step_clock(&self, steps: Vec<i64>) {
1331            *self.hooks.clock_steps.lock().expect("hook") = steps;
1332        }
1333
1334        /// Makes the registry's `nth` commit from now (1: the next) fail as
1335        /// `how`.
1336        pub(crate) fn fail_registry_commit(&self, nth: usize, how: CommitError) {
1337            self.registry.fail_commit(nth, how);
1338        }
1339    }
1340
1341    /// A master key kept wrapped, so a test can have it more than once.
1342    struct Master {
1343        holder: Key,
1344        wrapped: Vec<u8>,
1345    }
1346
1347    const CTX: Context = Context::Tenant {
1348        tenant: TenantId([0; 16]),
1349    };
1350
1351    impl Master {
1352        fn new() -> Master {
1353            let holder = Key::generate().expect("key");
1354            let wrapped = envelope::wrap(&holder, &CTX, &Key::generate().expect("key"));
1355            Master { holder, wrapped }
1356        }
1357
1358        fn key(&self) -> Key {
1359            envelope::unwrap(&self.holder, &CTX, &self.wrapped).expect("unwraps")
1360        }
1361    }
1362
1363    pub(crate) struct Fixture {
1364        pub(crate) dir: tempfile::TempDir,
1365        pub(crate) fs: Arc<CrashFs>,
1366        pub(crate) clock: Arc<ManualClock>,
1367        master: Master,
1368        pub(crate) tenants: Tenants,
1369    }
1370
1371    impl Fixture {
1372        fn open(&self) -> Result<Tenants, RegistryError> {
1373            Tenants::open(
1374                self.dir.path(),
1375                self.master.key(),
1376                self.fs.clone(),
1377                self.clock.clone(),
1378            )
1379        }
1380
1381        /// A crash, then a start: what was not synced is lost, and the
1382        /// registry is opened again.
1383        pub(crate) fn restart(&mut self) {
1384            self.fs.crash();
1385            let tenants = self.open().expect("opens again");
1386            drop(std::mem::replace(&mut self.tenants, tenants));
1387        }
1388
1389        pub(crate) fn conn(&self) -> MutexGuard<'_, Connection> {
1390            self.tenants.conn()
1391        }
1392
1393        /// The master key the registry was made under.
1394        pub(crate) fn master_key(&self) -> Key {
1395            self.master.key()
1396        }
1397
1398        pub(crate) fn tenants_dir(&self) -> PathBuf {
1399            self.dir.path().join("tenants")
1400        }
1401
1402        /// The tenant directories, as the filesystem shows them now.
1403        fn dirs(&self) -> Vec<OsString> {
1404            self.fs.list(&self.tenants_dir()).expect("list tenants")
1405        }
1406
1407        /// The one number a statement on server.sqlite answers.
1408        pub(crate) fn count(&self, sql: &str) -> i64 {
1409            self.conn().query_row(sql, [], |r| r.get(0)).expect(sql)
1410        }
1411
1412        pub(crate) fn master_wraps(&self) -> i64 {
1413            self.count("SELECT coalesce(sum(wraps), 0) FROM master_key_use")
1414        }
1415
1416        fn admin_log(&self) -> Vec<Value> {
1417            exported(&self.conn(), None)
1418        }
1419
1420        /// The tenant's key, unwrapped from its row.
1421        pub(crate) fn tenant_key(&self, id: TenantId) -> Key {
1422            let wrapped: Vec<u8> = self
1423                .conn()
1424                .query_row(
1425                    "SELECT wrapped_tenant_key FROM tenant WHERE id = ?1",
1426                    [id.0],
1427                    |r| r.get(0),
1428                )
1429                .expect("a row");
1430            envelope::unwrap(
1431                &self.master.key(),
1432                &Context::Tenant { tenant: id },
1433                &wrapped,
1434            )
1435            .expect("unwraps under the master key")
1436        }
1437
1438        /// The tenant's Store, opened as the registry would open it.
1439        pub(crate) fn store(&self, id: TenantId) -> Store {
1440            Store::open(
1441                &self.tenants_dir().join(id.to_string()),
1442                id,
1443                self.tenant_key(id),
1444                self.fs.clone(),
1445                self.clock.clone(),
1446            )
1447            .expect("the store opens")
1448        }
1449
1450        fn has_row(&self, id: TenantId) -> bool {
1451            self.conn()
1452                .query_row("SELECT 1 FROM tenant WHERE id = ?1", [id.0], |_| Ok(()))
1453                .optional()
1454                .expect("query")
1455                .is_some()
1456        }
1457
1458        /// A second connection to server.sqlite, as another writer.
1459        fn other(&self) -> Connection {
1460            let catalog_key = envelope::catalog_key(&self.master.key()).expect("catalog key");
1461            catalog::open(&self.dir.path().join("server.sqlite"), &catalog_key, "")
1462                .expect("second connection")
1463        }
1464    }
1465
1466    pub(crate) fn fixture() -> Fixture {
1467        let dir = tempfile::tempdir().expect("temp dir");
1468        let fs = Arc::new(CrashFs::new(dir.path()));
1469        let clock = Arc::new(ManualClock::at(datetime!(2026-10-23 12:00 UTC)));
1470        let master = Master::new();
1471        let tenants =
1472            Tenants::open(dir.path(), master.key(), fs.clone(), clock.clone()).expect("opens");
1473        Fixture {
1474            dir,
1475            fs,
1476            clock,
1477            master,
1478            tenants,
1479        }
1480    }
1481
1482    #[test]
1483    fn server_sqlite_is_a_catalog_under_the_master_keys_catalog_key() {
1484        let f = fixture();
1485        let conn = f.other();
1486        let tables: Vec<String> = conn
1487            .prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")
1488            .expect("prepare")
1489            .query_map([], |r| r.get(0))
1490            .expect("query")
1491            .collect::<Result<_, _>>()
1492            .expect("names");
1493        assert_eq!(
1494            tables,
1495            [
1496                "api_key",
1497                "audit",
1498                "master_key_use",
1499                "membership",
1500                "session",
1501                "sqlite_sequence",
1502                "tenant",
1503                "tenant_setting",
1504                "user_account"
1505            ]
1506        );
1507    }
1508
1509    #[test]
1510    fn an_admin_audit_page_is_export_s_lines_and_records_its_read_after_them() {
1511        let f = fixture();
1512        for name in ["acme", "beta"] {
1513            f.tenants.create(Actor::Cli, name, None).expect("made");
1514        }
1515        let mut before = Vec::new();
1516        f.tenants.export_admin(None, &mut before).expect("export");
1517        let who = Actor::Key(Key::generate().expect("key").id());
1518        let query = |after, limit| audit::AuditQuery { after, limit };
1519        assert_eq!(
1520            f.tenants.audit_page(who, &query(0, 1000)),
1521            Ok(before.clone())
1522        );
1523        let read = exported(&f.conn(), None);
1524        let last = read.last().expect("records");
1525        assert_eq!(last["action"], "audit_read");
1526        assert_eq!(last["status"], 200);
1527        let lines: Vec<&[u8]> = before.split_inclusive(|b| *b == b'\n').collect();
1528        assert_eq!(
1529            f.tenants.audit_page(who, &query(1, 1)),
1530            Ok(lines[1].to_vec())
1531        );
1532        f.conn()
1533            .execute(
1534                "INSERT INTO audit (at, actor, action, status, count)
1535                 VALUES ('2026-10-23T12:00:00Z', 'cli', 'read', 70000, 1)",
1536                [],
1537            )
1538            .expect("damaged");
1539        assert_eq!(
1540            f.tenants.audit_page(who, &query(0, 1000)),
1541            Err(TenantError::Io)
1542        );
1543        let last = exported_last(&f);
1544        assert_eq!(last["action"], "audit_read");
1545        assert_eq!(last["status"], 500);
1546        f.tenants.break_audit();
1547        assert_eq!(
1548            f.tenants.audit_page(who, &query(0, 1000)),
1549            Err(TenantError::AuditFailed)
1550        );
1551    }
1552
1553    /// The admin log's last record, read past a damaged one.
1554    fn exported_last(f: &Fixture) -> Value {
1555        let conn = f.conn();
1556        let (action, status): (String, i64) = conn
1557            .query_row(
1558                "SELECT action, status FROM audit ORDER BY seq DESC LIMIT 1",
1559                [],
1560                |r| Ok((r.get(0)?, r.get(1)?)),
1561            )
1562            .expect("a record");
1563        serde_json::json!({"action": action, "status": status})
1564    }
1565
1566    /// What a registry that does not open says: everything a failure
1567    /// report shows of the error.
1568    fn said(dir: &Path) -> String {
1569        let error = Tenants::open(
1570            dir,
1571            Key::generate().expect("key"),
1572            Arc::new(crate::fs::OsFs),
1573            Arc::new(ManualClock::at(datetime!(2026-10-23 12:00 UTC))),
1574        )
1575        .err()
1576        .expect("it does not open");
1577        format!("{error:?}")
1578    }
1579
1580    /// A server.sqlite that cannot be opened names the file, the step and
1581    /// SQLite's error, not only "Io".
1582    #[test]
1583    fn a_server_sqlite_that_cannot_be_opened_names_the_file_and_the_cause() {
1584        let dir = tempfile::tempdir().expect("temp dir");
1585        std::fs::create_dir(dir.path().join("server.sqlite")).expect("a directory in its place");
1586        let said = said(dir.path());
1587        assert!(said.contains("server.sqlite"), "the file is named: {said}");
1588        assert!(said.contains("OpenCatalog"), "the step is named: {said}");
1589        assert!(
1590            said.contains("unable to open database file"),
1591            "SQLite's own error is kept: {said}"
1592        );
1593    }
1594
1595    /// A tenants/ that cannot be made names the directory and the system's
1596    /// error.
1597    #[test]
1598    fn a_tenants_directory_that_cannot_be_made_names_it_and_the_cause() {
1599        let dir = tempfile::tempdir().expect("temp dir");
1600        std::fs::write(dir.path().join("tenants"), b"").expect("a file in its place");
1601        let said = said(dir.path());
1602        assert!(said.contains("tenants"), "the directory is named: {said}");
1603        assert!(said.contains("MakeTenantsDir"), "the step is named: {said}");
1604        assert!(
1605            said.contains("File exists"),
1606            "the system's error is kept: {said}"
1607        );
1608    }
1609
1610    #[test]
1611    fn a_wrong_master_key_does_not_open_server_sqlite() {
1612        let f = fixture();
1613        let wrong = Tenants::open(
1614            f.dir.path(),
1615            Master::new().key(),
1616            f.fs.clone(),
1617            f.clock.clone(),
1618        );
1619        assert!(
1620            matches!(wrong, Err(RegistryError::WrongKey)),
1621            "a wrong key is told apart from every other failure: {:?}",
1622            wrong.err()
1623        );
1624        assert!(f.open().is_ok(), "the right key still opens it");
1625    }
1626
1627    #[test]
1628    fn only_the_optional_columns_may_be_empty() {
1629        let f = fixture();
1630        let conn = f.conn();
1631        let tenant = [
1632            ("id", "x'11'"),
1633            ("name", "'a'"),
1634            ("retention", "'7y'"),
1635            ("created_at", "1"),
1636            ("tenant_key_id", "x'22'"),
1637            ("wrapped_tenant_key", "x'33'"),
1638            ("pending_wrapped_tenant_key", "x'44'"),
1639            ("key_since", "1"),
1640        ];
1641        let key_use = [("master_key_id", "x'55'"), ("wraps", "1"), ("since", "1")];
1642        let api_key = [
1643            ("id", "x'66'"),
1644            ("tenant", "x'11'"),
1645            ("token_hash", "x'77'"),
1646            ("scopes", "'read'"),
1647            ("label", "'a'"),
1648            ("created_at", "1"),
1649            ("revoked_at", "2"),
1650        ];
1651        let mut may_be_empty = columns_taking_null(&conn, "tenant", &tenant);
1652        may_be_empty.extend(columns_taking_null(&conn, "master_key_use", &key_use));
1653        may_be_empty.extend(columns_taking_null(&conn, "api_key", &api_key));
1654        assert_eq!(
1655            may_be_empty,
1656            [
1657                "tenant.retention",
1658                "tenant.pending_wrapped_tenant_key",
1659                "api_key.tenant",
1660                "api_key.revoked_at"
1661            ]
1662        );
1663    }
1664
1665    #[test]
1666    fn a_name_belongs_to_one_tenant() {
1667        let f = fixture();
1668        let conn = f.conn();
1669        let add = |id: u8, name: &str| {
1670            conn.execute(
1671                "INSERT INTO tenant (id, name, created_at, tenant_key_id,
1672                     wrapped_tenant_key, key_since)
1673                 VALUES (?1, ?2, 1, x'22', x'33', 1)",
1674                params![[id; 16], name],
1675            )
1676        };
1677        add(1, "a").expect("the first tenant");
1678        add(2, "b").expect("another name");
1679        assert!(add(3, "a").is_err(), "a second tenant named a");
1680    }
1681
1682    /// Run while the connection is open, so the commits are still in the
1683    /// WAL.
1684    #[test]
1685    fn no_plain_record_reaches_server_sqlite_or_its_wal() {
1686        let f = fixture();
1687        f.tenants
1688            .create(Actor::Cli, MARKER, Some(Retention::Years(7)))
1689            .expect("a tenant");
1690        let wal = std::fs::metadata(f.dir.path().join("server.sqlite-wal")).expect("a WAL");
1691        assert!(wal.len() > 0, "the commits are in the WAL");
1692        for entry in std::fs::read_dir(f.dir.path()).expect("list") {
1693            let file = entry.expect("entry").path();
1694            if !file.is_file() {
1695                continue;
1696            }
1697            let bytes = std::fs::read(&file).expect("read");
1698            assert!(
1699                !bytes.windows(MARKER.len()).any(|w| w == MARKER.as_bytes()),
1700                "plain record in {}",
1701                file.display()
1702            );
1703        }
1704    }
1705
1706    #[test]
1707    fn a_new_registrys_tenants_directory_survives_a_crash() {
1708        let f = fixture();
1709        f.fs.crash();
1710        assert_eq!(
1711            f.fs.list(f.dir.path()).expect("list"),
1712            [OsString::from("tenants")]
1713        );
1714    }
1715
1716    /// A tenant row's columns, besides its id and wrapped key.
1717    struct Row {
1718        name: String,
1719        retention: Option<String>,
1720        created_at: i64,
1721        key_id: Vec<u8>,
1722        pending: Option<Vec<u8>>,
1723        key_since: i64,
1724    }
1725
1726    #[test]
1727    fn a_tenant_is_made_with_its_key_directory_catalog_and_row() {
1728        let f = fixture();
1729        let id = f
1730            .tenants
1731            .create(Actor::Cli, "acme", Some(Retention::Years(7)))
1732            .expect("made");
1733        f.clock.set(datetime!(2026-10-23 13:00 UTC));
1734        let other = f.tenants.create(Actor::Cli, "lab", None).expect("another");
1735        assert_ne!(id, other, "a new id each time");
1736
1737        let Row {
1738            name,
1739            retention,
1740            created_at,
1741            key_id,
1742            pending,
1743            key_since,
1744        } = f
1745            .conn()
1746            .query_row(
1747                "SELECT name, retention, created_at, tenant_key_id,
1748                     pending_wrapped_tenant_key, key_since
1749                 FROM tenant WHERE id = ?1",
1750                [id.0],
1751                |r| {
1752                    Ok(Row {
1753                        name: r.get(0)?,
1754                        retention: r.get(1)?,
1755                        created_at: r.get(2)?,
1756                        key_id: r.get(3)?,
1757                        pending: r.get(4)?,
1758                        key_since: r.get(5)?,
1759                    })
1760                },
1761            )
1762            .expect("a row");
1763        let now = nanos(datetime!(2026-10-23 12:00 UTC));
1764        assert_eq!(name, "acme");
1765        assert_eq!(retention.as_deref(), Some("7y"));
1766        assert_eq!((created_at, key_since), (now, now));
1767        assert_eq!(pending, None);
1768        let key = f.tenant_key(id);
1769        assert_eq!(key_id, key.id().bytes());
1770        let lab_retention: Option<String> = f
1771            .conn()
1772            .query_row(
1773                "SELECT retention FROM tenant WHERE id = ?1",
1774                [other.0],
1775                |r| r.get(0),
1776            )
1777            .expect("a row");
1778        assert_eq!(lab_retention, None, "no period means the server default");
1779
1780        let mut dirs = vec![
1781            OsString::from(id.to_string()),
1782            OsString::from(other.to_string()),
1783        ];
1784        dirs.sort();
1785        assert_eq!(f.dirs(), dirs);
1786        drop(f.store(id));
1787        let catalog_key = envelope::catalog_key(&key).expect("catalog key");
1788        let tenant_dir = f.tenants_dir().join(id.to_string());
1789        assert!(
1790            catalog::open(&tenant_dir.join("catalog.sqlite"), &catalog_key, "").is_ok(),
1791            "the catalog is under the tenant key's catalog key"
1792        );
1793
1794        let (wraps, since): (i64, i64) = f
1795            .conn()
1796            .query_row(
1797                "SELECT wraps, since FROM master_key_use WHERE master_key_id = ?1",
1798                [f.master.key().id().bytes()],
1799                |r| Ok((r.get(0)?, r.get(1)?)),
1800            )
1801            .expect("the master key's use");
1802        assert_eq!((wraps, since), (2, now));
1803
1804        let log = f.admin_log();
1805        assert_eq!(log.len(), 2);
1806        assert_eq!(log[0]["actor"], "cli");
1807        assert_eq!(log[0]["action"], "tenant_create");
1808        assert_eq!(log[0]["target"], id.to_string());
1809        assert_eq!(log[0]["status"], 201);
1810        assert_eq!(log[0]["at"], "2026-10-23T12:00:00Z");
1811    }
1812
1813    #[test]
1814    fn a_taken_name_is_refused_before_anything_is_made() {
1815        let f = fixture();
1816        f.tenants.create(Actor::Cli, "acme", None).expect("made");
1817        let ops = f.fs.log().len();
1818        assert_eq!(
1819            f.tenants.create(Actor::Cli, "acme", None),
1820            Err(TenantError::NameTaken)
1821        );
1822        assert_eq!(f.fs.log().len(), ops, "nothing made");
1823        assert_eq!(f.master_wraps(), 1, "nothing wrapped");
1824        assert_eq!(f.count("SELECT count(*) FROM tenant"), 1);
1825        let log = f.admin_log();
1826        assert_eq!(log[1]["action"], "tenant_create");
1827        assert_eq!(log[1]["status"], 409);
1828        assert_eq!(log[1]["target"], Value::Null, "no tenant was made");
1829    }
1830
1831    #[test]
1832    fn a_name_is_1_to_128_characters_without_controls_or_outer_spaces() {
1833        let long = "é".repeat(128);
1834        for name in ["acme", "a", "Acme Corp", "Acme — Europe", long.as_str()] {
1835            assert!(good_name(name), "{name:?}");
1836        }
1837        let longer = "é".repeat(129);
1838        for name in [
1839            "",
1840            " acme",
1841            "acme ",
1842            "ac\nme",
1843            "ac\tme",
1844            "acme\u{7f}",
1845            "\u{85}acme",
1846            "acme\u{3000}",
1847            longer.as_str(),
1848        ] {
1849            assert!(!good_name(name), "{name:?}");
1850        }
1851    }
1852
1853    #[test]
1854    fn a_bad_name_is_refused_and_recorded_before_anything_is_made() {
1855        let f = fixture();
1856        let ops = f.fs.log().len();
1857        assert_eq!(
1858            f.tenants.create(Actor::Cli, " acme", None),
1859            Err(TenantError::BadName)
1860        );
1861        assert_eq!(f.fs.log().len(), ops, "nothing made");
1862        assert_eq!(f.master_wraps(), 0, "nothing wrapped");
1863        assert_eq!(f.count("SELECT count(*) FROM tenant"), 0);
1864        let log = f.admin_records("tenant_create");
1865        assert_eq!(log.len(), 1);
1866        assert_eq!(log[0]["status"], 422);
1867        assert_eq!(log[0]["target"], Value::Null, "no tenant was made");
1868    }
1869
1870    #[test]
1871    fn a_master_key_at_its_wrap_limit_makes_no_tenant() {
1872        let f = fixture();
1873        f.conn()
1874            .execute(
1875                "INSERT INTO master_key_use (master_key_id, wraps, since) VALUES (?1, ?2, 1)",
1876                params![f.master.key().id().bytes(), 1_i64 << 32],
1877            )
1878            .expect("at the limit");
1879        let ops = f.fs.log().len();
1880        assert_eq!(
1881            f.tenants.create(Actor::Cli, "acme", None),
1882            Err(TenantError::LimitReached)
1883        );
1884        assert_eq!(f.fs.log().len(), ops, "nothing made");
1885        assert_eq!(f.master_wraps(), 1_i64 << 32, "nothing counted");
1886        assert_eq!(f.count("SELECT count(*) FROM tenant"), 0);
1887        assert_eq!(f.admin_log()[0]["status"], 503);
1888    }
1889
1890    #[test]
1891    fn a_negative_wrap_count_is_damage_and_makes_no_tenant() {
1892        let f = fixture();
1893        f.conn()
1894            .execute(
1895                "INSERT INTO master_key_use (master_key_id, wraps, since) VALUES (?1, -1, 1)",
1896                [f.master.key().id().bytes()],
1897            )
1898            .expect("a damaged count");
1899        let ops = f.fs.log().len();
1900        assert_eq!(
1901            f.tenants.create(Actor::Cli, "acme", None),
1902            Err(TenantError::Io)
1903        );
1904        assert_eq!(f.fs.log().len(), ops, "nothing made");
1905    }
1906
1907    #[test]
1908    fn a_name_taken_while_the_directory_is_made_loses_and_leaves_nothing() {
1909        let f = fixture();
1910        let other = f.other();
1911        *f.tenants.hooks.between.lock().expect("hook") = Some(Box::new(move |_| {
1912            other
1913                .execute(
1914                    "INSERT INTO tenant (id, name, created_at, tenant_key_id,
1915                         wrapped_tenant_key, key_since)
1916                     VALUES (x'01', 'acme', 1, x'02', x'03', 1)",
1917                    [],
1918                )
1919                .expect("another create wins the name");
1920        }));
1921        assert_eq!(
1922            f.tenants.create(Actor::Cli, "acme", None),
1923            Err(TenantError::NameTaken)
1924        );
1925        assert_eq!(f.dirs(), Vec::<OsString>::new(), "its directory is removed");
1926        assert_eq!(f.master_wraps(), 1, "its wrap is still counted");
1927        let log = f.admin_log();
1928        assert_eq!(log.len(), 1);
1929        assert_eq!(log[0]["status"], 409);
1930    }
1931
1932    #[test]
1933    fn a_create_whose_audit_record_fails_leaves_nothing() {
1934        let f = fixture();
1935        f.conn()
1936            .execute_batch(
1937                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
1938                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
1939            )
1940            .expect("trigger");
1941        assert_eq!(
1942            f.tenants.create(Actor::Cli, "acme", None),
1943            Err(TenantError::AuditFailed)
1944        );
1945        assert_eq!(f.count("SELECT count(*) FROM tenant"), 0);
1946        assert_eq!(f.dirs(), Vec::<OsString>::new(), "its directory is removed");
1947    }
1948
1949    #[test]
1950    fn a_create_whose_row_cannot_be_written_leaves_nothing() {
1951        let f = fixture();
1952        f.conn()
1953            .execute_batch(
1954                "CREATE TEMP TRIGGER no_row BEFORE INSERT ON tenant
1955                 BEGIN SELECT RAISE(ABORT, 'the disk has failed'); END;",
1956            )
1957            .expect("trigger");
1958        assert_eq!(
1959            f.tenants.create(Actor::Cli, "acme", None),
1960            Err(TenantError::Io)
1961        );
1962        assert_eq!(f.count("SELECT count(*) FROM tenant"), 0);
1963        assert_eq!(f.dirs(), Vec::<OsString>::new(), "its directory is removed");
1964    }
1965
1966    #[test]
1967    fn a_create_whose_commit_outcome_is_unknown_keeps_its_directory() {
1968        let f = fixture();
1969        // The wrap count commits first; the second commit, which adds the
1970        // row, is kept and then reported as failed, as a lost connection
1971        // reports a commit the database made.
1972        f.tenants.fail_registry_commit(2, CommitError::Unknown);
1973        assert_eq!(
1974            f.tenants.create(Actor::Cli, "acme", None),
1975            Err(TenantError::Io),
1976            "a_create_whose_commit_outcome_is_unknown_keeps_its_directory: f.tenants.create(Actor::Cli, \"acme\", None)"
1977        );
1978        assert_eq!(
1979            f.count("SELECT count(*) FROM tenant"),
1980            1,
1981            "a_create_whose_commit_outcome_is_unknown_keeps_its_directory: f.count(\"SELECT count(*) FROM tenant\")"
1982        );
1983        assert_eq!(
1984            f.dirs().len(),
1985            1,
1986            "the directory made for the kept row stays"
1987        );
1988        let id = f.tenants.ids().expect("ids")[0];
1989        let store = f.tenants.store(id).expect("the kept tenant opens");
1990        let (found, body) = vcon(UUID, "kept");
1991        store.create(&caller(), &found, &body).expect("stores");
1992    }
1993
1994    #[test]
1995    fn a_create_whose_commit_rolls_back_leaves_nothing() {
1996        let f = fixture();
1997        f.tenants.fail_registry_commit(2, CommitError::RolledBack);
1998        assert_eq!(
1999            f.tenants.create(Actor::Cli, "acme", None),
2000            Err(TenantError::Io),
2001            "a_create_whose_commit_rolls_back_leaves_nothing: f.tenants.create(Actor::Cli, \"acme\", None)"
2002        );
2003        assert_eq!(
2004            f.count("SELECT count(*) FROM tenant"),
2005            0,
2006            "a_create_whose_commit_rolls_back_leaves_nothing: f.count(\"SELECT count(*) FROM tenant\")"
2007        );
2008        assert_eq!(f.dirs(), Vec::<OsString>::new(), "its directory is removed");
2009    }
2010
2011    #[test]
2012    fn a_refusal_whose_audit_record_fails_is_an_audit_failure() {
2013        let f = fixture();
2014        f.tenants.create(Actor::Cli, "acme", None).expect("made");
2015        f.conn()
2016            .execute_batch(
2017                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
2018                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
2019            )
2020            .expect("trigger");
2021        assert_eq!(
2022            f.tenants.create(Actor::Cli, "acme", None),
2023            Err(TenantError::AuditFailed)
2024        );
2025    }
2026
2027    /// The steps of a create that the filesystem sees: the tenant's
2028    /// directory; the new catalog's WAL and then the tenant's directory
2029    /// synced when the catalog opens; its objects directory and the sync of
2030    /// the tenant's directory; start-up recovery's commit synced; the sync
2031    /// of `tenants/`. The row's commit follows them.
2032    const CREATE_STEPS: usize = 7;
2033
2034    #[test]
2035    fn a_create_writes_its_directories_in_order() {
2036        let f = fixture();
2037        let ops = f.fs.log().len();
2038        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2039        let dir = f.tenants_dir().join(id.to_string());
2040        let wal = dir.join("catalog.sqlite-wal");
2041        assert_eq!(
2042            f.fs.log()[ops..],
2043            [
2044                Op::CreateDir(dir.clone()),
2045                Op::SyncData(wal.clone()),
2046                Op::SyncDir(dir.clone()),
2047                Op::CreateDir(dir.join("objects")),
2048                Op::SyncDir(dir),
2049                Op::SyncData(wal),
2050                Op::SyncDir(f.tenants_dir()),
2051            ],
2052            "the WAL is synced, then its directory, before anything else is made"
2053        );
2054        assert_eq!(
2055            f.fs.log().len() - ops,
2056            CREATE_STEPS,
2057            "the steps a cut can hit"
2058        );
2059    }
2060
2061    #[test]
2062    fn a_create_cut_off_at_any_step_leaves_a_whole_tenant_or_none() {
2063        let uncut = {
2064            let f = fixture();
2065            let ops = f.fs.log().len();
2066            f.tenants.create(Actor::Cli, "acme", None).expect("made");
2067            f.fs.log()[ops..].to_vec()
2068        };
2069        assert_eq!(
2070            uncut.len(),
2071            CREATE_STEPS,
2072            "every step of a create: {uncut:?}"
2073        );
2074        for step in 0..=CREATE_STEPS {
2075            let mut f = fixture();
2076            f.fs.fail_from(f.fs.log().len() + step);
2077            let result = f.tenants.create(Actor::Cli, "acme", None);
2078            assert_eq!(
2079                result.is_ok(),
2080                step == CREATE_STEPS,
2081                "step {step}: {result:?}"
2082            );
2083            f.restart();
2084            match result {
2085                Ok(id) => {
2086                    assert!(f.has_row(id), "step {step}");
2087                    assert_eq!(f.dirs(), [OsString::from(id.to_string())]);
2088                    let store = f.store(id);
2089                    drop(store);
2090                }
2091                Err(_) => {
2092                    assert_eq!(f.count("SELECT count(*) FROM tenant"), 0, "step {step}");
2093                    assert_eq!(f.dirs(), Vec::<OsString>::new(), "step {step}");
2094                }
2095            }
2096        }
2097    }
2098
2099    #[test]
2100    fn a_create_cut_off_before_its_commit_leaves_no_tenant() {
2101        let mut f = fixture();
2102        let other = f.other();
2103        let fs = f.fs.clone();
2104        *f.tenants.hooks.between.lock().expect("hook") = Some(Box::new(move |_| {
2105            fs.fail_from(0);
2106            other
2107                .execute_batch(
2108                    "CREATE TRIGGER dead BEFORE INSERT ON audit
2109                     BEGIN SELECT RAISE(ABORT, 'the process has died'); END;",
2110                )
2111                .expect("trigger");
2112        }));
2113        assert!(f.tenants.create(Actor::Cli, "acme", None).is_err());
2114        assert_eq!(f.dirs().len(), 1, "the dead process removed nothing");
2115        f.conn()
2116            .execute_batch("DROP TRIGGER dead")
2117            .expect("drop trigger");
2118        f.restart();
2119        assert_eq!(f.count("SELECT count(*) FROM tenant"), 0);
2120        assert_eq!(f.dirs(), Vec::<OsString>::new(), "removed at start");
2121    }
2122
2123    /// The fixture clock's start, as the creates below begin.
2124    const START: OffsetDateTime = datetime!(2026-10-23 12:00 UTC);
2125
2126    /// `START` moved by `nanos` nanoseconds.
2127    fn start_plus(nanos: i64) -> OffsetDateTime {
2128        START + time::Duration::nanoseconds(nanos)
2129    }
2130
2131    impl Fixture {
2132        /// The creating rows of the registry: the creates under way.
2133        fn creating(&self) -> Vec<(TenantId, i64)> {
2134            self.tenants
2135                .registry
2136                .snapshot()
2137                .expect("a read begins")
2138                .creating()
2139                .expect("lists")
2140        }
2141
2142        /// Sets the hook between a create's space and its row to move the
2143        /// clock to `to` and run recovery with `writers`, as another
2144        /// process recovering at that time would.
2145        fn recover_between(&self, to: OffsetDateTime, writers: Writers) {
2146            let clock = self.clock.clone();
2147            *self.tenants.hooks.between.lock().expect("hook") =
2148                Some(Box::new(move |tenants: &Tenants| {
2149                    clock.set(to);
2150                    tenants.recover(writers).expect("recovery runs");
2151                }));
2152        }
2153    }
2154
2155    #[test]
2156    fn a_create_under_way_keeps_its_space_through_recovery_beside_other_writers() {
2157        let f = fixture();
2158        f.recover_between(START, Writers::Maybe);
2159        let id = f
2160            .tenants
2161            .create(Actor::Cli, "acme", None)
2162            .expect("the create commits");
2163        assert_eq!(f.dirs(), [OsString::from(id.to_string())], "its space kept");
2164        drop(f.store(id));
2165    }
2166
2167    /// Recovery reads the registry's clock once: a create a minute inside
2168    /// its lease at that reading is kept, though the clock passes the
2169    /// lease before recovery lists the spaces. Else its space would go
2170    /// while its creating row stays, and the create would add a tenant
2171    /// with no space.
2172    #[test]
2173    fn recovery_judges_every_creating_row_by_one_reading_of_the_clock() {
2174        let f = fixture();
2175        let minute = 60 * 1_000_000_000;
2176        let clock = f.clock.clone();
2177        let to = start_plus(pending::WRITE_LEASE - minute);
2178        // The steps are set in the create's pause, so that recovery's are
2179        // the next readings: the create reads the clock before it too.
2180        *f.tenants.hooks.between.lock().expect("hook") =
2181            Some(Box::new(move |tenants: &Tenants| {
2182                clock.set(to);
2183                tenants.step_clock(vec![0, 2 * minute]);
2184                tenants.recover(Writers::Maybe).expect("recovery runs");
2185            }));
2186        let id = f
2187            .tenants
2188            .create(Actor::Cli, "acme", None)
2189            .expect("the create commits");
2190        assert_eq!(
2191            f.dirs(),
2192            [OsString::from(id.to_string())],
2193            "its space was kept with its row"
2194        );
2195        drop(f.store(id));
2196    }
2197
2198    #[test]
2199    fn a_create_just_inside_its_lease_keeps_its_space() {
2200        let f = fixture();
2201        f.recover_between(start_plus(pending::WRITE_LEASE - 1), Writers::Maybe);
2202        let id = f
2203            .tenants
2204            .create(Actor::Cli, "acme", None)
2205            .expect("the create commits");
2206        assert_eq!(f.dirs(), [OsString::from(id.to_string())], "its space kept");
2207        drop(f.store(id));
2208    }
2209
2210    #[test]
2211    fn a_create_seen_from_a_clock_behind_is_still_under_way() {
2212        let f = fixture();
2213        f.recover_between(start_plus(1 - pending::WRITE_LEASE), Writers::Maybe);
2214        let id = f
2215            .tenants
2216            .create(Actor::Cli, "acme", None)
2217            .expect("a clock behind within the lease keeps it");
2218        assert_eq!(f.dirs(), [OsString::from(id.to_string())], "its space kept");
2219        drop(f.store(id));
2220    }
2221
2222    #[test]
2223    fn a_create_past_its_lease_is_a_leftover_and_adds_no_row() {
2224        let f = fixture();
2225        f.recover_between(start_plus(pending::WRITE_LEASE), Writers::Maybe);
2226        assert_eq!(
2227            f.tenants.create(Actor::Cli, "acme", None),
2228            Err(TenantError::Io),
2229            "recovery took its space, so the create is refused"
2230        );
2231        assert_eq!(f.count("SELECT count(*) FROM tenant"), 0, "no row");
2232        assert_eq!(f.dirs(), Vec::<OsString>::new(), "and no space");
2233        assert_eq!(f.creating(), Vec::new(), "nor a creating row");
2234    }
2235
2236    #[test]
2237    fn a_create_under_way_is_a_leftover_to_a_process_that_holds_the_registry_alone() {
2238        let f = fixture();
2239        f.recover_between(START, Writers::None);
2240        assert_eq!(
2241            f.tenants.create(Actor::Cli, "acme", None),
2242            Err(TenantError::Io),
2243            "with no other writer, the space is a leftover's"
2244        );
2245        assert_eq!(f.count("SELECT count(*) FROM tenant"), 0, "no row");
2246        assert_eq!(f.dirs(), Vec::<OsString>::new(), "and no space");
2247    }
2248
2249    #[test]
2250    fn a_create_records_itself_under_way_until_its_row() {
2251        let f = fixture();
2252        let seen = Arc::new(Mutex::new(Vec::new()));
2253        let into = seen.clone();
2254        *f.tenants.hooks.between.lock().expect("hook") =
2255            Some(Box::new(move |tenants: &Tenants| {
2256                *into.lock().expect("seen") = tenants
2257                    .registry
2258                    .snapshot()
2259                    .expect("a read begins")
2260                    .creating()
2261                    .expect("lists");
2262            }));
2263        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2264        assert_eq!(
2265            *seen.lock().expect("seen"),
2266            vec![(id, nanos(START))],
2267            "between its space and its row, the create is under way"
2268        );
2269        assert_eq!(f.creating(), Vec::new(), "the row's commit drops it");
2270    }
2271
2272    #[test]
2273    fn a_create_refused_for_its_name_leaves_no_creating_row() {
2274        let f = fixture();
2275        f.tenants.create(Actor::Cli, "acme", None).expect("made");
2276        assert_eq!(
2277            f.tenants.create(Actor::Cli, "acme", None),
2278            Err(TenantError::NameTaken),
2279            "the name is taken at the first step"
2280        );
2281        assert_eq!(f.creating(), Vec::new(), "a first-step refusal adds none");
2282        let other = f.other();
2283        *f.tenants.hooks.between.lock().expect("hook") = Some(Box::new(move |_| {
2284            other
2285                .execute(
2286                    "INSERT INTO tenant (id, name, created_at, tenant_key_id,
2287                         wrapped_tenant_key, key_since)
2288                     VALUES (x'01', 'beta', 1, x'02', x'03', 1)",
2289                    [],
2290                )
2291                .expect("another create wins the name");
2292        }));
2293        assert_eq!(
2294            f.tenants.create(Actor::Cli, "beta", None),
2295            Err(TenantError::NameTaken),
2296            "another create took the name before the row"
2297        );
2298        assert_eq!(f.creating(), Vec::new(), "nor a refusal at the row");
2299    }
2300
2301    #[test]
2302    fn a_create_whose_row_fails_leaves_no_creating_row() {
2303        let f = fixture();
2304        f.conn()
2305            .execute_batch(
2306                "CREATE TEMP TRIGGER no_tenant BEFORE INSERT ON tenant
2307                 BEGIN SELECT RAISE(ABORT, 'no row'); END;",
2308            )
2309            .expect("trigger");
2310        assert!(
2311            f.tenants.create(Actor::Cli, "acme", None).is_err(),
2312            "the row cannot be written"
2313        );
2314        assert_eq!(f.creating(), Vec::new(), "the failed create drops it");
2315        assert_eq!(f.dirs(), Vec::<OsString>::new(), "and its space");
2316    }
2317
2318    #[test]
2319    fn recovery_beside_other_writers_removes_a_space_with_no_row_and_no_create() {
2320        let f = fixture();
2321        let kept = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2322        let orphan = TenantId::generate();
2323        f.fs.create_dir_all(&f.tenants_dir().join(orphan.to_string()))
2324            .expect("a directory");
2325        f.tenants.recover(Writers::Maybe).expect("recovery runs");
2326        assert_eq!(
2327            f.dirs(),
2328            [OsString::from(kept.to_string())],
2329            "no create is under way for the orphan"
2330        );
2331    }
2332
2333    #[test]
2334    fn recovery_drops_only_the_creating_rows_past_their_lease() {
2335        let f = fixture();
2336        {
2337            let mut tx = f.tenants.registry.immediate().expect("a write begins");
2338            tx.add_creating(TenantId([1; 16]), nanos(START) - pending::WRITE_LEASE)
2339                .expect("adds");
2340            tx.add_creating(TenantId([2; 16]), nanos(START) - pending::WRITE_LEASE + 1)
2341                .expect("adds");
2342            tx.commit().expect("commits");
2343        }
2344        f.tenants.recover(Writers::Maybe).expect("recovery runs");
2345        assert_eq!(
2346            f.creating(),
2347            vec![(TenantId([2; 16]), nanos(START) - pending::WRITE_LEASE + 1)],
2348            "the row inside the lease is a create under way"
2349        );
2350        f.tenants.recover(Writers::None).expect("recovery runs");
2351        assert_eq!(f.creating(), Vec::new(), "alone, every row is a leftover's");
2352    }
2353
2354    /// The recovery a running server repeats at each sweep: the leftover
2355    /// space goes without a restart, and the tenant's Store is recovered
2356    /// as one other writers may be using.
2357    #[test]
2358    fn a_running_server_s_recovery_removes_a_space_with_no_row_and_keeps_the_rest() {
2359        let f = fixture();
2360        let kept = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2361        let orphan = TenantId::generate();
2362        let tenants = f.tenants_dir();
2363        for name in [orphan.to_string(), "notes".to_owned()] {
2364            f.fs.create_dir_all(&tenants.join(name))
2365                .expect("a directory");
2366        }
2367        f.tenants.recover_all().expect("recovery runs");
2368        assert_eq!(
2369            f.dirs(),
2370            [OsString::from(kept.to_string()), OsString::from("notes")],
2371            "the space with no row goes; the tenant and a name not ours stay"
2372        );
2373        drop(f.store(kept));
2374    }
2375
2376    #[test]
2377    fn a_running_server_s_recovery_keeps_a_write_under_way_in_this_process() {
2378        let f = fixture();
2379        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2380        let store = f.tenants.store(id).expect("its store");
2381        let (arrive, arrived) = std::sync::mpsc::channel();
2382        let (go, went) = std::sync::mpsc::channel::<()>();
2383        let wait = std::time::Duration::from_secs(60);
2384        store.on_between(Box::new(move || {
2385            arrive.send(()).expect("the test waits");
2386            went.recv_timeout(wait).expect("the test says go on");
2387        }));
2388        let (found, body) =
2389            crate::store::testing::vcon("0199e5c6-0d7a-7c11-8000-0000000000a1", "under way");
2390        let who = crate::store::Caller {
2391            key: crate::ids::KeyId([3; 8]),
2392        };
2393        std::thread::scope(|s| {
2394            let writing = s.spawn(|| store.create(&who, &found, &body));
2395            arrived.recv_timeout(wait).expect("the write is under way");
2396            f.tenants.recover_all().expect("recovery runs mid-write");
2397            go.send(()).expect("the write waits");
2398            writing.join().expect("joins").expect("the write commits");
2399        });
2400        store.get(&who, found.uuid).expect("its object was kept");
2401    }
2402
2403    #[test]
2404    fn opening_removes_only_tenant_directories_with_no_row() {
2405        let mut f = fixture();
2406        let kept = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2407        let orphan = TenantId::generate();
2408        let tenants = f.tenants_dir();
2409        for name in [orphan.to_string(), "notes".to_owned()] {
2410            f.fs.create_dir_all(&tenants.join(name))
2411                .expect("a directory");
2412        }
2413        f.fs.sync_dir(&tenants).expect("sync");
2414        f.restart();
2415        assert_eq!(
2416            f.dirs(),
2417            [OsString::from(kept.to_string()), OsString::from("notes")]
2418        );
2419        drop(f.store(kept));
2420    }
2421
2422    /// The server's registry opens each tenant's Store with recovery, so a
2423    /// crash's leftovers in it go once the tenant is next used.
2424    #[test]
2425    fn a_servers_registry_opens_each_store_with_recovery() {
2426        let f = fixture();
2427        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2428        let objects = f.tenants_dir().join(id.to_string()).join("objects");
2429        let leftover = format!("{}.tmp", VersionId([0x0e; 16]));
2430        f.fs.write_new(&objects.join(&leftover), b"x")
2431            .expect("write");
2432        let tenants = f.open().expect("opens again");
2433        drop(tenants.store(id).expect("its store"));
2434        assert!(
2435            !f.fs
2436                .list(&objects)
2437                .expect("list")
2438                .contains(&OsString::from(leftover)),
2439            "the leftover is removed"
2440        );
2441    }
2442
2443    /// A command beside a running server must not take a create or a
2444    /// write the server has in progress for a crash's leftovers, in the
2445    /// registry or in a tenant's store.
2446    #[test]
2447    fn opening_beside_a_server_removes_nothing() {
2448        let f = fixture();
2449        let kept = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2450        let orphan = TenantId::generate();
2451        let tenants = f.tenants_dir();
2452        f.fs.create_dir_all(&tenants.join(orphan.to_string()))
2453            .expect("a directory");
2454        f.fs.sync_dir(&tenants).expect("sync");
2455        let in_progress = tenants
2456            .join(kept.to_string())
2457            .join("objects")
2458            .join(format!("{}.tmp", VersionId([0x0e; 16])));
2459        f.fs.write_new(&in_progress, b"x").expect("write");
2460        let beside =
2461            Tenants::open_beside(f.dir.path(), f.master.key(), f.fs.clone(), f.clock.clone())
2462                .expect("opens beside");
2463        let mut expected = [
2464            OsString::from(kept.to_string()),
2465            OsString::from(orphan.to_string()),
2466        ];
2467        expected.sort();
2468        assert_eq!(f.dirs(), expected);
2469        drop(beside.store(kept).expect("its store"));
2470        assert!(
2471            f.fs.list(in_progress.parent().expect("objects"))
2472                .expect("list")
2473                .contains(&OsString::from(in_progress.file_name().expect("name"))),
2474            "the write in progress stays"
2475        );
2476    }
2477
2478    /// The `synchronous` setting of a tenant catalog's connection: 1 is
2479    /// NORMAL (a group sync after COMMIT), 2 is FULL (COMMIT syncs).
2480    fn synchronous(store: &crate::store::Store) -> i64 {
2481        store
2482            .conn_for_test()
2483            .pragma_query_value(None, "synchronous", |r| r.get(0))
2484            .expect("reads synchronous")
2485    }
2486
2487    /// A tenant served from a data directory with local objects, the
2488    /// default, syncs its commits in groups: the serving open holds the
2489    /// directory and runs recovery. (Release 0.4.18 opened it as a command
2490    /// beside a server does, and every commit synced inside COMMIT.)
2491    #[test]
2492    fn a_served_tenant_with_local_objects_syncs_its_commits_in_groups() {
2493        let f = fixture();
2494        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2495        let store = f.tenants.store(id).expect("its store");
2496        assert_eq!(
2497            synchronous(&store),
2498            1,
2499            "NORMAL: the served tenant's commits share a group sync"
2500        );
2501    }
2502
2503    /// A tenant opened beside a server keeps synchronous FULL: its commits
2504    /// are durable before the server can read them.
2505    #[test]
2506    fn a_tenant_opened_beside_a_server_syncs_inside_commit() {
2507        let f = fixture();
2508        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2509        drop(f.tenants);
2510        let beside =
2511            Tenants::open_beside(f.dir.path(), f.master.key(), f.fs.clone(), f.clock.clone())
2512                .expect("opens beside");
2513        let store = beside.store(id).expect("its store");
2514        assert_eq!(
2515            synchronous(&store),
2516            2,
2517            "FULL: a command beside a server syncs inside COMMIT"
2518        );
2519    }
2520
2521    /// A served tenant's create waits for the group sync of its WAL, which
2522    /// the crash filesystem holds; under synchronous FULL no such sync is
2523    /// made and nothing would be held.
2524    #[test]
2525    fn a_served_tenant_s_create_waits_for_the_group_sync() {
2526        let f = fixture();
2527        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2528        let store = f.tenants.store(id).expect("its store");
2529        let caller = Caller {
2530            key: Key::generate().expect("caller key").id(),
2531        };
2532        let (found, body) = vcon("01a07da8-c2bb-83e5-b9a2-279e0d16bc07", "first");
2533        f.fs.hold_syncs();
2534        std::thread::scope(|t| {
2535            let creating = t.spawn(|| store.create(&caller, &found, &body));
2536            f.fs.await_held(1);
2537            assert!(!creating.is_finished(), "no answer while the sync is held");
2538            f.fs.release_syncs();
2539            assert!(
2540                matches!(creating.join().expect("ends"), Ok(Created::New(_))),
2541                "answered after the group sync"
2542            );
2543        });
2544    }
2545
2546    /// A caller with a key of its own, for a Store's writes.
2547    fn a_caller() -> Caller {
2548        Caller {
2549            key: Key::generate().expect("caller key").id(),
2550        }
2551    }
2552
2553    /// A vCon numbered `n`, with its body.
2554    fn numbered(n: usize, subject: &str) -> (vcon::read::Inspection, Vec<u8>) {
2555        vcon(&format!("01a07da8-c2bb-83e5-b9a2-27900000{n:04}"), subject)
2556    }
2557
2558    /// The WAL of tenant `id`, whose syncs the crash filesystem counts.
2559    fn wal_of(f: &Fixture, id: TenantId) -> PathBuf {
2560        f.tenants_dir()
2561            .join(id.to_string())
2562            .join("catalog.sqlite-wal")
2563    }
2564
2565    /// A served tenant, made, and its Store.
2566    fn served(f: &Fixture, name: &str) -> (TenantId, Arc<crate::store::Store>) {
2567        let id = f.tenants.create(Actor::Cli, name, None).expect("made");
2568        (id, f.tenants.store(id).expect("its store"))
2569    }
2570
2571    /// `writers` creates at once on one served tenant whose syncs are
2572    /// held: every one of them waits for a sync of the WAL, none is
2573    /// answered until the syncs go on, then each is. Returns the WAL syncs
2574    /// made, from the hold on.
2575    fn writers_at_once(writers: usize) -> usize {
2576        let f = fixture();
2577        let (id, store) = served(&f, "acme");
2578        let caller = a_caller();
2579        let vcons: Vec<_> = (0..writers).map(|n| numbered(n, "first")).collect();
2580        let before = f.fs.syncs(&wal_of(&f, id));
2581        f.fs.hold_syncs();
2582        std::thread::scope(|t| {
2583            let creating: Vec<_> = vcons
2584                .iter()
2585                .map(|(found, body)| t.spawn(|| store.create(&caller, found, body)))
2586                .collect();
2587            store.await_sync_waiters(writers);
2588            for c in &creating {
2589                assert!(!c.is_finished(), "no answer while the group sync is held");
2590            }
2591            f.fs.release_syncs();
2592            for c in creating {
2593                assert!(
2594                    matches!(c.join().expect("ends"), Ok(Created::New(_))),
2595                    "each answered after a sync that covers it"
2596                );
2597            }
2598        });
2599        f.fs.syncs(&wal_of(&f, id)) - before
2600    }
2601
2602    // Success: every serving open syncs its tenants' commits in groups.
2603
2604    #[test]
2605    fn a_registry_opened_in_a_data_directory_serves_for_group_sync() {
2606        let f = fixture();
2607        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2608        drop(f.tenants);
2609        let tenants = Tenants::open_in(
2610            f.dir.path(),
2611            f.master.key(),
2612            f.fs.clone(),
2613            f.clock.clone(),
2614            ObjectPlace::Local,
2615            &Catalogs::Local,
2616        )
2617        .expect("opens as a server does");
2618        assert_eq!(
2619            synchronous(&tenants.store(id).expect("its store")),
2620            1,
2621            "the server's opener: NORMAL, a group sync"
2622        );
2623    }
2624
2625    #[test]
2626    fn a_tenant_made_before_a_restart_is_served_for_group_sync() {
2627        let mut f = fixture();
2628        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2629        f.restart();
2630        assert_eq!(
2631            synchronous(&f.tenants.store(id).expect("its store")),
2632            1,
2633            "after the start: NORMAL"
2634        );
2635    }
2636
2637    #[test]
2638    fn the_sweep_s_recovery_keeps_a_served_tenant_on_group_sync() {
2639        let f = fixture();
2640        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2641        assert_eq!(f.tenants.recover_all(), Ok(0), "every tenant recovered");
2642        assert_eq!(
2643            synchronous(&f.tenants.store(id).expect("its store")),
2644            1,
2645            "the sweep opens the tenant as the server does"
2646        );
2647    }
2648
2649    #[test]
2650    fn one_writer_s_create_makes_two_group_syncs_of_its_tenant() {
2651        let f = fixture();
2652        let (id, store) = served(&f, "acme");
2653        let (found, body) = numbered(1, "first");
2654        let before = f.fs.syncs(&wal_of(&f, id));
2655        store.create(&a_caller(), &found, &body).expect("stored");
2656        assert_eq!(
2657            f.fs.syncs(&wal_of(&f, id)) - before,
2658            2,
2659            "its pending row's commit and its version's, each synced after COMMIT"
2660        );
2661    }
2662
2663    #[test]
2664    fn one_writer_waits_for_the_group_sync() {
2665        let made = writers_at_once(1);
2666        assert_eq!(made, 2, "one create: two commits, two syncs");
2667    }
2668
2669    #[test]
2670    fn two_writers_wait_for_the_group_sync_and_share_it() {
2671        let made = writers_at_once(2);
2672        assert!(
2673            (2..=4).contains(&made),
2674            "two creates: their syncs shared where they met, {made} made"
2675        );
2676    }
2677
2678    #[test]
2679    fn eight_writers_wait_for_the_group_sync_and_share_it() {
2680        let made = writers_at_once(8);
2681        // The held sync covers the first commit; one more covers the other
2682        // seven first commits; the last commits take at most one each.
2683        assert!(
2684            (2..=10).contains(&made),
2685            "eight creates: fewer syncs than their sixteen commits, {made} made"
2686        );
2687    }
2688
2689    #[test]
2690    fn a_served_tenant_s_replace_waits_for_the_group_sync() {
2691        let f = fixture();
2692        let (_, store) = served(&f, "acme");
2693        let caller = a_caller();
2694        let (found, body) = numbered(1, "first");
2695        let Ok(Created::New(first)) = store.create(&caller, &found, &body) else {
2696            panic!("a new vCon")
2697        };
2698        let (_, newer) = numbered(1, "second");
2699        f.fs.hold_syncs();
2700        std::thread::scope(|t| {
2701            let replacing = t.spawn(|| store.replace(&caller, first, &found, &newer));
2702            f.fs.await_held(1);
2703            assert!(!replacing.is_finished(), "no answer while the sync is held");
2704            f.fs.release_syncs();
2705            assert!(replacing.join().expect("ends").is_ok(), "replaced");
2706        });
2707    }
2708
2709    #[test]
2710    fn a_served_tenant_s_delete_waits_for_the_group_sync() {
2711        let f = fixture();
2712        let (_, store) = served(&f, "acme");
2713        let caller = a_caller();
2714        let (found, body) = numbered(1, "first");
2715        store.create(&caller, &found, &body).expect("stored");
2716        f.fs.hold_syncs();
2717        std::thread::scope(|t| {
2718            let deleting = t
2719                .spawn(|| store.delete(&caller, found.uuid, crate::retention::Retention::Years(7)));
2720            f.fs.await_held(1);
2721            assert!(!deleting.is_finished(), "no answer while the sync is held");
2722            f.fs.release_syncs();
2723            assert_eq!(deleting.join().expect("ends"), Ok(()), "deleted");
2724        });
2725    }
2726
2727    #[test]
2728    fn a_served_tenant_s_read_waits_for_the_group_sync_of_its_record() {
2729        let f = fixture();
2730        let (_, store) = served(&f, "acme");
2731        let caller = a_caller();
2732        let (found, body) = numbered(1, "first");
2733        store.create(&caller, &found, &body).expect("stored");
2734        f.fs.hold_syncs();
2735        std::thread::scope(|t| {
2736            let reading = t.spawn(|| store.get(&caller, found.uuid));
2737            f.fs.await_held(1);
2738            assert!(!reading.is_finished(), "no answer while the sync is held");
2739            f.fs.release_syncs();
2740            assert!(reading.join().expect("ends").is_ok(), "read");
2741        });
2742    }
2743
2744    // Failure: a served tenant's failed group sync is a commit whose
2745    // outcome is unknown, answered Io, and the tenant is refused until the
2746    // server starts again.
2747
2748    #[test]
2749    fn a_served_tenant_whose_group_sync_fails_answers_io() {
2750        let f = fixture();
2751        let (_, store) = served(&f, "acme");
2752        let (found, body) = numbered(1, "first");
2753        f.fs.fail_syncs();
2754        assert_eq!(
2755            store.create(&a_caller(), &found, &body).map(|_| ()),
2756            Err(StoreError::Io),
2757            "CommitError::Unknown: the commit may or may not be kept"
2758        );
2759    }
2760
2761    #[test]
2762    fn a_served_tenant_is_refused_after_a_failed_group_sync() {
2763        let f = fixture();
2764        let (_, store) = served(&f, "acme");
2765        let caller = a_caller();
2766        let (found, body) = numbered(1, "first");
2767        f.fs.fail_syncs();
2768        assert!(
2769            store.create(&caller, &found, &body).is_err(),
2770            "the sync failed"
2771        );
2772        f.fs.heal_syncs();
2773        let (other, other_body) = numbered(2, "second");
2774        assert_eq!(
2775            store.create(&caller, &other, &other_body).map(|_| ()),
2776            Err(StoreError::Io),
2777            "poisoned until the catalog is opened again"
2778        );
2779    }
2780
2781    /// A served open syncs the tenant's WAL before it serves anything: a
2782    /// WAL that cannot be synced leaves the tenant unserved.
2783    #[test]
2784    fn a_served_tenant_whose_wal_cannot_be_synced_at_open_is_not_served() {
2785        let mut f = fixture();
2786        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2787        f.restart();
2788        f.fs.fail_syncs();
2789        assert!(
2790            f.tenants.store(id).is_err(),
2791            "the open's sync of the WAL failed"
2792        );
2793    }
2794
2795    /// A create whose object cannot be written fails, and its tenant keeps
2796    /// serving with its group sync.
2797    #[test]
2798    fn a_served_tenant_s_create_whose_object_fails_leaves_it_served() {
2799        let f = fixture();
2800        let (_, store) = served(&f, "acme");
2801        let caller = a_caller();
2802        let (found, body) = numbered(1, "first");
2803        // The first change is the pending row's group sync; the second is
2804        // the object's write, which fails.
2805        f.fs.fail_from(f.fs.log().len() + 1);
2806        assert!(
2807            store.create(&caller, &found, &body).is_err(),
2808            "the write failed"
2809        );
2810        f.fs.revive();
2811        let (other, other_body) = numbered(2, "second");
2812        assert!(
2813            matches!(
2814                store.create(&caller, &other, &other_body),
2815                Ok(Created::New(_))
2816            ),
2817            "served again"
2818        );
2819        assert_eq!(synchronous(&store), 1, "still NORMAL");
2820    }
2821
2822    #[test]
2823    fn a_failed_group_sync_refuses_only_its_own_tenant() {
2824        let f = fixture();
2825        let (_, first) = served(&f, "acme");
2826        let (_, second) = served(&f, "globex");
2827        let caller = a_caller();
2828        let (found, body) = numbered(1, "first");
2829        f.fs.fail_syncs();
2830        assert!(
2831            first.create(&caller, &found, &body).is_err(),
2832            "the sync failed"
2833        );
2834        f.fs.heal_syncs();
2835        assert!(
2836            matches!(second.create(&caller, &found, &body), Ok(Created::New(_))),
2837            "another tenant has a WAL and a sync of its own"
2838        );
2839    }
2840
2841    #[test]
2842    fn a_served_tenant_s_read_whose_record_sync_fails_is_refused() {
2843        let f = fixture();
2844        let (_, store) = served(&f, "acme");
2845        let caller = a_caller();
2846        let (found, body) = numbered(1, "first");
2847        store.create(&caller, &found, &body).expect("stored");
2848        f.fs.fail_syncs();
2849        assert_eq!(
2850            store.get(&caller, found.uuid).map(|_| ()),
2851            Err(StoreError::Io),
2852            "a read whose record may be lost is not answered"
2853        );
2854    }
2855
2856    #[test]
2857    fn a_served_tenant_s_replace_whose_sync_fails_answers_io() {
2858        let f = fixture();
2859        let (_, store) = served(&f, "acme");
2860        let caller = a_caller();
2861        let (found, body) = numbered(1, "first");
2862        let Ok(Created::New(first)) = store.create(&caller, &found, &body) else {
2863            panic!("a new vCon")
2864        };
2865        let (_, newer) = numbered(1, "second");
2866        f.fs.fail_syncs();
2867        assert_eq!(
2868            store.replace(&caller, first, &found, &newer).map(|_| ()),
2869            Err(StoreError::Io),
2870            "the replace's outcome is unknown"
2871        );
2872    }
2873
2874    #[test]
2875    fn a_served_tenant_s_delete_whose_sync_fails_answers_io() {
2876        let f = fixture();
2877        let (_, store) = served(&f, "acme");
2878        let caller = a_caller();
2879        let (found, body) = numbered(1, "first");
2880        store.create(&caller, &found, &body).expect("stored");
2881        f.fs.fail_syncs();
2882        assert_eq!(
2883            store.delete(&caller, found.uuid, crate::retention::Retention::Years(7)),
2884            Err(StoreError::Io),
2885            "the delete's outcome is unknown"
2886        );
2887    }
2888
2889    #[test]
2890    fn a_served_tenant_s_close_after_a_failed_group_sync_says_so() {
2891        let f = fixture();
2892        let (_, store) = served(&f, "acme");
2893        let (found, body) = numbered(1, "first");
2894        f.fs.fail_syncs();
2895        assert!(
2896            store.create(&a_caller(), &found, &body).is_err(),
2897            "the sync failed"
2898        );
2899        assert_eq!(store.close(), Err(StoreError::Io), "a commit may be lost");
2900    }
2901
2902    #[test]
2903    fn a_restart_serves_a_tenant_again_after_its_failed_group_sync() {
2904        let mut f = fixture();
2905        let (id, store) = served(&f, "acme");
2906        let caller = a_caller();
2907        let (found, body) = numbered(1, "first");
2908        f.fs.fail_syncs();
2909        assert!(
2910            store.create(&caller, &found, &body).is_err(),
2911            "the sync failed"
2912        );
2913        drop(store);
2914        f.fs.heal_syncs();
2915        f.restart();
2916        let store = f.tenants.store(id).expect("its store");
2917        match store.get(&caller, found.uuid) {
2918            Ok(stored) => assert_eq!(stored.body, body, "whole"),
2919            Err(StoreError::NotFound) => {}
2920            other => panic!("half a vCon after the restart: {other:?}"),
2921        }
2922        let (other, other_body) = numbered(2, "second");
2923        assert!(
2924            matches!(
2925                store.create(&caller, &other, &other_body),
2926                Ok(Created::New(_))
2927            ),
2928            "served again"
2929        );
2930    }
2931
2932    #[test]
2933    fn the_sweep_counts_a_tenant_whose_recovery_sync_fails() {
2934        let f = fixture();
2935        f.tenants.create(Actor::Cli, "acme", None).expect("made");
2936        f.fs.fail_syncs();
2937        assert_eq!(
2938            f.tenants.recover_all(),
2939            Ok(1),
2940            "a tenant whose catalog cannot be synced is counted as not recovered"
2941        );
2942    }
2943
2944    // Edge: the openers beside a server, and more than one Store at once.
2945
2946    #[test]
2947    fn a_registry_opened_beside_in_a_data_directory_syncs_inside_commit() {
2948        let f = fixture();
2949        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2950        drop(f.tenants);
2951        let beside = Tenants::open_beside_in(
2952            f.dir.path(),
2953            f.master.key(),
2954            f.fs.clone(),
2955            f.clock.clone(),
2956            ObjectPlace::Local,
2957            &Catalogs::Local,
2958        )
2959        .expect("opens beside");
2960        assert_eq!(
2961            synchronous(&beside.store(id).expect("its store")),
2962            2,
2963            "FULL"
2964        );
2965    }
2966
2967    #[test]
2968    fn a_tenant_s_store_asked_for_twice_is_one_store_on_group_sync() {
2969        let f = fixture();
2970        let (id, first) = served(&f, "acme");
2971        let second = f.tenants.store(id).expect("its store again");
2972        assert!(Arc::ptr_eq(&first, &second), "one Store per tenant");
2973        assert_eq!(synchronous(&second), 1, "NORMAL");
2974    }
2975
2976    #[test]
2977    fn a_beside_tenant_s_create_waits_for_no_group_sync() {
2978        let f = fixture();
2979        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
2980        let wal = wal_of(&f, id);
2981        drop(f.tenants);
2982        let beside =
2983            Tenants::open_beside(f.dir.path(), f.master.key(), f.fs.clone(), f.clock.clone())
2984                .expect("opens beside");
2985        let store = beside.store(id).expect("its store");
2986        let (found, body) = numbered(1, "first");
2987        let before = f.fs.syncs(&wal);
2988        store.create(&a_caller(), &found, &body).expect("stored");
2989        assert_eq!(
2990            f.fs.syncs(&wal) - before,
2991            0,
2992            "FULL: SQLite syncs inside COMMIT, never through the group sync"
2993        );
2994    }
2995
2996    #[test]
2997    fn two_served_tenants_each_have_a_group_sync_of_their_own() {
2998        let f = fixture();
2999        let (_, first) = served(&f, "acme");
3000        let (_, second) = served(&f, "globex");
3001        let caller = a_caller();
3002        let (a, a_body) = numbered(1, "first");
3003        let (b, b_body) = numbered(2, "second");
3004        f.fs.hold_syncs();
3005        std::thread::scope(|t| {
3006            let one = t.spawn(|| first.create(&caller, &a, &a_body));
3007            let two = t.spawn(|| second.create(&caller, &b, &b_body));
3008            f.fs.await_held(2);
3009            f.fs.release_syncs();
3010            assert!(one.join().expect("ends").is_ok(), "the first tenant's");
3011            assert!(two.join().expect("ends").is_ok(), "the second tenant's");
3012        });
3013    }
3014
3015    #[test]
3016    fn a_served_and_a_beside_store_of_one_tenant_keep_their_own_settings() {
3017        let f = fixture();
3018        let (id, served_store) = served(&f, "acme");
3019        let beside =
3020            Tenants::open_beside(f.dir.path(), f.master.key(), f.fs.clone(), f.clock.clone())
3021                .expect("opens beside");
3022        let beside_store = beside.store(id).expect("its store");
3023        assert_eq!(synchronous(&served_store), 1, "the server's: NORMAL");
3024        assert_eq!(synchronous(&beside_store), 2, "the command's: FULL");
3025    }
3026
3027    #[test]
3028    fn an_unknown_tenant_has_no_store() {
3029        let f = fixture();
3030        assert_eq!(
3031            f.tenants.store(TenantId::generate()).err(),
3032            Some(TenantError::NotFound)
3033        );
3034    }
3035
3036    #[test]
3037    fn every_request_to_a_tenant_shares_one_store() {
3038        let f = fixture();
3039        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3040        let a = f.tenants.store(id).expect("a store");
3041        let b = f.tenants.store(id).expect("the same store");
3042        assert!(Arc::ptr_eq(&a, &b));
3043        let (found, body) = vcon(UUID, "first");
3044        a.create(&caller(), &found, &body).expect("stored");
3045        assert_eq!(b.get(&caller(), found.uuid).expect("read").body, body);
3046    }
3047
3048    /// The first request opens the Store; one arriving meanwhile waits for
3049    /// it rather than opening a second.
3050    #[test]
3051    fn a_store_is_opened_once_even_by_requests_at_the_same_time() {
3052        let f = fixture();
3053        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3054        let (opening, is_opening) = std::sync::mpsc::channel();
3055        let (go, wait) = std::sync::mpsc::channel::<()>();
3056        *f.tenants.hooks.opening.lock().expect("hook") = Some(Box::new(move || {
3057            opening.send(()).expect("send");
3058            wait.recv_timeout(std::time::Duration::from_secs(30))
3059                .expect("go");
3060        }));
3061        // Everything the threads wait on is moved into the scope, so a
3062        // failed assertion drops it and the threads end instead of hanging.
3063        let tenants = &f.tenants;
3064        std::thread::scope(move |s| {
3065            let first = s.spawn(move || tenants.store(id).expect("the first"));
3066            is_opening
3067                .recv_timeout(std::time::Duration::from_secs(10))
3068                .expect("the first is opening");
3069            let (second_done, second) = std::sync::mpsc::channel();
3070            s.spawn(move || {
3071                second_done
3072                    .send(tenants.store(id).expect("the second"))
3073                    .expect("send");
3074            });
3075            assert!(
3076                second
3077                    .recv_timeout(std::time::Duration::from_millis(100))
3078                    .is_err(),
3079                "the second waits while the first opens"
3080            );
3081            go.send(()).expect("go");
3082            let first = first.join().expect("the first returns");
3083            let second = second
3084                .recv_timeout(std::time::Duration::from_secs(30))
3085                .expect("the second returns");
3086            assert!(Arc::ptr_eq(&first, &second));
3087        });
3088    }
3089
3090    #[test]
3091    fn a_tenant_key_that_does_not_unwrap_opens_no_store() {
3092        let f = fixture();
3093        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3094        f.conn()
3095            .execute(
3096                "UPDATE tenant SET wrapped_tenant_key = x'00' WHERE id = ?1",
3097                [id.0],
3098            )
3099            .expect("damage the wrapped key");
3100        assert_eq!(f.tenants.store(id).err(), Some(TenantError::Io));
3101    }
3102
3103    #[test]
3104    fn draining_refuses_new_requests_and_waits_for_those_in_flight() {
3105        let f = fixture();
3106        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3107        let (found, body) = vcon(UUID, "first");
3108        let held = f.tenants.store(id).expect("a request in flight");
3109        std::thread::scope(|s| {
3110            let (done, drained) = std::sync::mpsc::channel();
3111            let tenants = &f.tenants;
3112            s.spawn(move || {
3113                tenants.drain(id).expect("drains");
3114                done.send(()).expect("send");
3115            });
3116            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
3117            while f.tenants.store(id).is_ok() {
3118                assert!(std::time::Instant::now() < deadline, "never closing");
3119                std::thread::yield_now();
3120            }
3121            assert_eq!(f.tenants.store(id).err(), Some(TenantError::Closing));
3122            assert!(
3123                drained
3124                    .recv_timeout(std::time::Duration::from_millis(100))
3125                    .is_err(),
3126                "the drain waits for the request in flight"
3127            );
3128            held.create(&caller(), &found, &body)
3129                .expect("the request in flight finishes");
3130            drop(held);
3131            drained
3132                .recv_timeout(std::time::Duration::from_secs(30))
3133                .expect("the drain ends once the last handle is dropped");
3134        });
3135        assert_eq!(f.tenants.store(id).err(), Some(TenantError::Closing));
3136    }
3137
3138    #[test]
3139    fn a_tenant_no_request_opened_drains_at_once() {
3140        let f = fixture();
3141        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3142        f.tenants.drain(id).expect("drains");
3143        assert_eq!(f.tenants.store(id).err(), Some(TenantError::Closing));
3144    }
3145
3146    impl Fixture {
3147        /// The tenant's own retention period, as its row holds it.
3148        fn own_retention(&self, id: TenantId) -> Option<String> {
3149            self.conn()
3150                .query_row("SELECT retention FROM tenant WHERE id = ?1", [id.0], |r| {
3151                    r.get(0)
3152                })
3153                .expect("a row")
3154        }
3155
3156        /// A second connection to the tenant's catalog.
3157        pub(crate) fn tenant_catalog(&self, id: TenantId) -> Connection {
3158            let catalog_key = envelope::catalog_key(&self.tenant_key(id)).expect("catalog key");
3159            catalog::open(
3160                &self
3161                    .tenants_dir()
3162                    .join(id.to_string())
3163                    .join("catalog.sqlite"),
3164                &catalog_key,
3165                "",
3166            )
3167            .expect("the tenant's catalog")
3168        }
3169
3170        /// The records with this action in the admin log.
3171        pub(crate) fn admin_records(&self, action: &str) -> Vec<Value> {
3172            self.admin_log()
3173                .into_iter()
3174                .filter(|r| r["action"] == action)
3175                .collect()
3176        }
3177    }
3178
3179    /// The rule the sweep and `check` both apply.
3180    #[test]
3181    fn retention_falls_back_to_the_server_default_when_unset() {
3182        let info = |retention| TenantInfo {
3183            id: TenantId([1; 16]),
3184            name: "acme".to_owned(),
3185            retention,
3186            metadata: Metadata::None,
3187            created_at: datetime!(2026-10-23 12:00 UTC),
3188        };
3189        assert_eq!(
3190            info(None).kept_for(Retention::Years(7)),
3191            Retention::Years(7)
3192        );
3193        assert_eq!(
3194            info(Some(Retention::Days(90))).kept_for(Retention::Years(7)),
3195            Retention::Days(90)
3196        );
3197    }
3198
3199    #[test]
3200    fn a_tenant_retention_is_read_afresh_and_not_recorded() {
3201        let f = fixture();
3202        let lab = f
3203            .tenants
3204            .create(Actor::Cli, "lab", Some(Retention::Months(18)))
3205            .expect("made");
3206        let acme = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3207        let records = f.tenants.admin_records().len();
3208
3209        assert_eq!(f.tenants.retention(lab), Ok(Some(Retention::Months(18))));
3210        assert_eq!(f.tenants.retention(acme), Ok(None));
3211        f.tenants
3212            .set_retention(Actor::Cli, acme, Some(Retention::Days(0)))
3213            .expect("changed");
3214        assert_eq!(f.tenants.retention(acme), Ok(Some(Retention::Days(0))));
3215        assert_eq!(
3216            f.tenants.retention(TenantId([0xee; 16])),
3217            Err(TenantError::NotFound)
3218        );
3219        assert_eq!(
3220            f.tenants.admin_records().len(),
3221            records + 1,
3222            "only the retention change is recorded"
3223        );
3224        f.tenants
3225            .conn_for_test()
3226            .execute("UPDATE tenant SET retention = '7w' WHERE id = ?1", [lab.0])
3227            .expect("damaged");
3228        assert_eq!(
3229            f.tenants.retention(lab),
3230            Err(TenantError::Io),
3231            "a period that does not read back is damage"
3232        );
3233    }
3234
3235    #[test]
3236    fn ids_names_every_tenant_and_records_nothing() {
3237        let f = fixture();
3238        let a = f.tenants.create(Actor::Cli, "a", None).expect("made");
3239        let b = f.tenants.create(Actor::Cli, "b", None).expect("made");
3240        let records = f.tenants.admin_records().len();
3241
3242        let mut ids = f.tenants.ids().expect("ids");
3243        ids.sort_by_key(|id| id.0);
3244        let mut made = vec![a, b];
3245        made.sort_by_key(|id| id.0);
3246
3247        assert_eq!(ids, made);
3248        assert_eq!(f.tenants.admin_records().len(), records, "nothing recorded");
3249    }
3250
3251    #[test]
3252    fn list_shows_every_tenant_by_name_and_is_recorded() {
3253        let f = fixture();
3254        assert_eq!(f.tenants.list(Actor::Cli), Ok(Vec::new()));
3255        let lab = f
3256            .tenants
3257            .create(Actor::Cli, "lab", Some(Retention::Days(90)))
3258            .expect("made");
3259        f.clock.set(datetime!(2026-10-23 13:00 UTC));
3260        let acme = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3261        assert_eq!(
3262            f.tenants.list(Actor::Cli),
3263            Ok(vec![
3264                TenantInfo {
3265                    id: acme,
3266                    name: "acme".to_owned(),
3267                    retention: None,
3268                    metadata: Metadata::None,
3269                    created_at: datetime!(2026-10-23 13:00 UTC),
3270                },
3271                TenantInfo {
3272                    id: lab,
3273                    name: "lab".to_owned(),
3274                    retention: Some(Retention::Days(90)),
3275                    metadata: Metadata::None,
3276                    created_at: datetime!(2026-10-23 12:00 UTC),
3277                },
3278            ])
3279        );
3280        let lists = f.admin_records("tenant_list");
3281        assert_eq!(lists.len(), 2, "one record per list");
3282        for record in lists {
3283            assert_eq!(record["actor"], "cli");
3284            assert_eq!(record["status"], 200);
3285            assert_eq!(record["target"], Value::Null);
3286        }
3287    }
3288
3289    #[test]
3290    fn a_stored_period_that_does_not_read_back_is_damage() {
3291        let f = fixture();
3292        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3293        f.conn()
3294            .execute("UPDATE tenant SET retention = '7w' WHERE id = ?1", [id.0])
3295            .expect("damage the period");
3296        assert_eq!(f.tenants.list(Actor::Cli), Err(TenantError::Io));
3297    }
3298
3299    #[test]
3300    fn a_list_whose_record_fails_shows_nothing() {
3301        let f = fixture();
3302        f.tenants.create(Actor::Cli, "acme", None).expect("made");
3303        f.conn()
3304            .execute_batch(
3305                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
3306                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
3307            )
3308            .expect("trigger");
3309        assert_eq!(f.tenants.list(Actor::Cli), Err(TenantError::AuditFailed));
3310    }
3311
3312    #[test]
3313    fn a_retention_change_is_kept_and_recorded_in_both_logs() {
3314        let f = fixture();
3315        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3316        f.clock.set(datetime!(2026-10-23 13:00 UTC));
3317        f.tenants
3318            .set_retention(Actor::Cli, id, Some(Retention::Months(18)))
3319            .expect("set");
3320        assert_eq!(f.own_retention(id).as_deref(), Some("18m"));
3321        f.tenants
3322            .set_retention(Actor::Cli, id, None)
3323            .expect("back to the default");
3324        assert_eq!(f.own_retention(id), None);
3325
3326        let admin = f.admin_records("tenant_retention");
3327        assert_eq!(admin.len(), 2);
3328        for record in &admin {
3329            assert_eq!(record["actor"], "cli");
3330            assert_eq!(record["target"], id.to_string());
3331            assert_eq!(record["status"], 200);
3332            assert_eq!(record["at"], "2026-10-23T13:00:00Z");
3333        }
3334        let copies: Vec<Value> = exported(&f.tenant_catalog(id), None)
3335            .into_iter()
3336            .filter(|r| r["action"] == "retention")
3337            .collect();
3338        assert_eq!(copies.len(), 2, "a copy in the tenant's log for each");
3339        for record in &copies {
3340            assert_eq!(record["actor"], "cli");
3341            assert_eq!(record["target"], id.to_string());
3342            assert_eq!(record["status"], 200);
3343        }
3344    }
3345
3346    impl Fixture {
3347        /// The tenant's metadata level, as its row holds it.
3348        fn own_metadata(&self, id: TenantId) -> Option<String> {
3349            self.conn()
3350                .query_row("SELECT metadata FROM tenant WHERE id = ?1", [id.0], |r| {
3351                    r.get(0)
3352                })
3353                .expect("a row")
3354        }
3355    }
3356
3357    /// A tenant's level is `none` until set; a change is kept, shown in
3358    /// the list, and recorded in the admin log and the tenant's own.
3359    #[test]
3360    fn a_metadata_level_is_none_until_set_and_each_change_is_recorded() {
3361        let f = fixture();
3362        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3363        assert_eq!(
3364            f.tenants.metadata(id),
3365            Ok(Metadata::None),
3366            "a new tenant is at none"
3367        );
3368        assert_eq!(f.own_metadata(id), None, "NULL is none");
3369        f.clock.set(datetime!(2026-10-23 13:00 UTC));
3370        f.tenants
3371            .set_metadata(Actor::Cli, id, Metadata::Full)
3372            .expect("set");
3373        assert_eq!(f.tenants.metadata(id), Ok(Metadata::Full), "the level set");
3374        assert_eq!(
3375            f.own_metadata(id).as_deref(),
3376            Some("full"),
3377            "the row holds the level's name"
3378        );
3379        let listed = f.tenants.list(Actor::Cli).expect("lists");
3380        assert_eq!(listed[0].to_json()["metadata"], "full", "shown in the list");
3381        f.tenants
3382            .set_metadata(Actor::Cli, id, Metadata::None)
3383            .expect("back to none");
3384        assert_eq!(f.own_metadata(id), None, "none is NULL again");
3385        assert_eq!(f.tenants.metadata(id), Ok(Metadata::None), "back to none");
3386
3387        let admin = f.admin_records("tenant_metadata");
3388        assert_eq!(admin.len(), 2, "one admin record per change");
3389        for record in &admin {
3390            assert_eq!(record["actor"], "cli", "the command line made the change");
3391            assert_eq!(
3392                record["target"],
3393                id.to_string(),
3394                "the record names the tenant"
3395            );
3396            assert_eq!(record["status"], 200, "the change succeeded");
3397            assert_eq!(record["at"], "2026-10-23T13:00:00Z", "at the clock's time");
3398        }
3399        let copies: Vec<Value> = exported(&f.tenant_catalog(id), None)
3400            .into_iter()
3401            .filter(|r| r["action"] == "metadata")
3402            .collect();
3403        assert_eq!(copies.len(), 2, "a copy in the tenant's log for each");
3404    }
3405
3406    #[test]
3407    fn a_metadata_change_for_an_unknown_or_closing_tenant_is_refused() {
3408        let f = fixture();
3409        let unknown = TenantId::generate();
3410        assert_eq!(
3411            f.tenants
3412                .set_metadata(Actor::Cli, unknown, Metadata::Counts),
3413            Err(TenantError::NotFound),
3414            "no tenant has the id"
3415        );
3416        assert_eq!(
3417            f.tenants.metadata(unknown),
3418            Err(TenantError::NotFound),
3419            "nor a level"
3420        );
3421        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3422        f.tenants.drain(id).expect("drains");
3423        assert_eq!(
3424            f.tenants.set_metadata(Actor::Cli, id, Metadata::Counts),
3425            Err(TenantError::Closing),
3426            "a closing tenant's level does not change"
3427        );
3428        assert_eq!(f.own_metadata(id), None, "unchanged");
3429        let statuses: Vec<Value> = f
3430            .admin_records("tenant_metadata")
3431            .iter()
3432            .map(|r| r["status"].clone())
3433            .collect();
3434        assert_eq!(
3435            statuses,
3436            [404, 503],
3437            "both refusals are recorded, each with its status"
3438        );
3439    }
3440
3441    /// A level this build does not know is damage, never taken as `none`.
3442    #[test]
3443    fn a_stored_metadata_level_this_build_does_not_know_is_an_error() {
3444        let f = fixture();
3445        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3446        f.conn()
3447            .execute("UPDATE tenant SET metadata = 'most' WHERE id = ?1", [id.0])
3448            .expect("update");
3449        assert_eq!(
3450            f.tenants.metadata(id),
3451            Err(TenantError::Io),
3452            "an unknown level is an error"
3453        );
3454    }
3455
3456    /// A registry made at schema version 2 gains the column at version 3,
3457    /// every tenant at `none`; one made at version 1 does too.
3458    #[test]
3459    fn an_older_registry_gains_the_metadata_column() {
3460        for from in [1, 2] {
3461            let mut f = fixture();
3462            let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3463            f.conn()
3464                .execute_batch(&format!(
3465                    "ALTER TABLE tenant DROP COLUMN pending_wrapped_kek;
3466                     ALTER TABLE tenant DROP COLUMN pending_wrap_ref;
3467                     ALTER TABLE tenant DROP COLUMN wrapped_kek;
3468                     ALTER TABLE tenant DROP COLUMN wrap_ref;
3469                     ALTER TABLE tenant DROP COLUMN role_cap;
3470                     ALTER TABLE tenant DROP COLUMN metadata; DROP TABLE membership;
3471                     DROP TABLE user_account; DROP TABLE tenant_setting;
3472                     DROP TABLE session;
3473                     ALTER TABLE api_key DROP COLUMN last_used_at;
3474                     ALTER TABLE api_key DROP COLUMN expires_at;
3475                     PRAGMA user_version = {from};"
3476                ))
3477                .expect("back to the old schema");
3478            f.restart();
3479            let version: i64 = f
3480                .conn()
3481                .pragma_query_value(None, "user_version", |r| r.get(0))
3482                .expect("version");
3483            assert_eq!(version, catalog::SCHEMA_VERSION, "from {from}");
3484            assert_eq!(f.tenants.metadata(id), Ok(Metadata::None), "from {from}");
3485            f.tenants
3486                .set_metadata(Actor::Cli, id, Metadata::Counts)
3487                .expect("the column is there");
3488        }
3489    }
3490
3491    #[test]
3492    fn a_retention_change_for_an_unknown_tenant_is_not_found() {
3493        let f = fixture();
3494        let id = TenantId::generate();
3495        assert_eq!(
3496            f.tenants
3497                .set_retention(Actor::Cli, id, Some(Retention::Years(1))),
3498            Err(TenantError::NotFound)
3499        );
3500        let admin = f.admin_records("tenant_retention");
3501        assert_eq!(admin.len(), 1);
3502        assert_eq!(admin[0]["status"], 404);
3503        assert_eq!(admin[0]["target"], id.to_string());
3504    }
3505
3506    #[test]
3507    fn a_retention_change_for_a_closing_tenant_is_refused() {
3508        let f = fixture();
3509        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3510        f.tenants.drain(id).expect("drains");
3511        assert_eq!(
3512            f.tenants
3513                .set_retention(Actor::Cli, id, Some(Retention::Years(1))),
3514            Err(TenantError::Closing)
3515        );
3516        assert_eq!(f.own_retention(id), None, "unchanged");
3517        assert_eq!(f.admin_records("tenant_retention")[0]["status"], 503);
3518    }
3519
3520    #[test]
3521    fn a_retention_change_whose_admin_record_fails_changes_nothing() {
3522        let f = fixture();
3523        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3524        f.conn()
3525            .execute_batch(
3526                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
3527                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
3528            )
3529            .expect("trigger");
3530        assert_eq!(
3531            f.tenants
3532                .set_retention(Actor::Cli, id, Some(Retention::Years(1))),
3533            Err(TenantError::AuditFailed)
3534        );
3535        assert_eq!(f.own_retention(id), None, "unchanged");
3536        let copies = exported(&f.tenant_catalog(id), None)
3537            .into_iter()
3538            .filter(|r| r["action"] == "retention")
3539            .count();
3540        assert_eq!(copies, 0, "no copy of a change that was not made");
3541    }
3542
3543    /// The change commits with its admin record; a failed copy in the
3544    /// tenant's log leaves the change standing and answers AuditFailed.
3545    #[test]
3546    fn a_retention_change_whose_tenant_copy_fails_stands() {
3547        let f = fixture();
3548        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3549        f.tenant_catalog(id)
3550            .execute_batch(
3551                "CREATE TRIGGER dead BEFORE INSERT ON audit
3552                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
3553            )
3554            .expect("trigger");
3555        assert_eq!(
3556            f.tenants
3557                .set_retention(Actor::Cli, id, Some(Retention::Years(10))),
3558            Err(TenantError::AuditFailed)
3559        );
3560        assert_eq!(
3561            f.own_retention(id).as_deref(),
3562            Some("10y"),
3563            "the change stands"
3564        );
3565        assert_eq!(f.admin_records("tenant_retention")[0]["status"], 200);
3566    }
3567
3568    /// A tenant with one vCon stored.
3569    fn with_vcon(f: &Fixture) -> TenantId {
3570        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3571        let (found, body) = vcon(UUID, "first");
3572        f.tenants
3573            .store(id)
3574            .expect("its store")
3575            .create(&caller(), &found, &body)
3576            .expect("stored");
3577        id
3578    }
3579
3580    fn hold(f: &Fixture, id: TenantId) {
3581        f.tenant_catalog(id)
3582            .execute("UPDATE vcon SET hold = 1", [])
3583            .expect("a hold");
3584    }
3585
3586    /// Waits until the tenant refuses new requests.
3587    fn until_closing(f: &Fixture, id: TenantId) {
3588        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
3589        while f.tenants.store(id).is_ok() {
3590            assert!(std::time::Instant::now() < deadline, "never closing");
3591            std::thread::yield_now();
3592        }
3593    }
3594
3595    #[test]
3596    fn a_tenant_already_closing_cannot_be_drained_again() {
3597        let f = fixture();
3598        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3599        f.tenants.drain(id).expect("drains");
3600        assert_eq!(f.tenants.drain(id).err(), Some(TenantError::Closing));
3601    }
3602
3603    #[test]
3604    fn removing_an_unknown_tenant_is_not_found() {
3605        let f = fixture();
3606        let id = TenantId::generate();
3607        assert_eq!(
3608            f.tenants.remove(Actor::Cli, id, Removal::Empty),
3609            Err(TenantError::NotFound)
3610        );
3611        assert_eq!(f.tenants.store(id).err(), Some(TenantError::NotFound));
3612        let records = f.admin_records("tenant_remove");
3613        assert_eq!(records.len(), 1);
3614        assert_eq!(records[0]["status"], 404);
3615        assert_eq!(records[0]["target"], id.to_string());
3616    }
3617
3618    #[test]
3619    fn an_empty_tenant_is_removed_with_its_key_directory_and_row() {
3620        let f = fixture();
3621        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3622        drop(f.tenants.store(id).expect("opened by a request"));
3623        f.clock.set(datetime!(2026-10-23 13:00 UTC));
3624        f.tenants
3625            .remove(Actor::Cli, id, Removal::Empty)
3626            .expect("removed");
3627        assert!(!f.has_row(id), "its row and wrapped key are gone");
3628        assert_eq!(f.tenants.store(id).err(), Some(TenantError::NotFound));
3629        assert_eq!(f.dirs(), Vec::<OsString>::new(), "its directory is gone");
3630        assert_eq!(f.tenants.list(Actor::Cli), Ok(Vec::new()));
3631        let records = f.admin_records("tenant_remove");
3632        assert_eq!(records.len(), 1);
3633        assert_eq!(records[0]["actor"], "cli");
3634        assert_eq!(records[0]["target"], id.to_string());
3635        assert_eq!(records[0]["status"], 204);
3636        assert_eq!(records[0]["at"], "2026-10-23T13:00:00Z");
3637    }
3638
3639    #[test]
3640    fn an_empty_removal_is_refused_while_any_version_is_kept() {
3641        let f = fixture();
3642        let id = with_vcon(&f);
3643        let uuid = vcon(UUID, "first").0.uuid;
3644        f.tenants
3645            .store(id)
3646            .expect("its store")
3647            .delete(&caller(), uuid, Retention::Years(7))
3648            .expect("deleted, so only a hidden version is kept");
3649        assert_eq!(
3650            f.tenants.remove(Actor::Cli, id, Removal::Empty),
3651            Err(TenantError::HoldsVcons)
3652        );
3653        assert!(f.has_row(id));
3654        let store = f.tenants.store(id).expect("still served");
3655        assert_eq!(store.counts().map(|c| c.versions), Ok(1));
3656        assert_eq!(f.admin_records("tenant_remove")[0]["status"], 409);
3657    }
3658
3659    #[test]
3660    fn a_forced_removal_takes_the_vcons_too() {
3661        let f = fixture();
3662        let id = with_vcon(&f);
3663        f.tenants
3664            .remove(Actor::Cli, id, Removal::Force)
3665            .expect("removed");
3666        assert!(!f.has_row(id));
3667        assert_eq!(f.dirs(), Vec::<OsString>::new());
3668    }
3669
3670    #[test]
3671    fn a_forced_removal_is_refused_while_a_uuid_is_held() {
3672        let f = fixture();
3673        let id = with_vcon(&f);
3674        hold(&f, id);
3675        assert_eq!(
3676            f.tenants.remove(Actor::Cli, id, Removal::Force),
3677            Err(TenantError::UnderHold)
3678        );
3679        assert!(f.has_row(id));
3680        assert!(f.tenants.store(id).is_ok(), "still served");
3681        assert_eq!(f.admin_records("tenant_remove")[0]["status"], 409);
3682    }
3683
3684    #[test]
3685    fn overriding_holds_removes_a_held_tenant() {
3686        let f = fixture();
3687        let id = with_vcon(&f);
3688        hold(&f, id);
3689        f.tenants
3690            .remove(Actor::Cli, id, Removal::ForceOverridingHolds)
3691            .expect("removed");
3692        assert!(!f.has_row(id));
3693        assert_eq!(f.dirs(), Vec::<OsString>::new());
3694    }
3695
3696    /// The removal drains before it looks, so a write that lands meanwhile
3697    /// makes the tenant non-empty and the removal is refused: the write
3698    /// is never acknowledged and then lost.
3699    #[test]
3700    fn a_write_in_flight_during_an_empty_removal_is_kept() {
3701        let f = fixture();
3702        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3703        let (found, body) = vcon(UUID, "first");
3704        let held = f.tenants.store(id).expect("a request in flight");
3705        let tenants = &f.tenants;
3706        let fx = &f;
3707        let (found_ref, body_ref) = (&found, &body);
3708        let result = std::thread::scope(move |s| {
3709            let (done, removed) = std::sync::mpsc::channel();
3710            s.spawn(move || {
3711                done.send(tenants.remove(Actor::Cli, id, Removal::Empty))
3712                    .expect("send");
3713            });
3714            until_closing(fx, id);
3715            assert!(
3716                removed
3717                    .recv_timeout(std::time::Duration::from_millis(100))
3718                    .is_err(),
3719                "the removal waits for the write"
3720            );
3721            held.create(&caller(), found_ref, body_ref)
3722                .expect("the write is acknowledged");
3723            drop(held);
3724            removed
3725                .recv_timeout(std::time::Duration::from_secs(30))
3726                .expect("the removal ends")
3727        });
3728        assert_eq!(result, Err(TenantError::HoldsVcons));
3729        assert_eq!(
3730            f.tenants
3731                .store(id)
3732                .expect("still served")
3733                .get(&caller(), found.uuid)
3734                .expect("the write is kept")
3735                .body,
3736            body
3737        );
3738    }
3739
3740    #[test]
3741    fn a_second_removal_while_one_drains_is_refused() {
3742        let f = fixture();
3743        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3744        let held = f.tenants.store(id).expect("a request in flight");
3745        let tenants = &f.tenants;
3746        let fx = &f;
3747        std::thread::scope(move |s| {
3748            let first = s.spawn(move || tenants.remove(Actor::Cli, id, Removal::Force));
3749            until_closing(fx, id);
3750            assert_eq!(
3751                fx.tenants.remove(Actor::Cli, id, Removal::Empty),
3752                Err(TenantError::Closing)
3753            );
3754            drop(held);
3755            assert_eq!(first.join().expect("the first returns"), Ok(()));
3756        });
3757        let statuses: Vec<Value> = f
3758            .admin_records("tenant_remove")
3759            .into_iter()
3760            .map(|r| r["status"].clone())
3761            .collect();
3762        assert_eq!(statuses, [503, 204]);
3763    }
3764
3765    #[test]
3766    fn a_removal_whose_record_fails_removes_nothing() {
3767        let f = fixture();
3768        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3769        f.conn()
3770            .execute_batch(
3771                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
3772                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
3773            )
3774            .expect("trigger");
3775        assert_eq!(
3776            f.tenants.remove(Actor::Cli, id, Removal::Empty),
3777            Err(TenantError::AuditFailed)
3778        );
3779        assert!(f.has_row(id));
3780        assert_eq!(f.dirs().len(), 1);
3781        assert!(f.tenants.store(id).is_ok(), "served again");
3782    }
3783
3784    /// The row's commit is the removal; a directory a crash leaves after
3785    /// it goes at the next start.
3786    #[test]
3787    fn a_removal_cut_off_after_its_commit_finishes_at_the_next_start() {
3788        let mut f = fixture();
3789        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3790        drop(f.tenants.store(id).expect("opened by a request"));
3791        f.fs.fail_from(f.fs.log().len());
3792        assert_eq!(f.tenants.remove(Actor::Cli, id, Removal::Empty), Ok(()));
3793        assert_eq!(f.dirs().len(), 1, "the dead process removed nothing");
3794        f.restart();
3795        assert!(!f.has_row(id));
3796        assert_eq!(f.dirs(), Vec::<OsString>::new());
3797    }
3798
3799    #[test]
3800    fn removal_deletes_the_directory_on_disk() {
3801        let dir = tempfile::tempdir().expect("temp dir");
3802        let tenants = Tenants::open(
3803            dir.path(),
3804            Master::new().key(),
3805            Arc::new(crate::fs::OsFs),
3806            Arc::new(ManualClock::at(datetime!(2026-10-23 12:00 UTC))),
3807        )
3808        .expect("opens");
3809        let id = tenants.create(Actor::Cli, "acme", None).expect("made");
3810        let tenant_dir = dir.path().join("tenants").join(id.to_string());
3811        assert!(tenant_dir.join("catalog.sqlite").is_file());
3812        tenants
3813            .remove(Actor::Cli, id, Removal::Empty)
3814            .expect("removed");
3815        assert!(!tenant_dir.exists());
3816    }
3817
3818    #[test]
3819    fn two_tenants_keep_the_same_uuid_apart() {
3820        let f = fixture();
3821        let a = f.tenants.create(Actor::Cli, "a", None).expect("made");
3822        let b = f.tenants.create(Actor::Cli, "b", None).expect("made");
3823        let (found, kept_by_a) = vcon(UUID, "kept by a");
3824        let (_, kept_by_b) = vcon(UUID, "kept by b");
3825        let (store_a, store_b) = (
3826            f.tenants.store(a).expect("a's store"),
3827            f.tenants.store(b).expect("b's store"),
3828        );
3829        assert!(matches!(
3830            store_a.create(&caller(), &found, &kept_by_a),
3831            Ok(Created::New(_))
3832        ));
3833        assert!(matches!(
3834            store_b.create(&caller(), &found, &kept_by_b),
3835            Ok(Created::New(_))
3836        ));
3837        let read = |store: &Store| store.get(&caller(), found.uuid).map(|s| s.body);
3838        assert_eq!(read(&store_a), Ok(kept_by_a));
3839        assert_eq!(read(&store_b), Ok(kept_by_b.clone()));
3840        store_a
3841            .delete(&caller(), found.uuid, Retention::Years(7))
3842            .expect("a deletes its own");
3843        assert_eq!(read(&store_a), Err(StoreError::Gone));
3844        assert_eq!(read(&store_b), Ok(kept_by_b), "b's is untouched");
3845    }
3846
3847    /// A version's data key is wrapped for its tenant by id, so the
3848    /// tenant's Store must be opened under that id.
3849    #[test]
3850    fn a_tenants_data_keys_are_bound_to_its_own_id() {
3851        let f = fixture();
3852        let id = f.tenants.create(Actor::Cli, "acme", None).expect("made");
3853        let (found, body) = vcon(UUID, "first");
3854        let Ok(Created::New(version)) =
3855            f.tenants
3856                .store(id)
3857                .expect("its store")
3858                .create(&caller(), &found, &body)
3859        else {
3860            panic!("a new vCon")
3861        };
3862        let wrapped: Vec<u8> = f
3863            .tenant_catalog(id)
3864            .query_row(
3865                "SELECT wrapped_key FROM version WHERE version = ?1",
3866                [version.0],
3867                |r| r.get(0),
3868            )
3869            .expect("its row");
3870        let ctx = Context::Version {
3871            tenant: id,
3872            uuid: found.uuid,
3873            version,
3874        };
3875        assert!(envelope::unwrap(&f.tenant_key(id), &ctx, &wrapped).is_ok());
3876    }
3877
3878    /// The answers one tenant gets for a uuid, whatever another holds.
3879    fn answers(store: &Store) -> Vec<String> {
3880        let (found, body) = vcon(UUID, "b's own");
3881        let (_, newer) = vcon(UUID, "b's newer");
3882        let kind = |r: Result<Created, StoreError>| match r {
3883            Ok(Created::New(_)) => "new".to_owned(),
3884            Ok(Created::Same(_)) => "same".to_owned(),
3885            Err(e) => format!("{e:?}"),
3886        };
3887        let who = caller();
3888        let mut answers = vec![
3889            format!("{:?}", store.get(&who, found.uuid).map(|_| ())),
3890            format!("{:?}", store.delete(&who, found.uuid, Retention::Years(7))),
3891            kind(store.create(&who, &found, &body)),
3892            kind(store.create(&who, &found, &body)),
3893        ];
3894        let current = store.get(&who, found.uuid).expect("stored").version;
3895        answers.push(format!(
3896            "{:?}",
3897            store.replace(&who, current, &found, &newer).map(|_| ())
3898        ));
3899        answers.push(format!(
3900            "{:?}",
3901            store.delete(&who, found.uuid, Retention::Years(7))
3902        ));
3903        answers.push(format!("{:?}", store.get(&who, found.uuid).map(|_| ())));
3904        answers
3905    }
3906
3907    #[test]
3908    fn nothing_one_tenant_does_shows_whether_another_holds_a_uuid() {
3909        let alone = fixture();
3910        let b = alone.tenants.create(Actor::Cli, "b", None).expect("made");
3911        let expected = answers(&alone.tenants.store(b).expect("b's store"));
3912
3913        let f = fixture();
3914        let a = f.tenants.create(Actor::Cli, "a", None).expect("made");
3915        let b = f.tenants.create(Actor::Cli, "b", None).expect("made");
3916        let store_a = f.tenants.store(a).expect("a's store");
3917        let (found, body) = vcon(UUID, "a's");
3918        store_a
3919            .create(&caller(), &found, &body)
3920            .expect("a holds it");
3921        let (other, body) = vcon("01a07da8-c2bb-83e5-b9a2-279e0d16bc47", "a's other");
3922        store_a.create(&caller(), &other, &body).expect("stored");
3923        store_a
3924            .delete(&caller(), other.uuid, Retention::Years(7))
3925            .expect("and has deleted another");
3926        assert_eq!(answers(&f.tenants.store(b).expect("b's store")), expected);
3927        assert_eq!(
3928            expected,
3929            [
3930                "Err(NotFound)",
3931                "Err(NotFound)",
3932                "new",
3933                "same",
3934                "Ok(())",
3935                "Ok(())",
3936                "Err(Gone)"
3937            ]
3938        );
3939    }
3940}