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 tenants.allow_no_expiry(config.keys_no_expiry);
455 App {
456 tenants,
457 limits: Limits {
458 body: config.body_limit,
459 inflated: config.inflated_limit,
460 body_timeout: config.read_timeout,
461 },
462 supported: config.supported_critical.clone(),
463 retention_default: config.retention_default,
464 mcp: config.mcp,
465 plane,
466 reports: crate::api::ReportGate::new(config.reports),
467 origin: origin_for(config, plane),
468 }
469}
470
471fn origin_for(config: &Config, plane: Plane) -> Option<crate::session::Origin> {
475 match plane {
476 Plane::Both | Plane::Tenant => config.public_origin.clone(),
477 Plane::Operator => config
478 .operator
479 .as_ref()
480 .and_then(|operator| operator.public_origin.clone()),
481 }
482}
483
484pub fn rotation_overdue(
487 backlog: &RotationBacklog,
488 rotation_warn: Duration,
489 now: OffsetDateTime,
490) -> bool {
491 [backlog.oldest_purge, backlog.oldest_removal]
492 .into_iter()
493 .flatten()
494 .any(|at| now - at > rotation_warn)
495}
496
497const ROTATION_CHECK: Duration = Duration::from_secs(86_400);
499
500fn warn_if_rotation_overdue(tenants: &Tenants, rotation_warn: Duration) {
502 match tenants.rotation_backlog() {
503 Ok(backlog) if rotation_overdue(&backlog, rotation_warn, SystemClock.now()) => {
504 tracing::warn!(
505 tenants_with_purges = backlog.tenants_with_purges,
506 purges = backlog.purges,
507 removals = backlog.removals,
508 "key rotation overdue: purged vCons and removed tenants stay readable on old copies until it"
509 );
510 }
511 Ok(_) => {}
512 Err(_) => tracing::warn!("the key rotation backlog could not be read"),
513 }
514}
515
516#[cfg(test)]
517mod tests {
518 use std::time::Duration;
519
520 use super::*;
521
522 mod startup {
523 use time::macros::datetime;
524
525 use super::*;
526
527 #[test]
530 fn a_start_without_storage_parquet_over_packed_versions_names_the_table() {
531 assert_eq!(
532 ServeError::ParquetRemoved { tenants: 2 }.to_string(),
533 "2 tenant(s) have versions packed into Parquet files, and the configuration has no \
534 [storage.parquet]: without it the server packs no more, and the start no longer \
535 refuses a bucket with Object Lock or versioning, either of which keeps the bytes of \
536 a pack file that a purge rewrote; put the [storage.parquet] table back, since packed \
537 versions cannot be turned back into objects; vcon-server check names the tenants",
538 "the refusal's text"
539 );
540 }
541
542 const NOW: OffsetDateTime = datetime!(2026-10-25 12:00 UTC);
543 const DAY: Duration = Duration::from_secs(86_400);
544
545 #[test]
546 fn rotation_is_overdue_once_the_oldest_waiting_work_passes_rotation_warn() {
547 let backlog =
548 |purge: Option<OffsetDateTime>, removal: Option<OffsetDateTime>| RotationBacklog {
549 tenants_with_purges: u64::from(purge.is_some()),
550 purges: u64::from(purge.is_some()),
551 oldest_purge: purge,
552 removals: u64::from(removal.is_some()),
553 oldest_removal: removal,
554 };
555 let day_ago = Some(datetime!(2026-10-24 12:00 UTC));
556 let older = Some(datetime!(2026-10-24 11:59:59 UTC));
557 for (b, overdue) in [
558 (backlog(None, None), false),
559 (backlog(day_ago, None), false),
560 (backlog(older, None), true),
561 (backlog(None, older), true),
562 (backlog(day_ago, older), true),
563 ] {
564 assert_eq!(rotation_overdue(&b, DAY, NOW), overdue, "{b:?}");
565 }
566 }
567
568 #[test]
569 fn a_refusal_for_keys_out_of_order_counts_and_points_at_check() {
570 let order = KeyOrder {
571 wrapped_elsewhere: 1,
572 rotations_stopped: 2,
573 data_under_other_keys: 3,
574 ..KeyOrder::default()
575 };
576 assert_eq!(
577 ServeError::KeysOutOfOrder(order).to_string(),
578 "1 tenant key(s) do not unwrap under the master key; \
579 2 key rotation(s) stopped part way; run rekey tenant again; \
580 3 tenant(s) with data under another key; \
581 vcon-server check names the tenants",
582 "each count in its fixed place, then where to look"
583 );
584 }
585
586 #[test]
589 fn a_refusal_for_catalogs_it_may_not_open_gives_the_error_not_a_key() {
590 let order = KeyOrder {
591 catalogs_unopened: 2,
592 unopened_error: Some("Permission denied (os error 13)".to_owned()),
593 ..KeyOrder::default()
594 };
595 assert_eq!(
596 ServeError::KeysOutOfOrder(order).to_string(),
597 "2 tenant catalog(s) cannot be opened: Permission denied (os error 13); vcon-server check names the tenants"
598 );
599 }
600 }
601 use crate::retention::Retention;
602
603 #[test]
604 fn the_api_takes_its_limits_and_extensions_from_the_configuration() {
605 let dir = tempfile::tempdir().expect("temp dir");
606 let tenants = Arc::new(
607 Tenants::open(
608 dir.path(),
609 Key::generate().expect("key"),
610 Arc::new(OsFs),
611 Arc::new(SystemClock),
612 )
613 .expect("opens"),
614 );
615 let config = Config {
616 listen: "127.0.0.1:8443".parse().expect("address"),
617 tls_cert: "cert.pem".into(),
618 tls_key: "key.pem".into(),
619 data_dir: dir.path().to_owned(),
620 master_key: "master.key".into(),
621 retention_default: Retention::Months(18),
622 purge_interval: Duration::from_secs(3600),
623 rotation_warn: Duration::from_secs(86400),
624 body_limit: 12_345,
625 inflated_limit: 67_890,
626 read_timeout: Duration::from_secs(17),
627 connection: crate::api::ConnectionLimits::default(),
628 supported_critical: ["known".to_owned()].into(),
629 mcp: crate::mcp::Limits {
630 calls_per_second: 3,
631 concurrent: 4,
632 response_bytes: 5,
633 },
634 reports: crate::api::ReportLimits::DEFAULT,
635 storage: crate::config::Storage::default(),
636 export: crate::config::Export::default(),
637 catalog: crate::config::CatalogStore::Local,
638 operator: None,
639 public_origin: None,
640 keys_no_expiry: false,
641 };
642 assert!(
643 tenants.no_expiry_allowed(),
644 "before the configuration is applied a key may have no expiry"
645 );
646 let app = app_from(&config, tenants.clone(), Plane::Tenant);
647 assert!(
648 !tenants.no_expiry_allowed(),
649 "keys.no_expiry = false reaches the registry the API makes keys in"
650 );
651 assert_eq!(app.plane, Plane::Tenant, "the plane it was given");
652 assert!(Arc::ptr_eq(&app.tenants, &tenants));
653 assert_eq!(app.limits.body, 12_345);
654 assert_eq!(app.limits.inflated, 67_890);
655 assert_eq!(app.limits.body_timeout, Duration::from_secs(17));
656 assert_eq!(app.supported, config.supported_critical);
657 assert_eq!(app.retention_default, config.retention_default);
658 assert_eq!(app.mcp, config.mcp);
659 assert_eq!(app.origin, None, "no public origin is configured");
660 }
661
662 fn configured(first: &str, last: &str) -> Config {
664 let text = format!(
665 "{first}listen = \"127.0.0.1:8443\"\ndata_dir = \"/var/lib/vcon-server\"\n\
666 master_key = \"/etc/vcon-server/master.key\"\n[tls]\ncert = \"/c.pem\"\n\
667 key = \"/k.pem\"\n{last}"
668 );
669 crate::config::parse(&text).expect("a configuration")
670 }
671
672 const OPERATOR: &str =
673 "[operator]\nlisten = \"127.0.0.1:8444\"\npublic_origin = \"https://ops.example.com\"\n";
674
675 #[test]
676 fn each_listener_takes_its_own_public_origin() {
677 let config = configured("public_origin = \"https://vcon.example.com\"\n", OPERATOR);
678 let origin = |plane| origin_for(&config, plane).map(|o| o.as_str().to_owned());
679 assert_eq!(
680 origin(Plane::Tenant).as_deref(),
681 Some("https://vcon.example.com"),
682 "`listen` takes public_origin"
683 );
684 assert_eq!(
685 origin(Plane::Operator).as_deref(),
686 Some("https://ops.example.com"),
687 "`operator.listen` takes operator.public_origin"
688 );
689 }
690
691 #[test]
692 fn the_one_listener_of_a_server_takes_public_origin_for_both_planes() {
693 let config = configured("public_origin = \"https://vcon.example.com\"\n", "");
694 assert_eq!(
695 origin_for(&config, Plane::Both),
696 crate::session::Origin::parse("https://vcon.example.com"),
697 "tenants' and operators' sessions come from the one origin"
698 );
699 }
700
701 #[test]
702 fn a_listener_with_no_public_origin_has_none_and_does_not_take_the_other_s() {
703 let config = configured("", OPERATOR);
704 assert_eq!(
705 origin_for(&config, Plane::Tenant),
706 None,
707 "not the operator's"
708 );
709 let config = configured("public_origin = \"https://vcon.example.com\"\n", "");
710 assert_eq!(
711 origin_for(&config, Plane::Operator),
712 None,
713 "not the tenant's"
714 );
715 let config = configured("", "");
716 assert_eq!(origin_for(&config, Plane::Both), None, "none is configured");
717 }
718
719 mod sweeps {
720 use std::sync::Arc;
721 use std::sync::atomic::{AtomicUsize, Ordering};
722 use std::time::Duration;
723
724 use time::macros::datetime;
725 use uuid::Uuid;
726
727 use crate::audit::Actor;
728 use crate::ids::{KeyId, TenantId};
729 use crate::retention::Retention;
730 use crate::serve::{SweepReport, every, sweep};
731 use crate::store::Caller;
732 use crate::store::testing::vcon;
733 use crate::tenants::{Tenants, fixture};
734
735 const CALLER: Caller = Caller { key: KeyId([7; 8]) };
736
737 fn deleted(tenants: &Tenants, id: TenantId, uuid: &str) -> Uuid {
740 let store = tenants.store(id).expect("its store");
741 let (found, body) = vcon(uuid, "kept");
742 store.create(&CALLER, &found, &body).expect("stored");
743 store
744 .delete(&CALLER, found.uuid, Retention::Years(7))
745 .expect("deleted");
746 found.uuid
747 }
748
749 fn kept(tenants: &Tenants, id: TenantId) -> u64 {
751 tenants
752 .store(id)
753 .expect("its store")
754 .counts()
755 .expect("counts")
756 .versions
757 }
758
759 #[test]
760 fn a_sweep_purges_what_is_due_in_each_tenant_under_its_own_period() {
761 let f = fixture();
762 let own = f
763 .tenants
764 .create(Actor::Cli, "own", Some(Retention::Days(1)))
765 .expect("made");
766 let default = f.tenants.create(Actor::Cli, "default", None).expect("made");
767 let long = f
768 .tenants
769 .create(Actor::Cli, "long", Some(Retention::Years(7)))
770 .expect("made");
771 deleted(&f.tenants, own, "0199e5c6-0d7a-7c11-8000-000000000001");
772 deleted(&f.tenants, default, "0199e5c6-0d7a-7c11-8000-000000000002");
773 deleted(&f.tenants, long, "0199e5c6-0d7a-7c11-8000-000000000003");
774 f.clock.set(datetime!(2026-10-25 13:00 UTC));
775
776 let report = sweep(&f.tenants, Retention::Days(1));
777
778 assert_eq!(
779 report,
780 SweepReport {
781 purged: 2,
782 failed: 0
783 }
784 );
785 assert_eq!(kept(&f.tenants, own), 0);
786 assert_eq!(kept(&f.tenants, default), 0);
787 assert_eq!(kept(&f.tenants, long), 1, "seven years have not passed");
788 }
789
790 #[test]
791 fn a_sweep_goes_on_past_a_tenant_it_cannot_sweep() {
792 let f = fixture();
793 let damaged = f.tenants.create(Actor::Cli, "damaged", None).expect("made");
794 let fine = f.tenants.create(Actor::Cli, "fine", None).expect("made");
795 deleted(&f.tenants, damaged, "0199e5c6-0d7a-7c11-8000-000000000001");
796 deleted(&f.tenants, fine, "0199e5c6-0d7a-7c11-8000-000000000002");
797 f.tenants
798 .conn_for_test()
799 .execute(
800 "UPDATE tenant SET retention = '7w' WHERE id = ?1",
801 [damaged.0],
802 )
803 .expect("damaged");
804 f.clock.set(datetime!(2026-10-25 13:00 UTC));
805
806 let report = sweep(&f.tenants, Retention::Days(1));
807
808 assert_eq!(
809 report,
810 SweepReport {
811 purged: 1,
812 failed: 1
813 }
814 );
815 assert_eq!(kept(&f.tenants, fine), 0);
816 assert_eq!(kept(&f.tenants, damaged), 1, "left for a later sweep");
817 }
818
819 #[tokio::test(start_paused = true)]
820 async fn every_runs_at_start_then_after_each_interval_until_shutdown() {
821 let runs = Arc::new(AtomicUsize::new(0));
822 let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
823 let counted = runs.clone();
824 let task = tokio::spawn(every(
825 Duration::from_secs(60),
826 async move {
827 let _ = stopped.await;
828 },
829 move || {
830 counted.fetch_add(1, Ordering::SeqCst);
831 async {}
832 },
833 ));
834 let settle = || async {
835 for _ in 0..10 {
836 tokio::task::yield_now().await;
837 }
838 };
839
840 settle().await;
841 assert_eq!(runs.load(Ordering::SeqCst), 1, "at start");
842 tokio::time::advance(Duration::from_secs(59)).await;
843 settle().await;
844 assert_eq!(runs.load(Ordering::SeqCst), 1, "not before the interval");
845 tokio::time::advance(Duration::from_secs(1)).await;
846 settle().await;
847 assert_eq!(runs.load(Ordering::SeqCst), 2, "after the interval");
848
849 stop.send(()).expect("still running");
850 task.await.expect("ends on shutdown");
851 tokio::time::advance(Duration::from_secs(600)).await;
852 assert_eq!(runs.load(Ordering::SeqCst), 2, "none after shutdown");
853 }
854 }
855}