1use 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#[derive(Debug)]
24pub enum ServeError {
25 DataDir(LockError),
27 MasterKey(KeyError),
29 WrongMasterKey,
31 Open(RegistryError),
33 Registry(TenantError),
35 Storage(StorageError),
37 KeysOutOfOrder(KeyOrder),
39 ParquetRemoved {
42 tenants: u64,
44 },
45 Tls(TlsError),
47 Listen(io::Error),
49 OperatorTls(TlsError),
51 OperatorListen(io::Error),
53 Serve(io::Error),
55}
56
57impl fmt::Display for ServeError {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 match self {
60 ServeError::DataDir(e) => write!(f, "{e}"),
61 ServeError::MasterKey(KeyError::Refused(why)) => {
62 write!(f, "the master key cannot be read: {why}")
63 }
64 ServeError::MasterKey(e) => write!(f, "the master key cannot be read: {e:?}"),
65 ServeError::WrongMasterKey => {
66 f.write_str("the master key is not the one server.sqlite was made under")
67 }
68 ServeError::Open(e) => {
69 write!(f, "the registry cannot be opened: {}", with_causes(e))
70 }
71 ServeError::Registry(e) => write!(f, "server.sqlite cannot be opened: {e:?}"),
72 ServeError::KeysOutOfOrder(order) => {
73 let mut parts = Vec::new();
74 if order.wrapped_elsewhere > 0 {
75 parts.push(format!(
76 "{} tenant key(s) do not unwrap under the master key",
77 order.wrapped_elsewhere
78 ));
79 }
80 if order.rotations_stopped > 0 {
81 parts.push(format!(
82 "{} key rotation(s) stopped part way; run rekey tenant again",
83 order.rotations_stopped
84 ));
85 }
86 if order.data_under_other_keys > 0 {
87 parts.push(format!(
88 "{} tenant(s) with data under another key",
89 order.data_under_other_keys
90 ));
91 }
92 if order.catalogs_unopened > 0 {
93 let why = order
94 .unopened_error
95 .as_ref()
96 .map(|e| format!(": {e}"))
97 .unwrap_or_default();
98 parts.push(format!(
99 "{} tenant catalog(s) cannot be opened{why}",
100 order.catalogs_unopened
101 ));
102 }
103 write!(
104 f,
105 "{}; vcon-server check names the tenants",
106 parts.join("; ")
107 )
108 }
109 ServeError::ParquetRemoved { tenants } => write!(
110 f,
111 "{tenants} tenant(s) have versions packed into Parquet files, and the \
112 configuration has no [storage.parquet]: without it the server packs no more, \
113 and the start no longer refuses a bucket with Object Lock or versioning, either \
114 of which keeps the bytes of a pack file that a purge rewrote; put the \
115 [storage.parquet] table back, since packed versions cannot be turned back into \
116 objects; vcon-server check names the tenants"
117 ),
118 ServeError::Tls(crate::api::TlsError::KeyFile(why)) => {
119 write!(f, "the TLS certificate or key cannot be used: {why}")
120 }
121 ServeError::Tls(e) => write!(f, "the TLS certificate or key cannot be used: {e:?}"),
122 ServeError::Listen(e) => write!(f, "the listening address cannot be bound: {e}"),
123 ServeError::OperatorTls(crate::api::TlsError::KeyFile(why)) => write!(
124 f,
125 "the operator listener's TLS certificate or key cannot be used: {why}"
126 ),
127 ServeError::OperatorTls(e) => write!(
128 f,
129 "the operator listener's TLS certificate or key cannot be used: {e:?}"
130 ),
131 ServeError::OperatorListen(e) => {
132 write!(f, "the operator listening address cannot be bound: {e}")
133 }
134 ServeError::Serve(e) => write!(f, "serving failed: {e}"),
135 ServeError::Storage(e) => write!(f, "the storage cannot be used: {e}"),
136 }
137 }
138}
139
140pub async fn run(config: &Config, shutdown: impl Future<Output = ()>) -> Result<(), ServeError> {
143 let _lock =
144 datadir::lock(&config.data_dir, Work::Serve.sharing()).map_err(ServeError::DataDir)?;
145 let master = Key::load_master(&config.master_key).map_err(ServeError::MasterKey)?;
146 let objects =
147 backend::objects_for(&config.storage, &config.data_dir).map_err(ServeError::Storage)?;
148 backend::catalog_for(&config.catalog)
149 .await
150 .map_err(ServeError::Storage)?;
151 let tenants = Tenants::open_in(
152 &config.data_dir,
153 master,
154 Arc::new(OsFs),
155 Arc::new(SystemClock),
156 objects,
157 )
158 .map_err(|e| match e {
159 RegistryError::WrongKey => ServeError::WrongMasterKey,
160 other => ServeError::Open(other),
161 })?;
162 let order = tenants.key_order().map_err(ServeError::Registry)?;
163 if !order.is_sound() {
164 return Err(ServeError::KeysOutOfOrder(order));
165 }
166 if config.storage.parquet.is_none() {
170 let tenants = tenants
171 .tenants_with_packed_versions()
172 .map_err(ServeError::Registry)?;
173 if tenants > 0 {
174 return Err(ServeError::ParquetRemoved { tenants });
175 }
176 }
177 let tls = api::tls_config(&config.tls_cert, &config.tls_key).map_err(ServeError::Tls)?;
178 let listener = TcpListener::bind(config.listen)
179 .await
180 .map_err(ServeError::Listen)?;
181 let bound = listener.local_addr().map_err(ServeError::Listen)?;
184 let operator = match &config.operator {
187 Some(operator) => {
188 let tls = api::tls_config_named(
189 &operator.tls_cert,
190 &operator.tls_key,
191 operator_key_name(config, operator),
192 )
193 .map_err(ServeError::OperatorTls)?;
194 let listener = TcpListener::bind(operator.listen)
195 .await
196 .map_err(ServeError::OperatorListen)?;
197 let bound = listener.local_addr().map_err(ServeError::OperatorListen)?;
198 Some((listener, tls, bound))
199 }
200 None => None,
201 };
202 let tenants = Arc::new(tenants);
203 let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
206 let (swept, default) = (tenants.clone(), config.retention_default);
207 let sweeper = tokio::spawn(every(
208 config.purge_interval,
209 async {
210 let _ = stopped.await;
211 },
212 move || {
213 let tenants = swept.clone();
214 async move {
215 let _ = tokio::task::spawn_blocking(move || sweep(&tenants, default)).await;
216 }
217 },
218 ));
219 let (stop_packing, packing_stopped) = tokio::sync::oneshot::channel::<()>();
222 let packer = config.storage.parquet.map(|parquet| {
223 let packed = tenants.clone();
224 tokio::spawn(every(
225 parquet.pack_interval,
226 async {
227 let _ = packing_stopped.await;
228 },
229 move || {
230 let tenants = packed.clone();
231 async move {
232 let _ = tokio::task::spawn_blocking(move || pack_all(&tenants, &parquet)).await;
233 }
234 },
235 ))
236 });
237 let (stop_warning, warning_stopped) = tokio::sync::oneshot::channel::<()>();
239 let (watched, rotation_warn) = (tenants.clone(), config.rotation_warn);
240 let warner = tokio::spawn(every(
241 ROTATION_CHECK,
242 async {
243 let _ = warning_stopped.await;
244 },
245 move || {
246 let tenants = watched.clone();
247 async move {
248 let _ = tokio::task::spawn_blocking(move || {
249 warn_if_rotation_overdue(&tenants, rotation_warn);
250 })
251 .await;
252 }
253 },
254 ));
255 let (halt, halted) = tokio::sync::watch::channel(());
258 let until_halted = |mut halted: tokio::sync::watch::Receiver<()>| async move {
259 let _ = halted.changed().await;
261 };
262 let counted = tenants.clone();
266 let counts_full = move |key: &'static str| {
267 let tenants = counted.clone();
268 move || {
269 let tenants = tenants.clone();
270 tokio::task::spawn_blocking(move || tenants.count_listener_full(key));
271 }
272 };
273 let both = async {
274 let Some((operator_listener, operator_tls, operator_bound)) = operator else {
275 let full = counts_full("listen");
276 let app = app_from(config, tenants, Plane::Both);
277 tracing::info!(listen = %bound, "serving");
278 return api::serve_observed(
279 listener,
280 tls,
281 api::router(Arc::new(app)),
282 until_halted(halted),
283 config.connection,
284 full,
285 )
286 .await;
287 };
288 let (tenant_full, operator_full) = (counts_full("listen"), counts_full("operator.listen"));
289 let tenant_app = app_from(config, tenants.clone(), Plane::Tenant);
290 let operator_app = app_from(config, tenants, Plane::Operator);
291 tracing::info!(operator_listen = %operator_bound, "the operator listener is bound");
294 tracing::info!(listen = %bound, "serving");
295 let (tenant, operator) = tokio::join!(
296 api::serve_observed(
297 listener,
298 tls,
299 api::router(Arc::new(tenant_app)),
300 until_halted(halted.clone()),
301 config.connection,
302 tenant_full,
303 ),
304 api::serve_observed(
305 operator_listener,
306 operator_tls,
307 api::router(Arc::new(operator_app)),
308 until_halted(halted),
309 config.connection,
310 operator_full,
311 ),
312 );
313 tenant.and(operator)
314 };
315 let mut both = std::pin::pin!(both);
316 let served = tokio::select! {
317 served = &mut both => served,
318 () = shutdown => {
319 let _ = halt.send(());
320 both.await
321 }
322 };
323 let _ = stop.send(());
324 let _ = stop_warning.send(());
325 let _ = stop_packing.send(());
326 let _ = sweeper.await;
327 let _ = warner.await;
328 if let Some(packer) = packer {
329 let _ = packer.await;
330 }
331 served.map_err(ServeError::Serve)?;
332 tracing::info!("stopped");
333 Ok(())
334}
335
336#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
338pub struct PackRunReport {
339 pub files: u64,
341 pub versions: u64,
343 pub failed: u64,
345}
346
347pub fn pack_all(tenants: &Tenants, settings: &ParquetSettings) -> PackRunReport {
352 let mut report = PackRunReport::default();
353 let plan = crate::store::packer::PackPlan {
354 grace: settings.reader_grace,
355 ..crate::store::packer::PackPlan::with_limit(settings.pack_limit)
356 };
357 match tenants.ids() {
358 Ok(ids) => {
359 for id in ids {
360 match tenants.store(id).map(|store| store.pack(&plan)) {
361 Ok(Ok(done)) => {
362 report.files += done.files;
363 report.versions += done.versions;
364 }
365 _ => report.failed += 1,
366 }
367 }
368 }
369 Err(_) => report.failed += 1,
370 }
371 tracing::info!(
372 files = report.files,
373 versions = report.versions,
374 failed = report.failed,
375 "pack run"
376 );
377 report
378}
379
380#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
382pub struct SweepReport {
383 pub purged: u64,
385 pub failed: u64,
387}
388
389pub fn sweep(tenants: &Tenants, default: Retention) -> SweepReport {
394 let mut report = SweepReport::default();
395 match tenants.ids() {
396 Ok(ids) => {
397 for id in ids {
398 let purged = tenants.retention(id).and_then(|own| {
399 let store = tenants.store(id)?;
400 Ok(store.purge_due(crate::tenants::kept_for(own, default)))
401 });
402 match purged {
403 Ok(Ok(done)) => report.purged += done.purged,
404 _ => report.failed += 1,
405 }
406 }
407 }
408 Err(_) => report.failed += 1,
409 }
410 tracing::info!(
411 purged = report.purged,
412 failed = report.failed,
413 "purge sweep"
414 );
415 report
416}
417
418pub async fn every<F, Fut>(interval: Duration, shutdown: impl Future<Output = ()>, mut job: F)
421where
422 F: FnMut() -> Fut,
423 Fut: Future<Output = ()>,
424{
425 tokio::pin!(shutdown);
426 loop {
427 tokio::select! {
428 biased;
429 () = &mut shutdown => return,
430 () = job() => {}
431 }
432 tokio::select! {
433 biased;
434 () = &mut shutdown => return,
435 () = tokio::time::sleep(interval) => {}
436 }
437 }
438}
439
440fn operator_key_name(config: &Config, operator: &Operator) -> &'static str {
444 if operator.tls_key == config.tls_key && operator.tls_cert == config.tls_cert {
445 "tls.key"
446 } else {
447 "operator.tls.key"
448 }
449}
450
451fn app_from(config: &Config, tenants: Arc<Tenants>, plane: Plane) -> App {
454 App {
455 tenants,
456 limits: Limits {
457 body: config.body_limit,
458 inflated: config.inflated_limit,
459 body_timeout: config.read_timeout,
460 },
461 supported: config.supported_critical.clone(),
462 retention_default: config.retention_default,
463 mcp: config.mcp,
464 plane,
465 reports: crate::api::ReportGate::new(config.reports),
466 }
467}
468
469pub fn rotation_overdue(
472 backlog: &RotationBacklog,
473 rotation_warn: Duration,
474 now: OffsetDateTime,
475) -> bool {
476 [backlog.oldest_purge, backlog.oldest_removal]
477 .into_iter()
478 .flatten()
479 .any(|at| now - at > rotation_warn)
480}
481
482const ROTATION_CHECK: Duration = Duration::from_secs(86_400);
484
485fn warn_if_rotation_overdue(tenants: &Tenants, rotation_warn: Duration) {
487 match tenants.rotation_backlog() {
488 Ok(backlog) if rotation_overdue(&backlog, rotation_warn, SystemClock.now()) => {
489 tracing::warn!(
490 tenants_with_purges = backlog.tenants_with_purges,
491 purges = backlog.purges,
492 removals = backlog.removals,
493 "key rotation overdue: purged vCons and removed tenants stay readable on old copies until it"
494 );
495 }
496 Ok(_) => {}
497 Err(_) => tracing::warn!("the key rotation backlog could not be read"),
498 }
499}
500
501#[cfg(test)]
502mod tests {
503 use std::time::Duration;
504
505 use super::*;
506
507 mod startup {
508 use time::macros::datetime;
509
510 use super::*;
511
512 #[test]
515 fn a_start_without_storage_parquet_over_packed_versions_names_the_table() {
516 assert_eq!(
517 ServeError::ParquetRemoved { tenants: 2 }.to_string(),
518 "2 tenant(s) have versions packed into Parquet files, and the configuration has no \
519 [storage.parquet]: without it the server packs no more, and the start no longer \
520 refuses a bucket with Object Lock or versioning, either of which keeps the bytes of \
521 a pack file that a purge rewrote; put the [storage.parquet] table back, since packed \
522 versions cannot be turned back into objects; vcon-server check names the tenants",
523 "the refusal's text"
524 );
525 }
526
527 const NOW: OffsetDateTime = datetime!(2026-10-25 12:00 UTC);
528 const DAY: Duration = Duration::from_secs(86_400);
529
530 #[test]
531 fn rotation_is_overdue_once_the_oldest_waiting_work_passes_rotation_warn() {
532 let backlog =
533 |purge: Option<OffsetDateTime>, removal: Option<OffsetDateTime>| RotationBacklog {
534 tenants_with_purges: u64::from(purge.is_some()),
535 purges: u64::from(purge.is_some()),
536 oldest_purge: purge,
537 removals: u64::from(removal.is_some()),
538 oldest_removal: removal,
539 };
540 let day_ago = Some(datetime!(2026-10-24 12:00 UTC));
541 let older = Some(datetime!(2026-10-24 11:59:59 UTC));
542 for (b, overdue) in [
543 (backlog(None, None), false),
544 (backlog(day_ago, None), false),
545 (backlog(older, None), true),
546 (backlog(None, older), true),
547 (backlog(day_ago, older), true),
548 ] {
549 assert_eq!(rotation_overdue(&b, DAY, NOW), overdue, "{b:?}");
550 }
551 }
552
553 #[test]
554 fn a_refusal_for_keys_out_of_order_counts_and_points_at_check() {
555 let order = KeyOrder {
556 wrapped_elsewhere: 1,
557 rotations_stopped: 2,
558 data_under_other_keys: 3,
559 ..KeyOrder::default()
560 };
561 assert_eq!(
562 ServeError::KeysOutOfOrder(order).to_string(),
563 "1 tenant key(s) do not unwrap under the master key; \
564 2 key rotation(s) stopped part way; run rekey tenant again; \
565 3 tenant(s) with data under another key; \
566 vcon-server check names the tenants",
567 "each count in its fixed place, then where to look"
568 );
569 }
570
571 #[test]
574 fn a_refusal_for_catalogs_it_may_not_open_gives_the_error_not_a_key() {
575 let order = KeyOrder {
576 catalogs_unopened: 2,
577 unopened_error: Some("Permission denied (os error 13)".to_owned()),
578 ..KeyOrder::default()
579 };
580 assert_eq!(
581 ServeError::KeysOutOfOrder(order).to_string(),
582 "2 tenant catalog(s) cannot be opened: Permission denied (os error 13); vcon-server check names the tenants"
583 );
584 }
585 }
586 use crate::retention::Retention;
587
588 #[test]
589 fn the_api_takes_its_limits_and_extensions_from_the_configuration() {
590 let dir = tempfile::tempdir().expect("temp dir");
591 let tenants = Arc::new(
592 Tenants::open(
593 dir.path(),
594 Key::generate().expect("key"),
595 Arc::new(OsFs),
596 Arc::new(SystemClock),
597 )
598 .expect("opens"),
599 );
600 let config = Config {
601 listen: "127.0.0.1:8443".parse().expect("address"),
602 tls_cert: "cert.pem".into(),
603 tls_key: "key.pem".into(),
604 data_dir: dir.path().to_owned(),
605 master_key: "master.key".into(),
606 retention_default: Retention::Months(18),
607 purge_interval: Duration::from_secs(3600),
608 rotation_warn: Duration::from_secs(86400),
609 body_limit: 12_345,
610 inflated_limit: 67_890,
611 read_timeout: Duration::from_secs(17),
612 connection: crate::api::ConnectionLimits::default(),
613 supported_critical: ["known".to_owned()].into(),
614 mcp: crate::mcp::Limits {
615 calls_per_second: 3,
616 concurrent: 4,
617 response_bytes: 5,
618 },
619 reports: crate::api::ReportLimits::DEFAULT,
620 storage: crate::config::Storage::default(),
621 export: crate::config::Export::default(),
622 catalog: crate::config::CatalogStore::Local,
623 operator: None,
624 };
625 let app = app_from(&config, tenants.clone(), Plane::Tenant);
626 assert_eq!(app.plane, Plane::Tenant, "the plane it was given");
627 assert!(Arc::ptr_eq(&app.tenants, &tenants));
628 assert_eq!(app.limits.body, 12_345);
629 assert_eq!(app.limits.inflated, 67_890);
630 assert_eq!(app.limits.body_timeout, Duration::from_secs(17));
631 assert_eq!(app.supported, config.supported_critical);
632 assert_eq!(app.retention_default, config.retention_default);
633 assert_eq!(app.mcp, config.mcp);
634 }
635
636 mod sweeps {
637 use std::sync::Arc;
638 use std::sync::atomic::{AtomicUsize, Ordering};
639 use std::time::Duration;
640
641 use time::macros::datetime;
642 use uuid::Uuid;
643
644 use crate::audit::Actor;
645 use crate::ids::{KeyId, TenantId};
646 use crate::retention::Retention;
647 use crate::serve::{SweepReport, every, sweep};
648 use crate::store::Caller;
649 use crate::store::testing::vcon;
650 use crate::tenants::{Tenants, fixture};
651
652 const CALLER: Caller = Caller { key: KeyId([7; 8]) };
653
654 fn deleted(tenants: &Tenants, id: TenantId, uuid: &str) -> Uuid {
657 let store = tenants.store(id).expect("its store");
658 let (found, body) = vcon(uuid, "kept");
659 store.create(&CALLER, &found, &body).expect("stored");
660 store
661 .delete(&CALLER, found.uuid, Retention::Years(7))
662 .expect("deleted");
663 found.uuid
664 }
665
666 fn kept(tenants: &Tenants, id: TenantId) -> u64 {
668 tenants
669 .store(id)
670 .expect("its store")
671 .counts()
672 .expect("counts")
673 .versions
674 }
675
676 #[test]
677 fn a_sweep_purges_what_is_due_in_each_tenant_under_its_own_period() {
678 let f = fixture();
679 let own = f
680 .tenants
681 .create(Actor::Cli, "own", Some(Retention::Days(1)))
682 .expect("made");
683 let default = f.tenants.create(Actor::Cli, "default", None).expect("made");
684 let long = f
685 .tenants
686 .create(Actor::Cli, "long", Some(Retention::Years(7)))
687 .expect("made");
688 deleted(&f.tenants, own, "0199e5c6-0d7a-7c11-8000-000000000001");
689 deleted(&f.tenants, default, "0199e5c6-0d7a-7c11-8000-000000000002");
690 deleted(&f.tenants, long, "0199e5c6-0d7a-7c11-8000-000000000003");
691 f.clock.set(datetime!(2026-10-25 13:00 UTC));
692
693 let report = sweep(&f.tenants, Retention::Days(1));
694
695 assert_eq!(
696 report,
697 SweepReport {
698 purged: 2,
699 failed: 0
700 }
701 );
702 assert_eq!(kept(&f.tenants, own), 0);
703 assert_eq!(kept(&f.tenants, default), 0);
704 assert_eq!(kept(&f.tenants, long), 1, "seven years have not passed");
705 }
706
707 #[test]
708 fn a_sweep_goes_on_past_a_tenant_it_cannot_sweep() {
709 let f = fixture();
710 let damaged = f.tenants.create(Actor::Cli, "damaged", None).expect("made");
711 let fine = f.tenants.create(Actor::Cli, "fine", None).expect("made");
712 deleted(&f.tenants, damaged, "0199e5c6-0d7a-7c11-8000-000000000001");
713 deleted(&f.tenants, fine, "0199e5c6-0d7a-7c11-8000-000000000002");
714 f.tenants
715 .conn_for_test()
716 .execute(
717 "UPDATE tenant SET retention = '7w' WHERE id = ?1",
718 [damaged.0],
719 )
720 .expect("damaged");
721 f.clock.set(datetime!(2026-10-25 13:00 UTC));
722
723 let report = sweep(&f.tenants, Retention::Days(1));
724
725 assert_eq!(
726 report,
727 SweepReport {
728 purged: 1,
729 failed: 1
730 }
731 );
732 assert_eq!(kept(&f.tenants, fine), 0);
733 assert_eq!(kept(&f.tenants, damaged), 1, "left for a later sweep");
734 }
735
736 #[tokio::test(start_paused = true)]
737 async fn every_runs_at_start_then_after_each_interval_until_shutdown() {
738 let runs = Arc::new(AtomicUsize::new(0));
739 let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
740 let counted = runs.clone();
741 let task = tokio::spawn(every(
742 Duration::from_secs(60),
743 async move {
744 let _ = stopped.await;
745 },
746 move || {
747 counted.fetch_add(1, Ordering::SeqCst);
748 async {}
749 },
750 ));
751 let settle = || async {
752 for _ in 0..10 {
753 tokio::task::yield_now().await;
754 }
755 };
756
757 settle().await;
758 assert_eq!(runs.load(Ordering::SeqCst), 1, "at start");
759 tokio::time::advance(Duration::from_secs(59)).await;
760 settle().await;
761 assert_eq!(runs.load(Ordering::SeqCst), 1, "not before the interval");
762 tokio::time::advance(Duration::from_secs(1)).await;
763 settle().await;
764 assert_eq!(runs.load(Ordering::SeqCst), 2, "after the interval");
765
766 stop.send(()).expect("still running");
767 task.await.expect("ends on shutdown");
768 tokio::time::advance(Duration::from_secs(600)).await;
769 assert_eq!(runs.load(Ordering::SeqCst), 2, "none after shutdown");
770 }
771 }
772}