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::api::{self, App, Limits, TlsError};
11use crate::backend;
12use crate::clock::{Clock, SystemClock};
13use crate::config::{Config, ParquetSettings, StorageError};
14use crate::datadir::{self, LockError, Work};
15use crate::envelope::{Key, KeyError};
16use crate::fs::OsFs;
17use crate::retention::Retention;
18use crate::tenants::{KeyOrder, RegistryError, RotationBacklog, TenantError, Tenants, with_causes};
19use time::OffsetDateTime;
20
21/// Why the server did not start, or stopped.
22#[derive(Debug)]
23pub enum ServeError {
24    /// The data directory could not be taken.
25    DataDir(LockError),
26    /// The master key file could not be read.
27    MasterKey(KeyError),
28    /// server.sqlite was made under another master key.
29    WrongMasterKey,
30    /// The registry could not be opened.
31    Open(RegistryError),
32    /// server.sqlite could not be read.
33    Registry(TenantError),
34    /// The storage the configuration names cannot be used.
35    Storage(StorageError),
36    /// Some tenant's data is not under its current key.
37    KeysOutOfOrder(KeyOrder),
38    /// `tenants` tenants have packed versions, and the configuration has no
39    /// `[storage.parquet]`.
40    ParquetRemoved {
41        /// How many tenants have packed versions.
42        tenants: u64,
43    },
44    /// The certificate or key could not be used.
45    Tls(TlsError),
46    /// The listening address could not be bound.
47    Listen(io::Error),
48    /// Serving failed.
49    Serve(io::Error),
50}
51
52impl fmt::Display for ServeError {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        match self {
55            ServeError::DataDir(e) => write!(f, "{e}"),
56            ServeError::MasterKey(KeyError::Refused(why)) => {
57                write!(f, "the master key cannot be read: {why}")
58            }
59            ServeError::MasterKey(e) => write!(f, "the master key cannot be read: {e:?}"),
60            ServeError::WrongMasterKey => {
61                f.write_str("the master key is not the one server.sqlite was made under")
62            }
63            ServeError::Open(e) => {
64                write!(f, "the registry cannot be opened: {}", with_causes(e))
65            }
66            ServeError::Registry(e) => write!(f, "server.sqlite cannot be opened: {e:?}"),
67            ServeError::KeysOutOfOrder(order) => {
68                let mut parts = Vec::new();
69                if order.wrapped_elsewhere > 0 {
70                    parts.push(format!(
71                        "{} tenant key(s) do not unwrap under the master key",
72                        order.wrapped_elsewhere
73                    ));
74                }
75                if order.rotations_stopped > 0 {
76                    parts.push(format!(
77                        "{} key rotation(s) stopped part way; run rekey tenant again",
78                        order.rotations_stopped
79                    ));
80                }
81                if order.data_under_other_keys > 0 {
82                    parts.push(format!(
83                        "{} tenant(s) with data under another key",
84                        order.data_under_other_keys
85                    ));
86                }
87                if order.catalogs_unopened > 0 {
88                    let why = order
89                        .unopened_error
90                        .as_ref()
91                        .map(|e| format!(": {e}"))
92                        .unwrap_or_default();
93                    parts.push(format!(
94                        "{} tenant catalog(s) cannot be opened{why}",
95                        order.catalogs_unopened
96                    ));
97                }
98                write!(
99                    f,
100                    "{}; vcon-server check names the tenants",
101                    parts.join("; ")
102                )
103            }
104            ServeError::ParquetRemoved { tenants } => write!(
105                f,
106                "{tenants} tenant(s) have versions packed into Parquet files, and the \
107                 configuration has no [storage.parquet]: without it the server packs no more, \
108                 and the start no longer refuses a bucket with Object Lock or versioning, either \
109                 of which keeps the bytes of a pack file that a purge rewrote; put the \
110                 [storage.parquet] table back, since packed versions cannot be turned back into \
111                 objects; vcon-server check names the tenants"
112            ),
113            ServeError::Tls(crate::api::TlsError::KeyFile(why)) => {
114                write!(f, "the TLS certificate or key cannot be used: {why}")
115            }
116            ServeError::Tls(e) => write!(f, "the TLS certificate or key cannot be used: {e:?}"),
117            ServeError::Listen(e) => write!(f, "the listening address cannot be bound: {e}"),
118            ServeError::Serve(e) => write!(f, "serving failed: {e}"),
119            ServeError::Storage(e) => write!(f, "the storage cannot be used: {e}"),
120        }
121    }
122}
123
124/// Runs the server until `shutdown` completes: locks the data directory,
125/// opens the registry under the master key, and serves the API over TLS.
126pub async fn run(config: &Config, shutdown: impl Future<Output = ()>) -> Result<(), ServeError> {
127    let _lock =
128        datadir::lock(&config.data_dir, Work::Serve.sharing()).map_err(ServeError::DataDir)?;
129    let master = Key::load_master(&config.master_key).map_err(ServeError::MasterKey)?;
130    let objects =
131        backend::objects_for(&config.storage, &config.data_dir).map_err(ServeError::Storage)?;
132    backend::catalog_for(&config.catalog)
133        .await
134        .map_err(ServeError::Storage)?;
135    let tenants = Tenants::open_in(
136        &config.data_dir,
137        master,
138        Arc::new(OsFs),
139        Arc::new(SystemClock),
140        objects,
141    )
142    .map_err(|e| match e {
143        RegistryError::WrongKey => ServeError::WrongMasterKey,
144        other => ServeError::Open(other),
145    })?;
146    let order = tenants.key_order().map_err(ServeError::Registry)?;
147    if !order.is_sound() {
148        return Err(ServeError::KeysOutOfOrder(order));
149    }
150    // Packed versions need Parquet storage kept on: nothing turns them
151    // back into objects, and only with it is the bucket checked for what
152    // would keep a purged row's bytes.
153    if config.storage.parquet.is_none() {
154        let tenants = tenants
155            .tenants_with_packed_versions()
156            .map_err(ServeError::Registry)?;
157        if tenants > 0 {
158            return Err(ServeError::ParquetRemoved { tenants });
159        }
160    }
161    let tls = api::tls_config(&config.tls_cert, &config.tls_key).map_err(ServeError::Tls)?;
162    let listener = TcpListener::bind(config.listen)
163        .await
164        .map_err(ServeError::Listen)?;
165    // The address bound, which names the port the system chose when the
166    // configuration gives port 0.
167    let bound = listener.local_addr().map_err(ServeError::Listen)?;
168    let tenants = Arc::new(tenants);
169    // The purge sweep: at start, then purge_interval after each sweep ends,
170    // until the server stops.
171    let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
172    let (swept, default) = (tenants.clone(), config.retention_default);
173    let sweeper = tokio::spawn(every(
174        config.purge_interval,
175        async {
176            let _ = stopped.await;
177        },
178        move || {
179            let tenants = swept.clone();
180            async move {
181                let _ = tokio::task::spawn_blocking(move || sweep(&tenants, default)).await;
182            }
183        },
184    ));
185    // The pack run, with Parquet storage: at start, then pack_interval
186    // after each run ends, until the server stops.
187    let (stop_packing, packing_stopped) = tokio::sync::oneshot::channel::<()>();
188    let packer = config.storage.parquet.map(|parquet| {
189        let packed = tenants.clone();
190        tokio::spawn(every(
191            parquet.pack_interval,
192            async {
193                let _ = packing_stopped.await;
194            },
195            move || {
196                let tenants = packed.clone();
197                async move {
198                    let _ = tokio::task::spawn_blocking(move || pack_all(&tenants, &parquet)).await;
199                }
200            },
201        ))
202    });
203    // The rotation warning: at start, then each day.
204    let (stop_warning, warning_stopped) = tokio::sync::oneshot::channel::<()>();
205    let (watched, rotation_warn) = (tenants.clone(), config.rotation_warn);
206    let warner = tokio::spawn(every(
207        ROTATION_CHECK,
208        async {
209            let _ = warning_stopped.await;
210        },
211        move || {
212            let tenants = watched.clone();
213            async move {
214                let _ = tokio::task::spawn_blocking(move || {
215                    warn_if_rotation_overdue(&tenants, rotation_warn);
216                })
217                .await;
218            }
219        },
220    ));
221    let app = app_from(config, tenants);
222    tracing::info!(listen = %bound, "serving");
223    let served = api::serve(listener, tls, api::router(Arc::new(app)), shutdown).await;
224    let _ = stop.send(());
225    let _ = stop_warning.send(());
226    let _ = stop_packing.send(());
227    let _ = sweeper.await;
228    let _ = warner.await;
229    if let Some(packer) = packer {
230        let _ = packer.await;
231    }
232    served.map_err(ServeError::Serve)?;
233    tracing::info!("stopped");
234    Ok(())
235}
236
237/// What one pack run over every tenant did.
238#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
239pub struct PackRunReport {
240    /// Pack files written and recorded, over every tenant.
241    pub files: u64,
242    /// Versions moved into them.
243    pub versions: u64,
244    /// Tenants whose run failed; they wait for the next run.
245    pub failed: u64,
246}
247
248/// One pack run over every tenant, as `Store::pack` does for one, with the
249/// configured limit and reader grace. A tenant whose run fails is
250/// counted and left for the next run. Logged with counts only, never a
251/// tenant.
252pub fn pack_all(tenants: &Tenants, settings: &ParquetSettings) -> PackRunReport {
253    let mut report = PackRunReport::default();
254    let plan = crate::store::packer::PackPlan {
255        grace: settings.reader_grace,
256        ..crate::store::packer::PackPlan::with_limit(settings.pack_limit)
257    };
258    match tenants.ids() {
259        Ok(ids) => {
260            for id in ids {
261                match tenants.store(id).map(|store| store.pack(&plan)) {
262                    Ok(Ok(done)) => {
263                        report.files += done.files;
264                        report.versions += done.versions;
265                    }
266                    _ => report.failed += 1,
267                }
268            }
269        }
270        Err(_) => report.failed += 1,
271    }
272    tracing::info!(
273        files = report.files,
274        versions = report.versions,
275        failed = report.failed,
276        "pack run"
277    );
278    report
279}
280
281/// What one purge sweep did.
282#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
283pub struct SweepReport {
284    /// Versions purged, over every tenant.
285    pub purged: u64,
286    /// Tenants that could not be swept; they wait for the next sweep.
287    pub failed: u64,
288}
289
290/// One purge sweep: each tenant purges what is due under its own retention
291/// period, else `default`. A tenant that cannot be swept, such as one whose
292/// period does not read back or that is being removed, is counted and left
293/// for the next sweep. The sweep is logged with counts only, never a tenant.
294pub fn sweep(tenants: &Tenants, default: Retention) -> SweepReport {
295    let mut report = SweepReport::default();
296    match tenants.ids() {
297        Ok(ids) => {
298            for id in ids {
299                let purged = tenants.retention(id).and_then(|own| {
300                    let store = tenants.store(id)?;
301                    Ok(store.purge_due(crate::tenants::kept_for(own, default)))
302                });
303                match purged {
304                    Ok(Ok(done)) => report.purged += done.purged,
305                    _ => report.failed += 1,
306                }
307            }
308        }
309        Err(_) => report.failed += 1,
310    }
311    tracing::info!(
312        purged = report.purged,
313        failed = report.failed,
314        "purge sweep"
315    );
316    report
317}
318
319/// Runs `job` at once, then again `interval` after each run ends, until
320/// `shutdown` completes; a run still going when it does is not awaited.
321pub async fn every<F, Fut>(interval: Duration, shutdown: impl Future<Output = ()>, mut job: F)
322where
323    F: FnMut() -> Fut,
324    Fut: Future<Output = ()>,
325{
326    tokio::pin!(shutdown);
327    loop {
328        tokio::select! {
329            biased;
330            () = &mut shutdown => return,
331            () = job() => {}
332        }
333        tokio::select! {
334            biased;
335            () = &mut shutdown => return,
336            () = tokio::time::sleep(interval) => {}
337        }
338    }
339}
340
341/// What the API serves from, as the configuration sets it.
342fn app_from(config: &Config, tenants: Arc<Tenants>) -> App {
343    App {
344        tenants,
345        limits: Limits {
346            body: config.body_limit,
347            inflated: config.inflated_limit,
348            body_timeout: config.read_timeout,
349        },
350        supported: config.supported_critical.clone(),
351        retention_default: config.retention_default,
352        mcp: config.mcp,
353    }
354}
355
356/// Whether key rotation is overdue: the oldest purge or removal waiting
357/// for it is older than `rotation_warn`.
358pub fn rotation_overdue(
359    backlog: &RotationBacklog,
360    rotation_warn: Duration,
361    now: OffsetDateTime,
362) -> bool {
363    [backlog.oldest_purge, backlog.oldest_removal]
364        .into_iter()
365        .flatten()
366        .any(|at| now - at > rotation_warn)
367}
368
369/// How often `serve` looks at the rotation backlog.
370const ROTATION_CHECK: Duration = Duration::from_secs(86_400);
371
372/// Logs a warning, with counts only, when key rotation is overdue.
373fn warn_if_rotation_overdue(tenants: &Tenants, rotation_warn: Duration) {
374    match tenants.rotation_backlog() {
375        Ok(backlog) if rotation_overdue(&backlog, rotation_warn, SystemClock.now()) => {
376            tracing::warn!(
377                tenants_with_purges = backlog.tenants_with_purges,
378                purges = backlog.purges,
379                removals = backlog.removals,
380                "key rotation overdue: purged vCons and removed tenants stay readable on old copies until it"
381            );
382        }
383        Ok(_) => {}
384        Err(_) => tracing::warn!("the key rotation backlog could not be read"),
385    }
386}
387
388#[cfg(test)]
389mod tests {
390    use std::time::Duration;
391
392    use super::*;
393
394    mod startup {
395        use time::macros::datetime;
396
397        use super::*;
398
399        /// The refusal names the table that was taken out, says what goes
400        /// wrong without it, and where the tenants are named.
401        #[test]
402        fn a_start_without_storage_parquet_over_packed_versions_names_the_table() {
403            assert_eq!(
404                ServeError::ParquetRemoved { tenants: 2 }.to_string(),
405                "2 tenant(s) have versions packed into Parquet files, and the configuration has no \
406                 [storage.parquet]: without it the server packs no more, and the start no longer \
407                 refuses a bucket with Object Lock or versioning, either of which keeps the bytes of \
408                 a pack file that a purge rewrote; put the [storage.parquet] table back, since packed \
409                 versions cannot be turned back into objects; vcon-server check names the tenants",
410                "the refusal's text"
411            );
412        }
413
414        const NOW: OffsetDateTime = datetime!(2026-10-25 12:00 UTC);
415        const DAY: Duration = Duration::from_secs(86_400);
416
417        #[test]
418        fn rotation_is_overdue_once_the_oldest_waiting_work_passes_rotation_warn() {
419            let backlog =
420                |purge: Option<OffsetDateTime>, removal: Option<OffsetDateTime>| RotationBacklog {
421                    tenants_with_purges: u64::from(purge.is_some()),
422                    purges: u64::from(purge.is_some()),
423                    oldest_purge: purge,
424                    removals: u64::from(removal.is_some()),
425                    oldest_removal: removal,
426                };
427            let day_ago = Some(datetime!(2026-10-24 12:00 UTC));
428            let older = Some(datetime!(2026-10-24 11:59:59 UTC));
429            for (b, overdue) in [
430                (backlog(None, None), false),
431                (backlog(day_ago, None), false),
432                (backlog(older, None), true),
433                (backlog(None, older), true),
434                (backlog(day_ago, older), true),
435            ] {
436                assert_eq!(rotation_overdue(&b, DAY, NOW), overdue, "{b:?}");
437            }
438        }
439
440        #[test]
441        fn a_refusal_for_keys_out_of_order_counts_and_points_at_check() {
442            let order = KeyOrder {
443                wrapped_elsewhere: 1,
444                rotations_stopped: 2,
445                data_under_other_keys: 3,
446                ..KeyOrder::default()
447            };
448            assert_eq!(
449                ServeError::KeysOutOfOrder(order).to_string(),
450                "1 tenant key(s) do not unwrap under the master key; \
451                 2 key rotation(s) stopped part way; run rekey tenant again; \
452                 3 tenant(s) with data under another key; \
453                 vcon-server check names the tenants",
454                "each count in its fixed place, then where to look"
455            );
456        }
457
458        /// Catalogs the server may not open are counted apart from keys,
459        /// with the system's error, and never a tenant or a path.
460        #[test]
461        fn a_refusal_for_catalogs_it_may_not_open_gives_the_error_not_a_key() {
462            let order = KeyOrder {
463                catalogs_unopened: 2,
464                unopened_error: Some("Permission denied (os error 13)".to_owned()),
465                ..KeyOrder::default()
466            };
467            assert_eq!(
468                ServeError::KeysOutOfOrder(order).to_string(),
469                "2 tenant catalog(s) cannot be opened: Permission denied (os error 13); vcon-server check names the tenants"
470            );
471        }
472    }
473    use crate::retention::Retention;
474
475    #[test]
476    fn the_api_takes_its_limits_and_extensions_from_the_configuration() {
477        let dir = tempfile::tempdir().expect("temp dir");
478        let tenants = Arc::new(
479            Tenants::open(
480                dir.path(),
481                Key::generate().expect("key"),
482                Arc::new(OsFs),
483                Arc::new(SystemClock),
484            )
485            .expect("opens"),
486        );
487        let config = Config {
488            listen: "127.0.0.1:8443".parse().expect("address"),
489            tls_cert: "cert.pem".into(),
490            tls_key: "key.pem".into(),
491            data_dir: dir.path().to_owned(),
492            master_key: "master.key".into(),
493            retention_default: Retention::Months(18),
494            purge_interval: Duration::from_secs(3600),
495            rotation_warn: Duration::from_secs(86400),
496            body_limit: 12_345,
497            inflated_limit: 67_890,
498            read_timeout: Duration::from_secs(17),
499            supported_critical: ["known".to_owned()].into(),
500            mcp: crate::mcp::Limits {
501                calls_per_second: 3,
502                concurrent: 4,
503                response_bytes: 5,
504            },
505            storage: crate::config::Storage::default(),
506            export: crate::config::Export::default(),
507            catalog: crate::config::CatalogStore::Local,
508        };
509        let app = app_from(&config, tenants.clone());
510        assert!(Arc::ptr_eq(&app.tenants, &tenants));
511        assert_eq!(app.limits.body, 12_345);
512        assert_eq!(app.limits.inflated, 67_890);
513        assert_eq!(app.limits.body_timeout, Duration::from_secs(17));
514        assert_eq!(app.supported, config.supported_critical);
515        assert_eq!(app.retention_default, config.retention_default);
516        assert_eq!(app.mcp, config.mcp);
517    }
518
519    mod sweeps {
520        use std::sync::Arc;
521        use std::sync::atomic::{AtomicUsize, Ordering};
522        use std::time::Duration;
523
524        use time::macros::datetime;
525        use uuid::Uuid;
526
527        use crate::audit::Actor;
528        use crate::ids::{KeyId, TenantId};
529        use crate::retention::Retention;
530        use crate::serve::{SweepReport, every, sweep};
531        use crate::store::Caller;
532        use crate::store::testing::vcon;
533        use crate::tenants::{Tenants, fixture};
534
535        const CALLER: Caller = Caller { key: KeyId([7; 8]) };
536
537        /// A vCon stored and deleted in `id` while seven years apply, so
538        /// it waits hidden for a sweep.
539        fn deleted(tenants: &Tenants, id: TenantId, uuid: &str) -> Uuid {
540            let store = tenants.store(id).expect("its store");
541            let (found, body) = vcon(uuid, "kept");
542            store.create(&CALLER, &found, &body).expect("stored");
543            store
544                .delete(&CALLER, found.uuid, Retention::Years(7))
545                .expect("deleted");
546            found.uuid
547        }
548
549        /// How many versions `id` still keeps.
550        fn kept(tenants: &Tenants, id: TenantId) -> u64 {
551            tenants
552                .store(id)
553                .expect("its store")
554                .counts()
555                .expect("counts")
556                .versions
557        }
558
559        #[test]
560        fn a_sweep_purges_what_is_due_in_each_tenant_under_its_own_period() {
561            let f = fixture();
562            let own = f
563                .tenants
564                .create(Actor::Cli, "own", Some(Retention::Days(1)))
565                .expect("made");
566            let default = f.tenants.create(Actor::Cli, "default", None).expect("made");
567            let long = f
568                .tenants
569                .create(Actor::Cli, "long", Some(Retention::Years(7)))
570                .expect("made");
571            deleted(&f.tenants, own, "0199e5c6-0d7a-7c11-8000-000000000001");
572            deleted(&f.tenants, default, "0199e5c6-0d7a-7c11-8000-000000000002");
573            deleted(&f.tenants, long, "0199e5c6-0d7a-7c11-8000-000000000003");
574            f.clock.set(datetime!(2026-10-25 13:00 UTC));
575
576            let report = sweep(&f.tenants, Retention::Days(1));
577
578            assert_eq!(
579                report,
580                SweepReport {
581                    purged: 2,
582                    failed: 0
583                }
584            );
585            assert_eq!(kept(&f.tenants, own), 0);
586            assert_eq!(kept(&f.tenants, default), 0);
587            assert_eq!(kept(&f.tenants, long), 1, "seven years have not passed");
588        }
589
590        #[test]
591        fn a_sweep_goes_on_past_a_tenant_it_cannot_sweep() {
592            let f = fixture();
593            let damaged = f.tenants.create(Actor::Cli, "damaged", None).expect("made");
594            let fine = f.tenants.create(Actor::Cli, "fine", None).expect("made");
595            deleted(&f.tenants, damaged, "0199e5c6-0d7a-7c11-8000-000000000001");
596            deleted(&f.tenants, fine, "0199e5c6-0d7a-7c11-8000-000000000002");
597            f.tenants
598                .conn_for_test()
599                .execute(
600                    "UPDATE tenant SET retention = '7w' WHERE id = ?1",
601                    [damaged.0],
602                )
603                .expect("damaged");
604            f.clock.set(datetime!(2026-10-25 13:00 UTC));
605
606            let report = sweep(&f.tenants, Retention::Days(1));
607
608            assert_eq!(
609                report,
610                SweepReport {
611                    purged: 1,
612                    failed: 1
613                }
614            );
615            assert_eq!(kept(&f.tenants, fine), 0);
616            assert_eq!(kept(&f.tenants, damaged), 1, "left for a later sweep");
617        }
618
619        #[tokio::test(start_paused = true)]
620        async fn every_runs_at_start_then_after_each_interval_until_shutdown() {
621            let runs = Arc::new(AtomicUsize::new(0));
622            let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
623            let counted = runs.clone();
624            let task = tokio::spawn(every(
625                Duration::from_secs(60),
626                async move {
627                    let _ = stopped.await;
628                },
629                move || {
630                    counted.fetch_add(1, Ordering::SeqCst);
631                    async {}
632                },
633            ));
634            let settle = || async {
635                for _ in 0..10 {
636                    tokio::task::yield_now().await;
637                }
638            };
639
640            settle().await;
641            assert_eq!(runs.load(Ordering::SeqCst), 1, "at start");
642            tokio::time::advance(Duration::from_secs(59)).await;
643            settle().await;
644            assert_eq!(runs.load(Ordering::SeqCst), 1, "not before the interval");
645            tokio::time::advance(Duration::from_secs(1)).await;
646            settle().await;
647            assert_eq!(runs.load(Ordering::SeqCst), 2, "after the interval");
648
649            stop.send(()).expect("still running");
650            task.await.expect("ends on shutdown");
651            tokio::time::advance(Duration::from_secs(600)).await;
652            assert_eq!(runs.load(Ordering::SeqCst), 2, "none after shutdown");
653        }
654    }
655}