Skip to main content

vcon_server/
serve.rs

1//! `vcon-server serve`: the server, run from its configuration.
2
3use std::future::Future;
4use std::sync::Arc;
5use std::time::Duration;
6use std::{fmt, io};
7
8use tokio::net::TcpListener;
9
10use crate::access::Plane;
11use crate::api::{self, App, Limits, TlsError};
12use crate::backend;
13use crate::clock::{Clock, SystemClock};
14use crate::config::{Config, Operator, ParquetSettings, StorageError};
15use crate::datadir::{self, LockError, Work};
16use crate::envelope::{Key, KeyError};
17use crate::fs::OsFs;
18use crate::retention::Retention;
19use crate::tenants::{KeyOrder, RegistryError, RotationBacklog, TenantError, Tenants, with_causes};
20use time::OffsetDateTime;
21
22/// Why the server did not start, or stopped.
23#[derive(Debug)]
24pub enum ServeError {
25    /// The data directory could not be taken.
26    DataDir(LockError),
27    /// The master key file could not be read.
28    MasterKey(KeyError),
29    /// server.sqlite was made under another master key.
30    WrongMasterKey,
31    /// The registry in the catalog database was made under another master
32    /// key.
33    WrongDatabaseKey,
34    /// The registry could not be opened.
35    Open(RegistryError),
36    /// server.sqlite could not be read.
37    Registry(TenantError),
38    /// The storage the configuration names cannot be used.
39    Storage(StorageError),
40    /// Some tenant's data is not under its current key.
41    KeysOutOfOrder(KeyOrder),
42    /// `tenants` tenants have packed versions, and the configuration has no
43    /// `[storage.parquet]`.
44    ParquetRemoved {
45        /// How many tenants have packed versions.
46        tenants: u64,
47    },
48    /// The certificate or key could not be used.
49    Tls(TlsError),
50    /// The listening address could not be bound.
51    Listen(io::Error),
52    /// The operator listener's certificate or key could not be used.
53    OperatorTls(TlsError),
54    /// The operator listener's address could not be bound.
55    OperatorListen(io::Error),
56    /// Serving failed.
57    Serve(io::Error),
58}
59
60impl fmt::Display for ServeError {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        match self {
63            ServeError::DataDir(e) => write!(f, "{e}"),
64            ServeError::MasterKey(KeyError::Refused(why)) => {
65                write!(f, "the master key cannot be read: {why}")
66            }
67            ServeError::MasterKey(e) => write!(f, "the master key cannot be read: {e:?}"),
68            ServeError::WrongMasterKey => {
69                f.write_str("the master key is not the one server.sqlite was made under")
70            }
71            ServeError::WrongDatabaseKey => f.write_str(crate::tenants::WRONG_DATABASE_KEY),
72            ServeError::Open(e) => {
73                write!(f, "the registry cannot be opened: {}", with_causes(e))
74            }
75            ServeError::Registry(e) => write!(f, "server.sqlite cannot be opened: {e:?}"),
76            ServeError::KeysOutOfOrder(order) => {
77                let mut parts = Vec::new();
78                if order.wrapped_elsewhere > 0 {
79                    parts.push(format!(
80                        "{} tenant key(s) do not unwrap under the master key",
81                        order.wrapped_elsewhere
82                    ));
83                }
84                if order.rotations_stopped > 0 {
85                    parts.push(format!(
86                        "{} key rotation(s) stopped part way; run rekey tenant again",
87                        order.rotations_stopped
88                    ));
89                }
90                if order.data_under_other_keys > 0 {
91                    parts.push(format!(
92                        "{} tenant(s) with data under another key",
93                        order.data_under_other_keys
94                    ));
95                }
96                if order.catalogs_unopened > 0 {
97                    let why = order
98                        .unopened_error
99                        .as_ref()
100                        .map(|e| format!(": {e}"))
101                        .unwrap_or_default();
102                    parts.push(format!(
103                        "{} tenant catalog(s) cannot be opened{why}",
104                        order.catalogs_unopened
105                    ));
106                }
107                write!(
108                    f,
109                    "{}; vcon-server check names the tenants",
110                    parts.join("; ")
111                )
112            }
113            ServeError::ParquetRemoved { tenants } => write!(
114                f,
115                "{tenants} tenant(s) have versions packed into Parquet files, and the \
116                 configuration has no [storage.parquet]: without it the server packs no more, \
117                 and the start no longer refuses a bucket with Object Lock or versioning, either \
118                 of which keeps the bytes of a pack file that a purge rewrote; put the \
119                 [storage.parquet] table back, since packed versions cannot be turned back into \
120                 objects; vcon-server check names the tenants"
121            ),
122            ServeError::Tls(crate::api::TlsError::KeyFile(why)) => {
123                write!(f, "the TLS certificate or key cannot be used: {why}")
124            }
125            ServeError::Tls(e) => write!(f, "the TLS certificate or key cannot be used: {e:?}"),
126            ServeError::Listen(e) => write!(f, "the listening address cannot be bound: {e}"),
127            ServeError::OperatorTls(crate::api::TlsError::KeyFile(why)) => write!(
128                f,
129                "the operator listener's TLS certificate or key cannot be used: {why}"
130            ),
131            ServeError::OperatorTls(e) => write!(
132                f,
133                "the operator listener's TLS certificate or key cannot be used: {e:?}"
134            ),
135            ServeError::OperatorListen(e) => {
136                write!(f, "the operator listening address cannot be bound: {e}")
137            }
138            ServeError::Serve(e) => write!(f, "serving failed: {e}"),
139            ServeError::Storage(e) => write!(f, "the storage cannot be used: {e}"),
140        }
141    }
142}
143
144/// Runs the server until `shutdown` completes: locks the data directory,
145/// opens the registry under the master key, and serves the API over TLS.
146///
147/// The opening runs on a blocking task: the registry and the catalogs are
148/// read there, and a PostgreSQL catalog waits on a runtime of its own,
149/// which no async worker may do. A server that stops, or whose start is
150/// refused after the catalogs were reached, gives its locks on the
151/// database up before it ends.
152pub async fn run(config: &Config, shutdown: impl Future<Output = ()>) -> Result<(), ServeError> {
153    let opening = config.clone();
154    let opened = blocking(move || open(&opening)).await?;
155    run_opened(config, opened, shutdown).await
156}
157
158/// [`run`], with the data directory locked and the registry opened: serves
159/// until `shutdown` completes or a listener fails, and then gives up the
160/// locks on the catalog database, while its connections still answer, so
161/// the next server finds the database free at once.
162pub(crate) async fn run_opened(
163    config: &Config,
164    (_lock, catalogs, tenants): Opened,
165    shutdown: impl Future<Output = ()>,
166) -> Result<(), ServeError> {
167    if let Some(server) = catalogs.server() {
168        tracing::info!(catalog = %server, "the catalogs are in PostgreSQL");
169    }
170    let served = serve_opened(config, tenants, shutdown).await;
171    blocking(move || catalogs.give_up_locks()).await;
172    served?;
173    tracing::info!("stopped");
174    Ok(())
175}
176
177/// Runs `work`, which reads files or waits on the catalog database, off
178/// the async workers.
179async fn blocking<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> T {
180    match tokio::task::spawn_blocking(work).await {
181        Ok(done) => done,
182        Err(e) => std::panic::resume_unwind(e.into_panic()),
183    }
184}
185
186/// What a start opens before it listens: the data directory's lock, where
187/// the catalogs are, and the registry, checked.
188pub(crate) type Opened = (datadir::DataDirLock, backend::Catalogs, Tenants);
189
190/// Locks the data directory, reads the master key, reaches the catalogs
191/// and then the objects, and opens the registry. A start refused after the
192/// catalogs were reached gives its locks on the database up.
193fn open(config: &Config) -> Result<Opened, ServeError> {
194    let lock =
195        datadir::lock(&config.data_dir, Work::Serve.sharing()).map_err(ServeError::DataDir)?;
196    let master = Key::load_master(&config.master_key).map_err(ServeError::MasterKey)?;
197    let catalogs = backend::catalog_for(&config.catalog, Work::Serve.sharing())
198        .map_err(ServeError::Storage)?;
199    let tenants = open_or_give_up(config, master, &catalogs)?;
200    Ok((lock, catalogs, tenants))
201}
202
203/// [`open_on`], and for a start it refuses, the locks on the catalog
204/// database given up while the connections still answer.
205pub(crate) fn open_or_give_up(
206    config: &Config,
207    master: Key,
208    catalogs: &backend::Catalogs,
209) -> Result<Tenants, ServeError> {
210    open_on(config, master, catalogs).inspect_err(|_| catalogs.give_up_locks())
211}
212
213/// The registry on `catalogs`, with the objects bound to them, and the
214/// checks a start makes of it before it listens.
215fn open_on(
216    config: &Config,
217    master: Key,
218    catalogs: &backend::Catalogs,
219) -> Result<Tenants, ServeError> {
220    let objects = backend::objects_for(&config.storage, &config.data_dir, catalogs)
221        .map_err(ServeError::Storage)?;
222    let tenants = Tenants::open_in(
223        &config.data_dir,
224        master,
225        Arc::new(OsFs),
226        Arc::new(SystemClock),
227        objects,
228        catalogs,
229    )
230    .map_err(|e| match e {
231        RegistryError::WrongKey => ServeError::WrongMasterKey,
232        RegistryError::WrongDatabaseKey => ServeError::WrongDatabaseKey,
233        other => ServeError::Open(other),
234    })?;
235    let order = tenants.key_order().map_err(ServeError::Registry)?;
236    if !order.is_sound() {
237        return Err(ServeError::KeysOutOfOrder(order));
238    }
239    // Packed versions need Parquet storage kept on: nothing turns them
240    // back into objects, and only with it is the bucket checked for what
241    // would keep a purged row's bytes.
242    if config.storage.parquet.is_none() {
243        let tenants = tenants
244            .tenants_with_packed_versions()
245            .map_err(ServeError::Registry)?;
246        if tenants > 0 {
247            return Err(ServeError::ParquetRemoved { tenants });
248        }
249    }
250    Ok(tenants)
251}
252
253/// Serves the opened registry until `shutdown` completes or a listener
254/// fails.
255async fn serve_opened(
256    config: &Config,
257    tenants: Tenants,
258    shutdown: impl Future<Output = ()>,
259) -> Result<(), ServeError> {
260    let tls = api::tls_config(&config.tls_cert, &config.tls_key).map_err(ServeError::Tls)?;
261    let listener = TcpListener::bind(config.listen)
262        .await
263        .map_err(ServeError::Listen)?;
264    // The address bound, which names the port the system chose when the
265    // configuration gives port 0.
266    let bound = listener.local_addr().map_err(ServeError::Listen)?;
267    // The operator listener, when the configuration has one: bound before
268    // anything is served, so a start that cannot have both serves neither.
269    let operator = match &config.operator {
270        Some(operator) => {
271            let tls = api::tls_config_named(
272                &operator.tls_cert,
273                &operator.tls_key,
274                operator_key_name(config, operator),
275            )
276            .map_err(ServeError::OperatorTls)?;
277            let listener = TcpListener::bind(operator.listen)
278                .await
279                .map_err(ServeError::OperatorListen)?;
280            let bound = listener.local_addr().map_err(ServeError::OperatorListen)?;
281            Some((listener, tls, bound))
282        }
283        None => None,
284    };
285    let tenants = Arc::new(tenants);
286    // The purge sweep: at start, then purge_interval after each sweep ends,
287    // until the server stops.
288    let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
289    let (swept, default) = (tenants.clone(), config.retention_default);
290    let sweeper = tokio::spawn(every(
291        config.purge_interval,
292        async {
293            let _ = stopped.await;
294        },
295        move || {
296            let tenants = swept.clone();
297            async move {
298                let _ = tokio::task::spawn_blocking(move || sweep(&tenants, default)).await;
299            }
300        },
301    ));
302    // The pack run, with Parquet storage: at start, then pack_interval
303    // after each run ends, until the server stops.
304    let (stop_packing, packing_stopped) = tokio::sync::oneshot::channel::<()>();
305    let packer = config.storage.parquet.map(|parquet| {
306        let packed = tenants.clone();
307        tokio::spawn(every(
308            parquet.pack_interval,
309            async {
310                let _ = packing_stopped.await;
311            },
312            move || {
313                let tenants = packed.clone();
314                async move {
315                    let _ = tokio::task::spawn_blocking(move || pack_all(&tenants, &parquet)).await;
316                }
317            },
318        ))
319    });
320    // The rotation warning: at start, then each day.
321    let (stop_warning, warning_stopped) = tokio::sync::oneshot::channel::<()>();
322    let (watched, rotation_warn) = (tenants.clone(), config.rotation_warn);
323    let warner = tokio::spawn(every(
324        ROTATION_CHECK,
325        async {
326            let _ = warning_stopped.await;
327        },
328        move || {
329            let tenants = watched.clone();
330            async move {
331                let _ = tokio::task::spawn_blocking(move || {
332                    warn_if_rotation_overdue(&tenants, rotation_warn);
333                })
334                .await;
335            }
336        },
337    ));
338    // With an operator listener each listener serves one kind of key;
339    // without one, the one listener serves both.
340    let (halt, halted) = tokio::sync::watch::channel(());
341    let until_halted = |mut halted: tokio::sync::watch::Receiver<()>| async move {
342        // An error is the sender dropped: halted as well.
343        let _ = halted.changed().await;
344    };
345    // Each time a listener finds every place held, that is counted in the
346    // admin log under the listener's configuration key. The count is
347    // written off the listener's task, which goes on to wait for a place.
348    let counted = tenants.clone();
349    let counts_full = move |key: &'static str| {
350        let tenants = counted.clone();
351        move || {
352            let tenants = tenants.clone();
353            tokio::task::spawn_blocking(move || tenants.count_listener_full(key));
354        }
355    };
356    let both = async {
357        let Some((operator_listener, operator_tls, operator_bound)) = operator else {
358            let full = counts_full("listen");
359            let app = app_from(config, tenants, Plane::Both);
360            tracing::info!(listen = %bound, "serving");
361            return api::serve_observed(
362                listener,
363                tls,
364                api::router(Arc::new(app)),
365                until_halted(halted),
366                config.connection,
367                full,
368            )
369            .await;
370        };
371        let (tenant_full, operator_full) = (counts_full("listen"), counts_full("operator.listen"));
372        let tenant_app = app_from(config, tenants.clone(), Plane::Tenant);
373        let operator_app = app_from(config, tenants, Plane::Operator);
374        // Before the serving line: whoever waits for that line finds both
375        // listeners bound.
376        tracing::info!(operator_listen = %operator_bound, "the operator listener is bound");
377        tracing::info!(listen = %bound, "serving");
378        let (tenant, operator) = tokio::join!(
379            api::serve_observed(
380                listener,
381                tls,
382                api::router(Arc::new(tenant_app)),
383                until_halted(halted.clone()),
384                config.connection,
385                tenant_full,
386            ),
387            api::serve_observed(
388                operator_listener,
389                operator_tls,
390                api::router(Arc::new(operator_app)),
391                until_halted(halted),
392                config.connection,
393                operator_full,
394            ),
395        );
396        tenant.and(operator)
397    };
398    let mut both = std::pin::pin!(both);
399    let served = tokio::select! {
400        served = &mut both => served,
401        () = shutdown => {
402            let _ = halt.send(());
403            both.await
404        }
405    };
406    let _ = stop.send(());
407    let _ = stop_warning.send(());
408    let _ = stop_packing.send(());
409    let _ = sweeper.await;
410    let _ = warner.await;
411    if let Some(packer) = packer {
412        let _ = packer.await;
413    }
414    served.map_err(ServeError::Serve)
415}
416
417/// What one pack run over every tenant did.
418#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
419pub struct PackRunReport {
420    /// Pack files written and recorded, over every tenant.
421    pub files: u64,
422    /// Versions moved into them.
423    pub versions: u64,
424    /// Tenants whose run failed; they wait for the next run.
425    pub failed: u64,
426}
427
428/// One pack run over every tenant, as `Store::pack` does for one, with the
429/// configured limit and reader grace. A tenant whose run fails is
430/// counted and left for the next run. Logged with counts only, never a
431/// tenant.
432pub fn pack_all(tenants: &Tenants, settings: &ParquetSettings) -> PackRunReport {
433    let mut report = PackRunReport::default();
434    let plan = crate::store::packer::PackPlan {
435        grace: settings.reader_grace,
436        ..crate::store::packer::PackPlan::with_limit(settings.pack_limit)
437    };
438    match tenants.ids() {
439        Ok(ids) => {
440            for id in ids {
441                match tenants.store(id).map(|store| store.pack(&plan)) {
442                    Ok(Ok(done)) => {
443                        report.files += done.files;
444                        report.versions += done.versions;
445                    }
446                    _ => report.failed += 1,
447                }
448            }
449        }
450        Err(_) => report.failed += 1,
451    }
452    tracing::info!(
453        files = report.files,
454        versions = report.versions,
455        failed = report.failed,
456        "pack run"
457    );
458    report
459}
460
461/// What one purge sweep did.
462#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
463pub struct SweepReport {
464    /// Versions purged, over every tenant.
465    pub purged: u64,
466    /// Tenants that could not be swept; they wait for the next sweep.
467    pub failed: u64,
468}
469
470/// One purge sweep: each tenant purges what is due under its own retention
471/// period, else `default`. A tenant that cannot be swept, such as one whose
472/// period does not read back or that is being removed, is counted and left
473/// for the next sweep. The sweep is logged with counts only, never a tenant.
474pub fn sweep(tenants: &Tenants, default: Retention) -> SweepReport {
475    let mut report = SweepReport::default();
476    match tenants.ids() {
477        Ok(ids) => {
478            for id in ids {
479                let purged = tenants.retention(id).and_then(|own| {
480                    let store = tenants.store(id)?;
481                    Ok(store.purge_due(crate::tenants::kept_for(own, default)))
482                });
483                match purged {
484                    Ok(Ok(done)) => report.purged += done.purged,
485                    _ => report.failed += 1,
486                }
487            }
488        }
489        Err(_) => report.failed += 1,
490    }
491    tracing::info!(
492        purged = report.purged,
493        failed = report.failed,
494        "purge sweep"
495    );
496    report
497}
498
499/// Runs `job` at once, then again `interval` after each run ends, until
500/// `shutdown` completes; a run still going when it does is not awaited.
501pub async fn every<F, Fut>(interval: Duration, shutdown: impl Future<Output = ()>, mut job: F)
502where
503    F: FnMut() -> Fut,
504    Fut: Future<Output = ()>,
505{
506    tokio::pin!(shutdown);
507    loop {
508        tokio::select! {
509            biased;
510            () = &mut shutdown => return,
511            () = job() => {}
512        }
513        tokio::select! {
514            biased;
515            () = &mut shutdown => return,
516            () = tokio::time::sleep(interval) => {}
517        }
518    }
519}
520
521/// The configuration key that names the operator listener's key file:
522/// `operator.tls.key`, or `tls.key` when the `[operator]` table names no
523/// pair of its own and the listener takes the server's.
524fn operator_key_name(config: &Config, operator: &Operator) -> &'static str {
525    if operator.tls_key == config.tls_key && operator.tls_cert == config.tls_cert {
526        "tls.key"
527    } else {
528        "operator.tls.key"
529    }
530}
531
532/// What the API serves from on a listener of `plane`, as the
533/// configuration sets it.
534fn app_from(config: &Config, tenants: Arc<Tenants>, plane: Plane) -> App {
535    tenants.allow_no_expiry(config.keys_no_expiry);
536    App {
537        tenants,
538        limits: Limits {
539            body: config.body_limit,
540            inflated: config.inflated_limit,
541            body_timeout: config.read_timeout,
542        },
543        supported: config.supported_critical.clone(),
544        retention_default: config.retention_default,
545        mcp: config.mcp,
546        plane,
547        reports: crate::api::ReportGate::new(config.reports),
548        origin: origin_for(config, plane),
549    }
550}
551
552/// The public origin of the listener of `plane`: `operator.public_origin`
553/// for the operator listener, `public_origin` for the tenant listener and
554/// for the one listener of a server with no operator listener.
555fn origin_for(config: &Config, plane: Plane) -> Option<crate::session::Origin> {
556    match plane {
557        Plane::Both | Plane::Tenant => config.public_origin.clone(),
558        Plane::Operator => config
559            .operator
560            .as_ref()
561            .and_then(|operator| operator.public_origin.clone()),
562    }
563}
564
565/// Whether key rotation is overdue: the oldest purge or removal waiting
566/// for it is older than `rotation_warn`.
567pub fn rotation_overdue(
568    backlog: &RotationBacklog,
569    rotation_warn: Duration,
570    now: OffsetDateTime,
571) -> bool {
572    [backlog.oldest_purge, backlog.oldest_removal]
573        .into_iter()
574        .flatten()
575        .any(|at| now - at > rotation_warn)
576}
577
578/// How often `serve` looks at the rotation backlog.
579const ROTATION_CHECK: Duration = Duration::from_secs(86_400);
580
581/// Logs a warning, with counts only, when key rotation is overdue.
582fn warn_if_rotation_overdue(tenants: &Tenants, rotation_warn: Duration) {
583    match tenants.rotation_backlog() {
584        Ok(backlog) if rotation_overdue(&backlog, rotation_warn, SystemClock.now()) => {
585            tracing::warn!(
586                tenants_with_purges = backlog.tenants_with_purges,
587                purges = backlog.purges,
588                removals = backlog.removals,
589                "key rotation overdue: purged vCons and removed tenants stay readable on old copies until it"
590            );
591        }
592        Ok(_) => {}
593        Err(_) => tracing::warn!("the key rotation backlog could not be read"),
594    }
595}
596
597#[cfg(test)]
598mod tests {
599    use std::time::Duration;
600
601    use super::*;
602
603    mod startup {
604        use time::macros::datetime;
605
606        use super::*;
607
608        /// The refusal names the table that was taken out, says what goes
609        /// wrong without it, and where the tenants are named.
610        #[test]
611        fn a_start_without_storage_parquet_over_packed_versions_names_the_table() {
612            assert_eq!(
613                ServeError::ParquetRemoved { tenants: 2 }.to_string(),
614                "2 tenant(s) have versions packed into Parquet files, and the configuration has no \
615                 [storage.parquet]: without it the server packs no more, and the start no longer \
616                 refuses a bucket with Object Lock or versioning, either of which keeps the bytes of \
617                 a pack file that a purge rewrote; put the [storage.parquet] table back, since packed \
618                 versions cannot be turned back into objects; vcon-server check names the tenants",
619                "the refusal's text"
620            );
621        }
622
623        const NOW: OffsetDateTime = datetime!(2026-10-25 12:00 UTC);
624        const DAY: Duration = Duration::from_secs(86_400);
625
626        #[test]
627        fn rotation_is_overdue_once_the_oldest_waiting_work_passes_rotation_warn() {
628            let backlog =
629                |purge: Option<OffsetDateTime>, removal: Option<OffsetDateTime>| RotationBacklog {
630                    tenants_with_purges: u64::from(purge.is_some()),
631                    purges: u64::from(purge.is_some()),
632                    oldest_purge: purge,
633                    removals: u64::from(removal.is_some()),
634                    oldest_removal: removal,
635                };
636            let day_ago = Some(datetime!(2026-10-24 12:00 UTC));
637            let older = Some(datetime!(2026-10-24 11:59:59 UTC));
638            for (b, overdue) in [
639                (backlog(None, None), false),
640                (backlog(day_ago, None), false),
641                (backlog(older, None), true),
642                (backlog(None, older), true),
643                (backlog(day_ago, older), true),
644            ] {
645                assert_eq!(rotation_overdue(&b, DAY, NOW), overdue, "{b:?}");
646            }
647        }
648
649        #[test]
650        fn a_refusal_for_keys_out_of_order_counts_and_points_at_check() {
651            let order = KeyOrder {
652                wrapped_elsewhere: 1,
653                rotations_stopped: 2,
654                data_under_other_keys: 3,
655                ..KeyOrder::default()
656            };
657            assert_eq!(
658                ServeError::KeysOutOfOrder(order).to_string(),
659                "1 tenant key(s) do not unwrap under the master key; \
660                 2 key rotation(s) stopped part way; run rekey tenant again; \
661                 3 tenant(s) with data under another key; \
662                 vcon-server check names the tenants",
663                "each count in its fixed place, then where to look"
664            );
665        }
666
667        /// Catalogs the server may not open are counted apart from keys,
668        /// with the system's error, and never a tenant or a path.
669        #[test]
670        fn a_refusal_for_catalogs_it_may_not_open_gives_the_error_not_a_key() {
671            let order = KeyOrder {
672                catalogs_unopened: 2,
673                unopened_error: Some("Permission denied (os error 13)".to_owned()),
674                ..KeyOrder::default()
675            };
676            assert_eq!(
677                ServeError::KeysOutOfOrder(order).to_string(),
678                "2 tenant catalog(s) cannot be opened: Permission denied (os error 13); vcon-server check names the tenants"
679            );
680        }
681    }
682    use crate::retention::Retention;
683
684    #[test]
685    fn the_api_takes_its_limits_and_extensions_from_the_configuration() {
686        let dir = tempfile::tempdir().expect("temp dir");
687        let tenants = Arc::new(
688            Tenants::open(
689                dir.path(),
690                Key::generate().expect("key"),
691                Arc::new(OsFs),
692                Arc::new(SystemClock),
693            )
694            .expect("opens"),
695        );
696        let config = Config {
697            listen: "127.0.0.1:8443".parse().expect("address"),
698            tls_cert: "cert.pem".into(),
699            tls_key: "key.pem".into(),
700            data_dir: dir.path().to_owned(),
701            master_key: "master.key".into(),
702            retention_default: Retention::Months(18),
703            purge_interval: Duration::from_secs(3600),
704            rotation_warn: Duration::from_secs(86400),
705            body_limit: 12_345,
706            inflated_limit: 67_890,
707            read_timeout: Duration::from_secs(17),
708            connection: crate::api::ConnectionLimits::default(),
709            supported_critical: ["known".to_owned()].into(),
710            mcp: crate::mcp::Limits {
711                calls_per_second: 3,
712                concurrent: 4,
713                response_bytes: 5,
714            },
715            reports: crate::api::ReportLimits::DEFAULT,
716            storage: crate::config::Storage::default(),
717            export: crate::config::Export::default(),
718            catalog: crate::config::CatalogStore::Local,
719            operator: None,
720            public_origin: None,
721            keys_no_expiry: false,
722        };
723        assert!(
724            tenants.no_expiry_allowed(),
725            "before the configuration is applied a key may have no expiry"
726        );
727        let app = app_from(&config, tenants.clone(), Plane::Tenant);
728        assert!(
729            !tenants.no_expiry_allowed(),
730            "keys.no_expiry = false reaches the registry the API makes keys in"
731        );
732        assert_eq!(app.plane, Plane::Tenant, "the plane it was given");
733        assert!(Arc::ptr_eq(&app.tenants, &tenants));
734        assert_eq!(app.limits.body, 12_345);
735        assert_eq!(app.limits.inflated, 67_890);
736        assert_eq!(app.limits.body_timeout, Duration::from_secs(17));
737        assert_eq!(app.supported, config.supported_critical);
738        assert_eq!(app.retention_default, config.retention_default);
739        assert_eq!(app.mcp, config.mcp);
740        assert_eq!(app.origin, None, "no public origin is configured");
741    }
742
743    /// A configuration with these lines before and after the least one.
744    fn configured(first: &str, last: &str) -> Config {
745        let text = format!(
746            "{first}listen = \"127.0.0.1:8443\"\ndata_dir = \"/var/lib/vcon-server\"\n\
747             master_key = \"/etc/vcon-server/master.key\"\n[tls]\ncert = \"/c.pem\"\n\
748             key = \"/k.pem\"\n{last}"
749        );
750        crate::config::parse(&text).expect("a configuration")
751    }
752
753    const OPERATOR: &str =
754        "[operator]\nlisten = \"127.0.0.1:8444\"\npublic_origin = \"https://ops.example.com\"\n";
755
756    #[test]
757    fn each_listener_takes_its_own_public_origin() {
758        let config = configured("public_origin = \"https://vcon.example.com\"\n", OPERATOR);
759        let origin = |plane| origin_for(&config, plane).map(|o| o.as_str().to_owned());
760        assert_eq!(
761            origin(Plane::Tenant).as_deref(),
762            Some("https://vcon.example.com"),
763            "`listen` takes public_origin"
764        );
765        assert_eq!(
766            origin(Plane::Operator).as_deref(),
767            Some("https://ops.example.com"),
768            "`operator.listen` takes operator.public_origin"
769        );
770    }
771
772    #[test]
773    fn the_one_listener_of_a_server_takes_public_origin_for_both_planes() {
774        let config = configured("public_origin = \"https://vcon.example.com\"\n", "");
775        assert_eq!(
776            origin_for(&config, Plane::Both),
777            crate::session::Origin::parse("https://vcon.example.com"),
778            "tenants' and operators' sessions come from the one origin"
779        );
780    }
781
782    #[test]
783    fn a_listener_with_no_public_origin_has_none_and_does_not_take_the_other_s() {
784        let config = configured("", OPERATOR);
785        assert_eq!(
786            origin_for(&config, Plane::Tenant),
787            None,
788            "not the operator's"
789        );
790        let config = configured("public_origin = \"https://vcon.example.com\"\n", "");
791        assert_eq!(
792            origin_for(&config, Plane::Operator),
793            None,
794            "not the tenant's"
795        );
796        let config = configured("", "");
797        assert_eq!(origin_for(&config, Plane::Both), None, "none is configured");
798    }
799
800    mod sweeps {
801        use std::sync::Arc;
802        use std::sync::atomic::{AtomicUsize, Ordering};
803        use std::time::Duration;
804
805        use time::macros::datetime;
806        use uuid::Uuid;
807
808        use crate::audit::Actor;
809        use crate::ids::{KeyId, TenantId};
810        use crate::retention::Retention;
811        use crate::serve::{SweepReport, every, sweep};
812        use crate::store::Caller;
813        use crate::store::testing::vcon;
814        use crate::tenants::{Tenants, fixture};
815
816        const CALLER: Caller = Caller { key: KeyId([7; 8]) };
817
818        /// A vCon stored and deleted in `id` while seven years apply, so
819        /// it waits hidden for a sweep.
820        fn deleted(tenants: &Tenants, id: TenantId, uuid: &str) -> Uuid {
821            let store = tenants.store(id).expect("its store");
822            let (found, body) = vcon(uuid, "kept");
823            store.create(&CALLER, &found, &body).expect("stored");
824            store
825                .delete(&CALLER, found.uuid, Retention::Years(7))
826                .expect("deleted");
827            found.uuid
828        }
829
830        /// How many versions `id` still keeps.
831        fn kept(tenants: &Tenants, id: TenantId) -> u64 {
832            tenants
833                .store(id)
834                .expect("its store")
835                .counts()
836                .expect("counts")
837                .versions
838        }
839
840        #[test]
841        fn a_sweep_purges_what_is_due_in_each_tenant_under_its_own_period() {
842            let f = fixture();
843            let own = f
844                .tenants
845                .create(Actor::Cli, "own", Some(Retention::Days(1)))
846                .expect("made");
847            let default = f.tenants.create(Actor::Cli, "default", None).expect("made");
848            let long = f
849                .tenants
850                .create(Actor::Cli, "long", Some(Retention::Years(7)))
851                .expect("made");
852            deleted(&f.tenants, own, "0199e5c6-0d7a-7c11-8000-000000000001");
853            deleted(&f.tenants, default, "0199e5c6-0d7a-7c11-8000-000000000002");
854            deleted(&f.tenants, long, "0199e5c6-0d7a-7c11-8000-000000000003");
855            f.clock.set(datetime!(2026-10-25 13:00 UTC));
856
857            let report = sweep(&f.tenants, Retention::Days(1));
858
859            assert_eq!(
860                report,
861                SweepReport {
862                    purged: 2,
863                    failed: 0
864                }
865            );
866            assert_eq!(kept(&f.tenants, own), 0);
867            assert_eq!(kept(&f.tenants, default), 0);
868            assert_eq!(kept(&f.tenants, long), 1, "seven years have not passed");
869        }
870
871        #[test]
872        fn a_sweep_goes_on_past_a_tenant_it_cannot_sweep() {
873            let f = fixture();
874            let damaged = f.tenants.create(Actor::Cli, "damaged", None).expect("made");
875            let fine = f.tenants.create(Actor::Cli, "fine", None).expect("made");
876            deleted(&f.tenants, damaged, "0199e5c6-0d7a-7c11-8000-000000000001");
877            deleted(&f.tenants, fine, "0199e5c6-0d7a-7c11-8000-000000000002");
878            f.tenants
879                .conn_for_test()
880                .execute(
881                    "UPDATE tenant SET retention = '7w' WHERE id = ?1",
882                    [damaged.0],
883                )
884                .expect("damaged");
885            f.clock.set(datetime!(2026-10-25 13:00 UTC));
886
887            let report = sweep(&f.tenants, Retention::Days(1));
888
889            assert_eq!(
890                report,
891                SweepReport {
892                    purged: 1,
893                    failed: 1
894                }
895            );
896            assert_eq!(kept(&f.tenants, fine), 0);
897            assert_eq!(kept(&f.tenants, damaged), 1, "left for a later sweep");
898        }
899
900        #[tokio::test(start_paused = true)]
901        async fn every_runs_at_start_then_after_each_interval_until_shutdown() {
902            let runs = Arc::new(AtomicUsize::new(0));
903            let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
904            let counted = runs.clone();
905            let task = tokio::spawn(every(
906                Duration::from_secs(60),
907                async move {
908                    let _ = stopped.await;
909                },
910                move || {
911                    counted.fetch_add(1, Ordering::SeqCst);
912                    async {}
913                },
914            ));
915            let settle = || async {
916                for _ in 0..10 {
917                    tokio::task::yield_now().await;
918                }
919            };
920
921            settle().await;
922            assert_eq!(runs.load(Ordering::SeqCst), 1, "at start");
923            tokio::time::advance(Duration::from_secs(59)).await;
924            settle().await;
925            assert_eq!(runs.load(Ordering::SeqCst), 1, "not before the interval");
926            tokio::time::advance(Duration::from_secs(1)).await;
927            settle().await;
928            assert_eq!(runs.load(Ordering::SeqCst), 2, "after the interval");
929
930            stop.send(()).expect("still running");
931            task.await.expect("ends on shutdown");
932            tokio::time::advance(Duration::from_secs(600)).await;
933            assert_eq!(runs.load(Ordering::SeqCst), 2, "none after shutdown");
934        }
935    }
936}