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 WrongDatabaseKey,
34 Open(RegistryError),
36 Registry(TenantError),
38 Storage(StorageError),
40 KeysOutOfOrder(KeyOrder),
42 ParquetRemoved {
45 tenants: u64,
47 },
48 Tls(TlsError),
50 Listen(io::Error),
52 OperatorTls(TlsError),
54 OperatorListen(io::Error),
56 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
144pub 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
158pub(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
177async 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
186pub(crate) type Opened = (datadir::DataDirLock, backend::Catalogs, Tenants);
189
190fn 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
203pub(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
213fn 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 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
253async 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 let bound = listener.local_addr().map_err(ServeError::Listen)?;
267 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 if let Some((_, _, operator_bound)) = &operator {
290 tracing::info!(operator_listen = %operator_bound, "the operator listener is bound");
291 }
292 tracing::info!(listen = %bound, "serving");
293 let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
296 let (swept, default) = (tenants.clone(), config.retention_default);
297 let sweeper = tokio::spawn(every(
298 config.purge_interval,
299 async {
300 let _ = stopped.await;
301 },
302 move || {
303 let tenants = swept.clone();
304 async move {
305 let _ = tokio::task::spawn_blocking(move || sweep(&tenants, default)).await;
306 }
307 },
308 ));
309 let (stop_packing, packing_stopped) = tokio::sync::oneshot::channel::<()>();
312 let packer = config.storage.parquet.map(|parquet| {
313 let packed = tenants.clone();
314 tokio::spawn(every(
315 parquet.pack_interval,
316 async {
317 let _ = packing_stopped.await;
318 },
319 move || {
320 let tenants = packed.clone();
321 async move {
322 let _ = tokio::task::spawn_blocking(move || pack_all(&tenants, &parquet)).await;
323 }
324 },
325 ))
326 });
327 let (stop_warning, warning_stopped) = tokio::sync::oneshot::channel::<()>();
329 let (watched, rotation_warn) = (tenants.clone(), config.rotation_warn);
330 let warner = tokio::spawn(every(
331 ROTATION_CHECK,
332 async {
333 let _ = warning_stopped.await;
334 },
335 move || {
336 let tenants = watched.clone();
337 async move {
338 let _ = tokio::task::spawn_blocking(move || {
339 warn_if_rotation_overdue(&tenants, rotation_warn);
340 })
341 .await;
342 }
343 },
344 ));
345 let (halt, halted) = tokio::sync::watch::channel(());
348 let until_halted = |mut halted: tokio::sync::watch::Receiver<()>| async move {
349 let _ = halted.changed().await;
351 };
352 let counted = tenants.clone();
356 let counts_full = move |key: &'static str| {
357 let tenants = counted.clone();
358 move || {
359 let tenants = tenants.clone();
360 tokio::task::spawn_blocking(move || tenants.count_listener_full(key));
361 }
362 };
363 let both = async {
364 let Some((operator_listener, operator_tls, _)) = operator else {
365 let full = counts_full("listen");
366 let app = app_from(config, tenants, Plane::Both);
367 return api::serve_observed(
368 listener,
369 tls,
370 api::router(Arc::new(app)),
371 until_halted(halted),
372 config.connection,
373 full,
374 )
375 .await;
376 };
377 let (tenant_full, operator_full) = (counts_full("listen"), counts_full("operator.listen"));
378 let tenant_app = app_from(config, tenants.clone(), Plane::Tenant);
379 let operator_app = app_from(config, tenants, Plane::Operator);
380 let (tenant, operator) = tokio::join!(
381 api::serve_observed(
382 listener,
383 tls,
384 api::router(Arc::new(tenant_app)),
385 until_halted(halted.clone()),
386 config.connection,
387 tenant_full,
388 ),
389 api::serve_observed(
390 operator_listener,
391 operator_tls,
392 api::router(Arc::new(operator_app)),
393 until_halted(halted),
394 config.connection,
395 operator_full,
396 ),
397 );
398 tenant.and(operator)
399 };
400 let mut both = std::pin::pin!(both);
401 let served = tokio::select! {
402 served = &mut both => served,
403 () = shutdown => {
404 let _ = halt.send(());
405 both.await
406 }
407 };
408 let _ = stop.send(());
409 let _ = stop_warning.send(());
410 let _ = stop_packing.send(());
411 let _ = sweeper.await;
412 let _ = warner.await;
413 if let Some(packer) = packer {
414 let _ = packer.await;
415 }
416 served.map_err(ServeError::Serve)
417}
418
419#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
421pub struct PackRunReport {
422 pub files: u64,
424 pub versions: u64,
426 pub failed: u64,
428}
429
430pub fn pack_all(tenants: &Tenants, settings: &ParquetSettings) -> PackRunReport {
435 let mut report = PackRunReport::default();
436 let plan = crate::store::packer::PackPlan {
437 grace: settings.reader_grace,
438 ..crate::store::packer::PackPlan::with_limit(settings.pack_limit)
439 };
440 match tenants.ids() {
441 Ok(ids) => {
442 for id in ids {
443 match tenants.store(id).map(|store| store.pack(&plan)) {
444 Ok(Ok(done)) => {
445 report.files += done.files;
446 report.versions += done.versions;
447 }
448 _ => report.failed += 1,
449 }
450 }
451 }
452 Err(_) => report.failed += 1,
453 }
454 tracing::info!(
455 files = report.files,
456 versions = report.versions,
457 failed = report.failed,
458 "pack run"
459 );
460 report
461}
462
463#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
465pub struct SweepReport {
466 pub purged: u64,
468 pub failed: u64,
470}
471
472pub fn sweep(tenants: &Tenants, default: Retention) -> SweepReport {
477 let mut report = SweepReport::default();
478 match tenants.ids() {
479 Ok(ids) => {
480 for id in ids {
481 let purged = tenants.retention(id).and_then(|own| {
482 let store = tenants.store(id)?;
483 Ok(store.purge_due(crate::tenants::kept_for(own, default)))
484 });
485 match purged {
486 Ok(Ok(done)) => report.purged += done.purged,
487 _ => report.failed += 1,
488 }
489 }
490 }
491 Err(_) => report.failed += 1,
492 }
493 tracing::info!(
494 purged = report.purged,
495 failed = report.failed,
496 "purge sweep"
497 );
498 report
499}
500
501pub async fn every<F, Fut>(interval: Duration, shutdown: impl Future<Output = ()>, mut job: F)
504where
505 F: FnMut() -> Fut,
506 Fut: Future<Output = ()>,
507{
508 tokio::pin!(shutdown);
509 loop {
510 tokio::select! {
511 biased;
512 () = &mut shutdown => return,
513 () = job() => {}
514 }
515 tokio::select! {
516 biased;
517 () = &mut shutdown => return,
518 () = tokio::time::sleep(interval) => {}
519 }
520 }
521}
522
523fn operator_key_name(config: &Config, operator: &Operator) -> &'static str {
527 if operator.tls_key == config.tls_key && operator.tls_cert == config.tls_cert {
528 "tls.key"
529 } else {
530 "operator.tls.key"
531 }
532}
533
534fn app_from(config: &Config, tenants: Arc<Tenants>, plane: Plane) -> App {
537 tenants.allow_no_expiry(config.keys_no_expiry);
538 App {
539 tenants,
540 limits: Limits {
541 body: config.body_limit,
542 inflated: config.inflated_limit,
543 body_timeout: config.read_timeout,
544 },
545 supported: config.supported_critical.clone(),
546 retention_default: config.retention_default,
547 mcp: config.mcp,
548 plane,
549 reports: crate::api::ReportGate::new(config.reports),
550 origin: origin_for(config, plane),
551 }
552}
553
554fn origin_for(config: &Config, plane: Plane) -> Option<crate::session::Origin> {
558 match plane {
559 Plane::Both | Plane::Tenant => config.public_origin.clone(),
560 Plane::Operator => config
561 .operator
562 .as_ref()
563 .and_then(|operator| operator.public_origin.clone()),
564 }
565}
566
567pub fn rotation_overdue(
570 backlog: &RotationBacklog,
571 rotation_warn: Duration,
572 now: OffsetDateTime,
573) -> bool {
574 [backlog.oldest_purge, backlog.oldest_removal]
575 .into_iter()
576 .flatten()
577 .any(|at| now - at > rotation_warn)
578}
579
580const ROTATION_CHECK: Duration = Duration::from_secs(86_400);
582
583fn warn_if_rotation_overdue(tenants: &Tenants, rotation_warn: Duration) {
585 match tenants.rotation_backlog() {
586 Ok(backlog) if rotation_overdue(&backlog, rotation_warn, SystemClock.now()) => {
587 tracing::warn!(
588 tenants_with_purges = backlog.tenants_with_purges,
589 purges = backlog.purges,
590 removals = backlog.removals,
591 "key rotation overdue: purged vCons and removed tenants stay readable on old copies until it"
592 );
593 }
594 Ok(_) => {}
595 Err(_) => tracing::warn!("the key rotation backlog could not be read"),
596 }
597}
598
599#[cfg(test)]
600mod start_tests;
601
602#[cfg(test)]
603mod tests {
604 use std::time::Duration;
605
606 use super::*;
607
608 mod startup {
609 use time::macros::datetime;
610
611 use super::*;
612
613 #[test]
616 fn a_start_without_storage_parquet_over_packed_versions_names_the_table() {
617 assert_eq!(
618 ServeError::ParquetRemoved { tenants: 2 }.to_string(),
619 "2 tenant(s) have versions packed into Parquet files, and the configuration has no \
620 [storage.parquet]: without it the server packs no more, and the start no longer \
621 refuses a bucket with Object Lock or versioning, either of which keeps the bytes of \
622 a pack file that a purge rewrote; put the [storage.parquet] table back, since packed \
623 versions cannot be turned back into objects; vcon-server check names the tenants",
624 "the refusal's text"
625 );
626 }
627
628 const NOW: OffsetDateTime = datetime!(2026-10-25 12:00 UTC);
629 const DAY: Duration = Duration::from_secs(86_400);
630
631 #[test]
632 fn rotation_is_overdue_once_the_oldest_waiting_work_passes_rotation_warn() {
633 let backlog =
634 |purge: Option<OffsetDateTime>, removal: Option<OffsetDateTime>| RotationBacklog {
635 tenants_with_purges: u64::from(purge.is_some()),
636 purges: u64::from(purge.is_some()),
637 oldest_purge: purge,
638 removals: u64::from(removal.is_some()),
639 oldest_removal: removal,
640 };
641 let day_ago = Some(datetime!(2026-10-24 12:00 UTC));
642 let older = Some(datetime!(2026-10-24 11:59:59 UTC));
643 for (b, overdue) in [
644 (backlog(None, None), false),
645 (backlog(day_ago, None), false),
646 (backlog(older, None), true),
647 (backlog(None, older), true),
648 (backlog(day_ago, older), true),
649 ] {
650 assert_eq!(rotation_overdue(&b, DAY, NOW), overdue, "{b:?}");
651 }
652 }
653
654 #[test]
655 fn a_refusal_for_keys_out_of_order_counts_and_points_at_check() {
656 let order = KeyOrder {
657 wrapped_elsewhere: 1,
658 rotations_stopped: 2,
659 data_under_other_keys: 3,
660 ..KeyOrder::default()
661 };
662 assert_eq!(
663 ServeError::KeysOutOfOrder(order).to_string(),
664 "1 tenant key(s) do not unwrap under the master key; \
665 2 key rotation(s) stopped part way; run rekey tenant again; \
666 3 tenant(s) with data under another key; \
667 vcon-server check names the tenants",
668 "each count in its fixed place, then where to look"
669 );
670 }
671
672 #[test]
675 fn a_refusal_for_catalogs_it_may_not_open_gives_the_error_not_a_key() {
676 let order = KeyOrder {
677 catalogs_unopened: 2,
678 unopened_error: Some("Permission denied (os error 13)".to_owned()),
679 ..KeyOrder::default()
680 };
681 assert_eq!(
682 ServeError::KeysOutOfOrder(order).to_string(),
683 "2 tenant catalog(s) cannot be opened: Permission denied (os error 13); vcon-server check names the tenants"
684 );
685 }
686 }
687 use crate::retention::Retention;
688
689 #[test]
690 fn the_api_takes_its_limits_and_extensions_from_the_configuration() {
691 let dir = tempfile::tempdir().expect("temp dir");
692 let tenants = Arc::new(
693 Tenants::open(
694 dir.path(),
695 Key::generate().expect("key"),
696 Arc::new(OsFs),
697 Arc::new(SystemClock),
698 )
699 .expect("opens"),
700 );
701 let config = Config {
702 listen: "127.0.0.1:8443".parse().expect("address"),
703 tls_cert: "cert.pem".into(),
704 tls_key: "key.pem".into(),
705 data_dir: dir.path().to_owned(),
706 master_key: "master.key".into(),
707 retention_default: Retention::Months(18),
708 purge_interval: Duration::from_secs(3600),
709 rotation_warn: Duration::from_secs(86400),
710 body_limit: 12_345,
711 inflated_limit: 67_890,
712 read_timeout: Duration::from_secs(17),
713 connection: crate::api::ConnectionLimits::default(),
714 supported_critical: ["known".to_owned()].into(),
715 mcp: crate::mcp::Limits {
716 calls_per_second: 3,
717 concurrent: 4,
718 response_bytes: 5,
719 },
720 reports: crate::api::ReportLimits::DEFAULT,
721 storage: crate::config::Storage::default(),
722 export: crate::config::Export::default(),
723 catalog: crate::config::CatalogStore::Local,
724 operator: None,
725 public_origin: None,
726 keys_no_expiry: false,
727 };
728 assert!(
729 tenants.no_expiry_allowed(),
730 "before the configuration is applied a key may have no expiry"
731 );
732 let app = app_from(&config, tenants.clone(), Plane::Tenant);
733 assert!(
734 !tenants.no_expiry_allowed(),
735 "keys.no_expiry = false reaches the registry the API makes keys in"
736 );
737 assert_eq!(app.plane, Plane::Tenant, "the plane it was given");
738 assert!(Arc::ptr_eq(&app.tenants, &tenants));
739 assert_eq!(app.limits.body, 12_345);
740 assert_eq!(app.limits.inflated, 67_890);
741 assert_eq!(app.limits.body_timeout, Duration::from_secs(17));
742 assert_eq!(app.supported, config.supported_critical);
743 assert_eq!(app.retention_default, config.retention_default);
744 assert_eq!(app.mcp, config.mcp);
745 assert_eq!(app.origin, None, "no public origin is configured");
746 }
747
748 fn configured(first: &str, last: &str) -> Config {
750 let text = format!(
751 "{first}listen = \"127.0.0.1:8443\"\ndata_dir = \"/var/lib/vcon-server\"\n\
752 master_key = \"/etc/vcon-server/master.key\"\n[tls]\ncert = \"/c.pem\"\n\
753 key = \"/k.pem\"\n{last}"
754 );
755 crate::config::parse(&text).expect("a configuration")
756 }
757
758 const OPERATOR: &str =
759 "[operator]\nlisten = \"127.0.0.1:8444\"\npublic_origin = \"https://ops.example.com\"\n";
760
761 #[test]
762 fn each_listener_takes_its_own_public_origin() {
763 let config = configured("public_origin = \"https://vcon.example.com\"\n", OPERATOR);
764 let origin = |plane| origin_for(&config, plane).map(|o| o.as_str().to_owned());
765 assert_eq!(
766 origin(Plane::Tenant).as_deref(),
767 Some("https://vcon.example.com"),
768 "`listen` takes public_origin"
769 );
770 assert_eq!(
771 origin(Plane::Operator).as_deref(),
772 Some("https://ops.example.com"),
773 "`operator.listen` takes operator.public_origin"
774 );
775 }
776
777 #[test]
778 fn the_one_listener_of_a_server_takes_public_origin_for_both_planes() {
779 let config = configured("public_origin = \"https://vcon.example.com\"\n", "");
780 assert_eq!(
781 origin_for(&config, Plane::Both),
782 crate::session::Origin::parse("https://vcon.example.com"),
783 "tenants' and operators' sessions come from the one origin"
784 );
785 }
786
787 #[test]
788 fn a_listener_with_no_public_origin_has_none_and_does_not_take_the_other_s() {
789 let config = configured("", OPERATOR);
790 assert_eq!(
791 origin_for(&config, Plane::Tenant),
792 None,
793 "not the operator's"
794 );
795 let config = configured("public_origin = \"https://vcon.example.com\"\n", "");
796 assert_eq!(
797 origin_for(&config, Plane::Operator),
798 None,
799 "not the tenant's"
800 );
801 let config = configured("", "");
802 assert_eq!(origin_for(&config, Plane::Both), None, "none is configured");
803 }
804
805 mod sweeps {
806 use std::sync::Arc;
807 use std::sync::atomic::{AtomicUsize, Ordering};
808 use std::time::Duration;
809
810 use time::macros::datetime;
811 use uuid::Uuid;
812
813 use crate::audit::Actor;
814 use crate::ids::{KeyId, TenantId};
815 use crate::retention::Retention;
816 use crate::serve::{SweepReport, every, sweep};
817 use crate::store::Caller;
818 use crate::store::testing::vcon;
819 use crate::tenants::{Tenants, fixture};
820
821 const CALLER: Caller = Caller { key: KeyId([7; 8]) };
822
823 fn deleted(tenants: &Tenants, id: TenantId, uuid: &str) -> Uuid {
826 let store = tenants.store(id).expect("its store");
827 let (found, body) = vcon(uuid, "kept");
828 store.create(&CALLER, &found, &body).expect("stored");
829 store
830 .delete(&CALLER, found.uuid, Retention::Years(7))
831 .expect("deleted");
832 found.uuid
833 }
834
835 fn kept(tenants: &Tenants, id: TenantId) -> u64 {
837 tenants
838 .store(id)
839 .expect("its store")
840 .counts()
841 .expect("counts")
842 .versions
843 }
844
845 #[test]
846 fn a_sweep_purges_what_is_due_in_each_tenant_under_its_own_period() {
847 let f = fixture();
848 let own = f
849 .tenants
850 .create(Actor::Cli, "own", Some(Retention::Days(1)))
851 .expect("made");
852 let default = f.tenants.create(Actor::Cli, "default", None).expect("made");
853 let long = f
854 .tenants
855 .create(Actor::Cli, "long", Some(Retention::Years(7)))
856 .expect("made");
857 deleted(&f.tenants, own, "0199e5c6-0d7a-7c11-8000-000000000001");
858 deleted(&f.tenants, default, "0199e5c6-0d7a-7c11-8000-000000000002");
859 deleted(&f.tenants, long, "0199e5c6-0d7a-7c11-8000-000000000003");
860 f.clock.set(datetime!(2026-10-25 13:00 UTC));
861
862 let report = sweep(&f.tenants, Retention::Days(1));
863
864 assert_eq!(
865 report,
866 SweepReport {
867 purged: 2,
868 failed: 0
869 }
870 );
871 assert_eq!(kept(&f.tenants, own), 0);
872 assert_eq!(kept(&f.tenants, default), 0);
873 assert_eq!(kept(&f.tenants, long), 1, "seven years have not passed");
874 }
875
876 #[test]
877 fn a_sweep_goes_on_past_a_tenant_it_cannot_sweep() {
878 let f = fixture();
879 let damaged = f.tenants.create(Actor::Cli, "damaged", None).expect("made");
880 let fine = f.tenants.create(Actor::Cli, "fine", None).expect("made");
881 deleted(&f.tenants, damaged, "0199e5c6-0d7a-7c11-8000-000000000001");
882 deleted(&f.tenants, fine, "0199e5c6-0d7a-7c11-8000-000000000002");
883 f.tenants
884 .conn_for_test()
885 .execute(
886 "UPDATE tenant SET retention = '7w' WHERE id = ?1",
887 [damaged.0],
888 )
889 .expect("damaged");
890 f.clock.set(datetime!(2026-10-25 13:00 UTC));
891
892 let report = sweep(&f.tenants, Retention::Days(1));
893
894 assert_eq!(
895 report,
896 SweepReport {
897 purged: 1,
898 failed: 1
899 }
900 );
901 assert_eq!(kept(&f.tenants, fine), 0);
902 assert_eq!(kept(&f.tenants, damaged), 1, "left for a later sweep");
903 }
904
905 #[tokio::test(start_paused = true)]
906 async fn every_runs_at_start_then_after_each_interval_until_shutdown() {
907 let runs = Arc::new(AtomicUsize::new(0));
908 let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
909 let counted = runs.clone();
910 let task = tokio::spawn(every(
911 Duration::from_secs(60),
912 async move {
913 let _ = stopped.await;
914 },
915 move || {
916 counted.fetch_add(1, Ordering::SeqCst);
917 async {}
918 },
919 ));
920 let settle = || async {
921 for _ in 0..10 {
922 tokio::task::yield_now().await;
923 }
924 };
925
926 settle().await;
927 assert_eq!(runs.load(Ordering::SeqCst), 1, "at start");
928 tokio::time::advance(Duration::from_secs(59)).await;
929 settle().await;
930 assert_eq!(runs.load(Ordering::SeqCst), 1, "not before the interval");
931 tokio::time::advance(Duration::from_secs(1)).await;
932 settle().await;
933 assert_eq!(runs.load(Ordering::SeqCst), 2, "after the interval");
934
935 stop.send(()).expect("still running");
936 task.await.expect("ends on shutdown");
937 tokio::time::advance(Duration::from_secs(600)).await;
938 assert_eq!(runs.load(Ordering::SeqCst), 2, "none after shutdown");
939 }
940 }
941}