1use std::future::Future;
4use std::sync::Arc;
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::time::Duration;
7use std::{fmt, io};
8
9use tokio::net::TcpListener;
10
11use crate::access::Plane;
12use crate::api::{self, App, Limits, TlsError};
13use crate::backend::{self, Job};
14use crate::clock::{Clock, SystemClock};
15use crate::config::{Config, Operator, ParquetSettings, StorageError};
16use crate::datadir::{self, LockError, Work};
17use crate::envelope::{Key, KeyError};
18use crate::fs::OsFs;
19use crate::retention::Retention;
20use crate::tenants::{KeyOrder, RegistryError, RotationBacklog, TenantError, Tenants, with_causes};
21use time::OffsetDateTime;
22
23#[derive(Debug)]
25pub enum ServeError {
26 DataDir(LockError),
28 MasterKey(KeyError),
30 WrongMasterKey,
32 WrongDatabaseKey,
35 Open(RegistryError),
37 Registry(TenantError),
39 Storage(StorageError),
41 KeysOutOfOrder(KeyOrder),
43 ParquetRemoved {
46 tenants: u64,
48 },
49 Tls(TlsError),
51 Listen(io::Error),
53 OperatorTls(TlsError),
55 OperatorListen(io::Error),
57 Serve(io::Error),
59}
60
61impl fmt::Display for ServeError {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 match self {
64 ServeError::DataDir(e) => write!(f, "{e}"),
65 ServeError::MasterKey(KeyError::Refused(why)) => {
66 write!(f, "the master key cannot be read: {why}")
67 }
68 ServeError::MasterKey(e) => write!(f, "the master key cannot be read: {e:?}"),
69 ServeError::WrongMasterKey => {
70 f.write_str("the master key is not the one server.sqlite was made under")
71 }
72 ServeError::WrongDatabaseKey => f.write_str(crate::tenants::WRONG_DATABASE_KEY),
73 ServeError::Open(e) => {
74 write!(f, "the registry cannot be opened: {}", with_causes(e))
75 }
76 ServeError::Registry(e) => write!(f, "server.sqlite cannot be opened: {e:?}"),
77 ServeError::KeysOutOfOrder(order) => {
78 let mut parts = Vec::new();
79 if order.wrapped_elsewhere > 0 {
80 parts.push(format!(
81 "{} tenant key(s) do not unwrap under the master key",
82 order.wrapped_elsewhere
83 ));
84 }
85 if order.rotations_stopped > 0 {
86 parts.push(format!(
87 "{} key rotation(s) stopped part way; run rekey tenant again",
88 order.rotations_stopped
89 ));
90 }
91 if order.data_under_other_keys > 0 {
92 parts.push(format!(
93 "{} tenant(s) with data under another key",
94 order.data_under_other_keys
95 ));
96 }
97 if order.catalogs_unopened > 0 {
98 let why = order
99 .unopened_error
100 .as_ref()
101 .map(|e| format!(": {e}"))
102 .unwrap_or_default();
103 parts.push(format!(
104 "{} tenant catalog(s) cannot be opened{why}",
105 order.catalogs_unopened
106 ));
107 }
108 write!(
109 f,
110 "{}; vcon-server check names the tenants",
111 parts.join("; ")
112 )
113 }
114 ServeError::ParquetRemoved { tenants } => write!(
115 f,
116 "{tenants} tenant(s) have versions packed into Parquet files, and the \
117 configuration has no [storage.parquet]: without it the server packs no more, \
118 and the start no longer refuses a bucket with Object Lock or versioning, either \
119 of which keeps the bytes of a pack file that a purge rewrote; put the \
120 [storage.parquet] table back, since packed versions cannot be turned back into \
121 objects; vcon-server check names the tenants"
122 ),
123 ServeError::Tls(crate::api::TlsError::KeyFile(why)) => {
124 write!(f, "the TLS certificate or key cannot be used: {why}")
125 }
126 ServeError::Tls(e) => write!(f, "the TLS certificate or key cannot be used: {e:?}"),
127 ServeError::Listen(e) => write!(f, "the listening address cannot be bound: {e}"),
128 ServeError::OperatorTls(crate::api::TlsError::KeyFile(why)) => write!(
129 f,
130 "the operator listener's TLS certificate or key cannot be used: {why}"
131 ),
132 ServeError::OperatorTls(e) => write!(
133 f,
134 "the operator listener's TLS certificate or key cannot be used: {e:?}"
135 ),
136 ServeError::OperatorListen(e) => {
137 write!(f, "the operator listening address cannot be bound: {e}")
138 }
139 ServeError::Serve(e) => write!(f, "serving failed: {e}"),
140 ServeError::Storage(e) => write!(f, "the storage cannot be used: {e}"),
141 }
142 }
143}
144
145pub async fn run(config: &Config, shutdown: impl Future<Output = ()>) -> Result<(), ServeError> {
154 let opening = config.clone();
155 let opened = blocking(move || open(&opening)).await?;
156 run_opened(config, opened, shutdown).await
157}
158
159pub(crate) async fn run_opened(
164 config: &Config,
165 (_lock, catalogs, tenants): Opened,
166 shutdown: impl Future<Output = ()>,
167) -> Result<(), ServeError> {
168 if let Some(server) = catalogs.server() {
169 tracing::info!(catalog = %server, "the catalogs are in PostgreSQL");
170 }
171 let served = serve_opened(config, tenants, shutdown).await;
172 blocking(move || catalogs.give_up_locks()).await;
173 served?;
174 tracing::info!("stopped");
175 Ok(())
176}
177
178async fn blocking<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> T {
181 match tokio::task::spawn_blocking(work).await {
182 Ok(done) => done,
183 Err(e) => std::panic::resume_unwind(e.into_panic()),
184 }
185}
186
187pub(crate) type Opened = (datadir::DataDirLock, backend::Catalogs, Tenants);
190
191fn open(config: &Config) -> Result<Opened, ServeError> {
195 let lock =
196 datadir::lock(&config.data_dir, Work::Serve.sharing()).map_err(ServeError::DataDir)?;
197 let master = Key::load_master(&config.master_key).map_err(ServeError::MasterKey)?;
198 let catalogs = backend::catalog_for(&config.catalog, Work::Serve.sharing())
199 .map_err(ServeError::Storage)?;
200 let tenants = open_or_give_up(config, master, &catalogs)?;
201 Ok((lock, catalogs, tenants))
202}
203
204pub(crate) fn open_or_give_up(
207 config: &Config,
208 master: Key,
209 catalogs: &backend::Catalogs,
210) -> Result<Tenants, ServeError> {
211 open_on(config, master, catalogs).inspect_err(|_| catalogs.give_up_locks())
212}
213
214fn open_on(
217 config: &Config,
218 master: Key,
219 catalogs: &backend::Catalogs,
220) -> Result<Tenants, ServeError> {
221 let objects = backend::objects_for(&config.storage, &config.data_dir, catalogs)
222 .map_err(ServeError::Storage)?;
223 let tenants = Tenants::open_in(
224 &config.data_dir,
225 master,
226 Arc::new(OsFs),
227 Arc::new(SystemClock),
228 objects,
229 catalogs,
230 )
231 .map_err(|e| match e {
232 RegistryError::WrongKey => ServeError::WrongMasterKey,
233 RegistryError::WrongDatabaseKey => ServeError::WrongDatabaseKey,
234 other => ServeError::Open(other),
235 })?;
236 tenants.set_start_parallel(config.key_wrap.start_parallel);
237 let order = tenants.key_order().map_err(ServeError::Registry)?;
238 if !order.is_sound() {
239 return Err(ServeError::KeysOutOfOrder(order));
240 }
241 if config.storage.parquet.is_none() {
245 let tenants = tenants
246 .tenants_with_packed_versions()
247 .map_err(ServeError::Registry)?;
248 if tenants > 0 {
249 return Err(ServeError::ParquetRemoved { tenants });
250 }
251 }
252 Ok(tenants)
253}
254
255async fn serve_opened(
258 config: &Config,
259 tenants: Tenants,
260 shutdown: impl Future<Output = ()>,
261) -> Result<(), ServeError> {
262 let tls = api::tls_config(&config.tls_cert, &config.tls_key).map_err(ServeError::Tls)?;
263 let listener = TcpListener::bind(config.listen)
264 .await
265 .map_err(ServeError::Listen)?;
266 let bound = listener.local_addr().map_err(ServeError::Listen)?;
269 let operator = match &config.operator {
272 Some(operator) => {
273 let tls = api::tls_config_named(
274 &operator.tls_cert,
275 &operator.tls_key,
276 operator_key_name(config, operator),
277 )
278 .map_err(ServeError::OperatorTls)?;
279 let listener = TcpListener::bind(operator.listen)
280 .await
281 .map_err(ServeError::OperatorListen)?;
282 let bound = listener.local_addr().map_err(ServeError::OperatorListen)?;
283 Some((listener, tls, bound))
284 }
285 None => None,
286 };
287 let tenants = Arc::new(tenants);
288 let leaving = tenants.clone();
290 if let Some((_, _, operator_bound)) = &operator {
294 tracing::info!(operator_listen = %operator_bound, "the operator listener is bound");
295 }
296 tracing::info!(listen = %bound, "serving");
297 let (swept, default) = (tenants.clone(), config.retention_default);
303 let ttl = lease_for(config.purge_interval);
304 let mut jobs = vec![Background::start(
305 "purge sweep",
306 config.purge_interval,
307 move |stopping| {
308 lead_sweep(&swept, default, ttl, stopping);
309 },
310 )];
311 if let Some(parquet) = config.storage.parquet {
312 let packed = tenants.clone();
313 let ttl = lease_for(parquet.pack_interval);
314 jobs.push(Background::start(
315 "pack run",
316 parquet.pack_interval,
317 move |stopping| {
318 lead_pack(&packed, &parquet, ttl, stopping);
319 },
320 ));
321 }
322 let (watched, rotation_warn) = (tenants.clone(), config.rotation_warn);
323 jobs.push(Background::start(
324 "rotation warning",
325 ROTATION_CHECK,
326 move |_| warn_if_rotation_overdue(&watched, rotation_warn),
327 ));
328 let (halt, halted) = tokio::sync::watch::channel(());
331 let until_halted = |mut halted: tokio::sync::watch::Receiver<()>| async move {
332 let _ = halted.changed().await;
334 };
335 let counted = tenants.clone();
339 let counts_full = move |key: &'static str| {
340 let tenants = counted.clone();
341 move || {
342 let tenants = tenants.clone();
343 tokio::task::spawn_blocking(move || tenants.count_listener_full(key));
344 }
345 };
346 let both = async {
347 let Some((operator_listener, operator_tls, _)) = operator else {
348 let full = counts_full("listen");
349 let app = app_from(config, tenants, Plane::Both);
350 return api::serve_observed(
351 listener,
352 tls,
353 api::router(Arc::new(app)),
354 until_halted(halted),
355 config.connection,
356 full,
357 )
358 .await;
359 };
360 let (tenant_full, operator_full) = (counts_full("listen"), counts_full("operator.listen"));
361 let tenant_app = app_from(config, tenants.clone(), Plane::Tenant);
362 let operator_app = app_from(config, tenants, Plane::Operator);
363 let (tenant, operator) = tokio::join!(
364 api::serve_observed(
365 listener,
366 tls,
367 api::router(Arc::new(tenant_app)),
368 until_halted(halted.clone()),
369 config.connection,
370 tenant_full,
371 ),
372 api::serve_observed(
373 operator_listener,
374 operator_tls,
375 api::router(Arc::new(operator_app)),
376 until_halted(halted),
377 config.connection,
378 operator_full,
379 ),
380 );
381 tenant.and(operator)
382 };
383 let mut both = std::pin::pin!(both);
384 let served = tokio::select! {
385 served = &mut both => served,
386 () = shutdown => {
387 let _ = halt.send(());
388 both.await
389 }
390 };
391 Background::stop_all(jobs).await;
392 blocking(move || give_up_leases(&leaving)).await;
395 served.map_err(ServeError::Serve)
396}
397
398const STOP_WARN: Duration = Duration::from_secs(30);
401
402struct Background {
405 name: &'static str,
407 stopping: Arc<AtomicBool>,
409 running: Arc<AtomicBool>,
411 tell: Option<tokio::sync::oneshot::Sender<()>>,
413 task: tokio::task::JoinHandle<()>,
414}
415
416impl Background {
417 fn start(
421 name: &'static str,
422 interval: Duration,
423 work: impl Fn(&dyn Fn() -> bool) + Send + Sync + 'static,
424 ) -> Background {
425 let stopping = Arc::new(AtomicBool::new(false));
426 let running = Arc::new(AtomicBool::new(false));
427 let (tell, told) = tokio::sync::oneshot::channel::<()>();
428 let work = Arc::new(work);
429 let (asked, busy) = (stopping.clone(), running.clone());
430 let task = tokio::spawn(every(
431 interval,
432 async {
433 let _ = told.await;
434 },
435 move || {
436 let (work, asked, busy) = (work.clone(), asked.clone(), busy.clone());
437 async move {
438 busy.store(true, Ordering::SeqCst);
439 let ran = tokio::task::spawn_blocking(move || {
440 work(&|| asked.load(Ordering::SeqCst));
441 })
442 .await;
443 busy.store(false, Ordering::SeqCst);
444 if let Err(error) = ran {
445 tracing::error!(job = name, error = %error, "a background job's run failed");
446 }
447 }
448 },
449 ));
450 Background {
451 name,
452 stopping,
453 running,
454 tell: Some(tell),
455 task,
456 }
457 }
458
459 fn ask(&mut self) {
463 self.stopping.store(true, Ordering::SeqCst);
464 if let Some(tell) = self.tell.take() {
465 let _ = tell.send(());
466 }
467 }
468
469 async fn join(self) {
473 let Background {
474 name,
475 running,
476 mut task,
477 ..
478 } = self;
479 if running.load(Ordering::SeqCst) {
480 tracing::info!(
481 job = name,
482 "stopping: waiting for a background job's run to end"
483 );
484 }
485 let mut waited = Duration::ZERO;
486 loop {
487 match tokio::time::timeout(STOP_WARN, &mut task).await {
488 Ok(Ok(())) => return,
489 Ok(Err(error)) => {
490 tracing::error!(job = name, error = %error, "a background job's run failed");
491 return;
492 }
493 Err(_) => {
494 waited += STOP_WARN;
495 tracing::warn!(
496 job = name,
497 waited_secs = waited.as_secs(),
498 "stopping: a background job's run has not ended; the stop goes on waiting"
499 );
500 }
501 }
502 }
503 }
504
505 async fn stop_all(mut jobs: Vec<Background>) {
507 for job in &mut jobs {
508 job.ask();
509 }
510 for job in jobs {
511 job.join().await;
512 }
513 }
514}
515
516#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
518pub struct PackRunReport {
519 pub files: u64,
521 pub versions: u64,
523 pub failed: u64,
525}
526
527pub fn pack_all(
533 tenants: &Tenants,
534 settings: &ParquetSettings,
535 stopping: &dyn Fn() -> bool,
536) -> PackRunReport {
537 pack_while(tenants, settings, &mut || !stopping())
538}
539
540fn pack_while(
543 tenants: &Tenants,
544 settings: &ParquetSettings,
545 held: &mut dyn FnMut() -> bool,
546) -> PackRunReport {
547 let mut report = PackRunReport::default();
548 let plan = crate::store::packer::PackPlan {
549 grace: settings.reader_grace,
550 ..crate::store::packer::PackPlan::with_limit(settings.pack_limit)
551 };
552 match tenants.ids() {
553 Ok(ids) => {
554 for id in ids {
555 if !held() {
556 break;
557 }
558 #[cfg(test)]
559 tenants.job_steps_for_test("pack run");
560 match tenants.store(id).map(|store| store.pack(&plan)) {
561 Ok(Ok(done)) => {
562 report.files += done.files;
563 report.versions += done.versions;
564 }
565 _ => report.failed += 1,
566 }
567 }
568 }
569 Err(_) => report.failed += 1,
570 }
571 tracing::info!(
572 files = report.files,
573 versions = report.versions,
574 failed = report.failed,
575 "pack run"
576 );
577 report
578}
579
580const SHORTEST_LEASE: Duration = Duration::from_secs(60);
582
583#[must_use]
589pub fn lease_for(interval: Duration) -> Duration {
590 interval.saturating_mul(2).max(SHORTEST_LEASE)
591}
592
593pub fn sweep(tenants: &Tenants, default: Retention, stopping: &dyn Fn() -> bool) -> SweepReport {
600 sweep_while(tenants, default, &mut || !stopping())
601}
602
603pub(crate) fn holds(tenants: &Tenants, job: Job, ttl: Duration) -> bool {
606 tenants.lead(job, ttl) == Ok(true)
607}
608
609pub fn lead_sweep(
618 tenants: &Tenants,
619 default: Retention,
620 ttl: Duration,
621 stopping: &dyn Fn() -> bool,
622) -> Option<SweepReport> {
623 if stopping() {
624 return None;
625 }
626 if !holds(tenants, Job::Sweep, ttl) {
627 tracing::info!("purge sweep: another server holds it");
628 return None;
629 }
630 let recovery_failed = tenants.recover_all().unwrap_or(1);
631 let mut report = sweep_while(tenants, default, &mut || {
632 !stopping() && holds(tenants, Job::Sweep, ttl)
633 });
634 report.failed += recovery_failed;
635 Some(report)
636}
637
638pub fn lead_pack(
642 tenants: &Tenants,
643 settings: &ParquetSettings,
644 ttl: Duration,
645 stopping: &dyn Fn() -> bool,
646) -> Option<PackRunReport> {
647 if stopping() {
648 return None;
649 }
650 if !holds(tenants, Job::Pack, ttl) {
651 tracing::info!("pack run: another server holds it");
652 return None;
653 }
654 Some(pack_while(tenants, settings, &mut || {
655 !stopping() && holds(tenants, Job::Pack, ttl)
656 }))
657}
658
659pub(crate) fn give_up_leases(tenants: &Tenants) -> usize {
669 let mut kept = 0;
670 for job in [Job::Sweep, Job::Pack] {
671 let given_up = (0..GIVE_UP_TRIES).any(|_| tenants.step_down(job).is_ok());
672 if !given_up {
673 kept += 1;
674 tracing::warn!(
675 job = job_name(job),
676 tries = GIVE_UP_TRIES,
677 "the lease could not be given up: another server takes the job when it ends"
678 );
679 }
680 }
681 kept
682}
683
684pub(crate) const GIVE_UP_TRIES: usize = 3;
686
687fn job_name(job: Job) -> &'static str {
689 match job {
690 Job::Sweep => "purge sweep",
691 Job::Pack => "pack run",
692 }
693}
694
695pub fn sweep_while(
699 tenants: &Tenants,
700 default: Retention,
701 held: &mut dyn FnMut() -> bool,
702) -> SweepReport {
703 let mut report = SweepReport::default();
704 match tenants.ids() {
705 Ok(ids) => {
706 for id in ids {
707 if !held() {
708 break;
709 }
710 #[cfg(test)]
711 tenants.job_steps_for_test("purge sweep");
712 let purged = tenants.retention(id).and_then(|own| {
713 let store = tenants.store(id)?;
714 Ok(store.purge_due(crate::tenants::kept_for(own, default)))
715 });
716 match purged {
717 Ok(Ok(done)) => report.purged += done.purged,
718 _ => report.failed += 1,
719 }
720 }
721 }
722 Err(_) => report.failed += 1,
723 }
724 tracing::info!(
725 purged = report.purged,
726 failed = report.failed,
727 "purge sweep"
728 );
729 report
730}
731
732#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
734pub struct SweepReport {
735 pub purged: u64,
737 pub failed: u64,
739}
740
741pub async fn every<F, Fut>(interval: Duration, shutdown: impl Future<Output = ()>, mut job: F)
745where
746 F: FnMut() -> Fut,
747 Fut: Future<Output = ()>,
748{
749 tokio::pin!(shutdown);
750 loop {
751 tokio::select! {
752 biased;
753 () = &mut shutdown => return,
754 () = std::future::ready(()) => {}
755 }
756 job().await;
757 tokio::select! {
758 biased;
759 () = &mut shutdown => return,
760 () = tokio::time::sleep(interval) => {}
761 }
762 }
763}
764
765fn operator_key_name(config: &Config, operator: &Operator) -> &'static str {
769 if operator.tls_key == config.tls_key && operator.tls_cert == config.tls_cert {
770 "tls.key"
771 } else {
772 "operator.tls.key"
773 }
774}
775
776fn app_from(config: &Config, tenants: Arc<Tenants>, plane: Plane) -> App {
779 tenants.allow_no_expiry(config.keys_no_expiry);
780 App {
781 tenants,
782 limits: Limits {
783 body: config.body_limit,
784 inflated: config.inflated_limit,
785 body_timeout: config.read_timeout,
786 },
787 supported: config.supported_critical.clone(),
788 retention_default: config.retention_default,
789 mcp: config.mcp,
790 plane,
791 reports: crate::api::ReportGate::new(config.reports),
792 origin: origin_for(config, plane),
793 }
794}
795
796fn origin_for(config: &Config, plane: Plane) -> Option<crate::session::Origin> {
800 match plane {
801 Plane::Both | Plane::Tenant => config.public_origin.clone(),
802 Plane::Operator => config
803 .operator
804 .as_ref()
805 .and_then(|operator| operator.public_origin.clone()),
806 }
807}
808
809pub fn rotation_overdue(
812 backlog: &RotationBacklog,
813 rotation_warn: Duration,
814 now: OffsetDateTime,
815) -> bool {
816 [backlog.oldest_purge, backlog.oldest_removal]
817 .into_iter()
818 .flatten()
819 .any(|at| now - at > rotation_warn)
820}
821
822const ROTATION_CHECK: Duration = Duration::from_secs(86_400);
824
825fn warn_if_rotation_overdue(tenants: &Tenants, rotation_warn: Duration) {
827 match tenants.rotation_backlog() {
828 Ok(backlog) if rotation_overdue(&backlog, rotation_warn, SystemClock.now()) => {
829 tracing::warn!(
830 tenants_with_purges = backlog.tenants_with_purges,
831 purges = backlog.purges,
832 removals = backlog.removals,
833 "key rotation overdue: purged vCons and removed tenants stay readable on old copies until it"
834 );
835 }
836 Ok(_) => {}
837 Err(_) => tracing::warn!("the key rotation backlog could not be read"),
838 }
839}
840
841#[cfg(test)]
842mod start_tests;
843
844#[cfg(test)]
845mod stop_tests;
846
847#[cfg(test)]
848mod tests {
849 use std::time::Duration;
850
851 use super::*;
852
853 mod startup {
854 use time::macros::datetime;
855
856 use super::*;
857
858 #[test]
861 fn a_start_without_storage_parquet_over_packed_versions_names_the_table() {
862 assert_eq!(
863 ServeError::ParquetRemoved { tenants: 2 }.to_string(),
864 "2 tenant(s) have versions packed into Parquet files, and the configuration has no \
865 [storage.parquet]: without it the server packs no more, and the start no longer \
866 refuses a bucket with Object Lock or versioning, either of which keeps the bytes of \
867 a pack file that a purge rewrote; put the [storage.parquet] table back, since packed \
868 versions cannot be turned back into objects; vcon-server check names the tenants",
869 "the refusal's text"
870 );
871 }
872
873 const NOW: OffsetDateTime = datetime!(2026-10-25 12:00 UTC);
874 const DAY: Duration = Duration::from_secs(86_400);
875
876 #[test]
877 fn rotation_is_overdue_once_the_oldest_waiting_work_passes_rotation_warn() {
878 let backlog =
879 |purge: Option<OffsetDateTime>, removal: Option<OffsetDateTime>| RotationBacklog {
880 tenants_with_purges: u64::from(purge.is_some()),
881 purges: u64::from(purge.is_some()),
882 oldest_purge: purge,
883 removals: u64::from(removal.is_some()),
884 oldest_removal: removal,
885 };
886 let day_ago = Some(datetime!(2026-10-24 12:00 UTC));
887 let older = Some(datetime!(2026-10-24 11:59:59 UTC));
888 for (b, overdue) in [
889 (backlog(None, None), false),
890 (backlog(day_ago, None), false),
891 (backlog(older, None), true),
892 (backlog(None, older), true),
893 (backlog(day_ago, older), true),
894 ] {
895 assert_eq!(rotation_overdue(&b, DAY, NOW), overdue, "{b:?}");
896 }
897 }
898
899 #[test]
900 fn a_refusal_for_keys_out_of_order_counts_and_points_at_check() {
901 let order = KeyOrder {
902 wrapped_elsewhere: 1,
903 rotations_stopped: 2,
904 data_under_other_keys: 3,
905 ..KeyOrder::default()
906 };
907 assert_eq!(
908 ServeError::KeysOutOfOrder(order).to_string(),
909 "1 tenant key(s) do not unwrap under the master key; \
910 2 key rotation(s) stopped part way; run rekey tenant again; \
911 3 tenant(s) with data under another key; \
912 vcon-server check names the tenants",
913 "each count in its fixed place, then where to look"
914 );
915 }
916
917 #[test]
920 fn a_refusal_for_catalogs_it_may_not_open_gives_the_error_not_a_key() {
921 let order = KeyOrder {
922 catalogs_unopened: 2,
923 unopened_error: Some("Permission denied (os error 13)".to_owned()),
924 ..KeyOrder::default()
925 };
926 assert_eq!(
927 ServeError::KeysOutOfOrder(order).to_string(),
928 "2 tenant catalog(s) cannot be opened: Permission denied (os error 13); vcon-server check names the tenants"
929 );
930 }
931 }
932 use crate::retention::Retention;
933
934 #[test]
935 fn the_api_takes_its_limits_and_extensions_from_the_configuration() {
936 let dir = tempfile::tempdir().expect("temp dir");
937 let tenants = Arc::new(
938 Tenants::open(
939 dir.path(),
940 Key::generate().expect("key"),
941 Arc::new(OsFs),
942 Arc::new(SystemClock),
943 )
944 .expect("opens"),
945 );
946 let config = Config {
947 listen: "127.0.0.1:8443".parse().expect("address"),
948 tls_cert: "cert.pem".into(),
949 tls_key: "key.pem".into(),
950 data_dir: dir.path().to_owned(),
951 master_key: "master.key".into(),
952 retention_default: Retention::Months(18),
953 purge_interval: Duration::from_secs(3600),
954 rotation_warn: Duration::from_secs(86400),
955 body_limit: 12_345,
956 inflated_limit: 67_890,
957 read_timeout: Duration::from_secs(17),
958 connection: crate::api::ConnectionLimits::default(),
959 supported_critical: ["known".to_owned()].into(),
960 mcp: crate::mcp::Limits {
961 calls_per_second: 3,
962 concurrent: 4,
963 response_bytes: 5,
964 },
965 reports: crate::api::ReportLimits::DEFAULT,
966 storage: crate::config::Storage::default(),
967 export: crate::config::Export::default(),
968 catalog: crate::config::CatalogStore::Local,
969 operator: None,
970 public_origin: None,
971 keys_no_expiry: false,
972 key_wrap: crate::config::KeyWrapSettings::default(),
973 };
974 let other = tempfile::tempdir().expect("temp dir");
975 let mut three = config.clone();
976 three.data_dir = other.path().to_owned();
977 three.key_wrap.start_parallel = 3;
978 let started = open_or_give_up(
979 &three,
980 Key::generate().expect("key"),
981 &crate::backend::Catalogs::Local,
982 )
983 .expect("a start opens a new registry");
984 assert_eq!(
985 started.start_parallel(),
986 3,
987 "key_wrap.start_parallel reaches the start's key check"
988 );
989 drop(started);
990 assert!(
991 tenants.no_expiry_allowed(),
992 "before the configuration is applied a key may have no expiry"
993 );
994 let app = app_from(&config, tenants.clone(), Plane::Tenant);
995 assert!(
996 !tenants.no_expiry_allowed(),
997 "keys.no_expiry = false reaches the registry the API makes keys in"
998 );
999 assert_eq!(app.plane, Plane::Tenant, "the plane it was given");
1000 assert!(Arc::ptr_eq(&app.tenants, &tenants));
1001 assert_eq!(app.limits.body, 12_345);
1002 assert_eq!(app.limits.inflated, 67_890);
1003 assert_eq!(app.limits.body_timeout, Duration::from_secs(17));
1004 assert_eq!(app.supported, config.supported_critical);
1005 assert_eq!(app.retention_default, config.retention_default);
1006 assert_eq!(app.mcp, config.mcp);
1007 assert_eq!(app.origin, None, "no public origin is configured");
1008 }
1009
1010 #[test]
1014 fn a_start_serves_tenants_on_local_objects_with_the_group_sync() {
1015 let dir = tempfile::tempdir().expect("temp dir");
1016 let mut config = configured("", "");
1017 config.data_dir = dir.path().to_owned();
1018 let tenants = open_or_give_up(
1019 &config,
1020 Key::generate().expect("key"),
1021 &crate::backend::Catalogs::Local,
1022 )
1023 .expect("a start opens a new registry");
1024 let id = tenants
1025 .create(crate::audit::Actor::Cli, "acme", None)
1026 .expect("made");
1027 let synchronous: i64 = tenants
1028 .store(id)
1029 .expect("its store")
1030 .conn_for_test()
1031 .pragma_query_value(None, "synchronous", |r| r.get(0))
1032 .expect("reads synchronous");
1033 assert_eq!(
1034 synchronous, 1,
1035 "NORMAL: the served tenant's commits share a group sync"
1036 );
1037 }
1038
1039 fn configured(first: &str, last: &str) -> Config {
1041 let text = format!(
1042 "{first}listen = \"127.0.0.1:8443\"\ndata_dir = \"/var/lib/vcon-server\"\n\
1043 master_key = \"/etc/vcon-server/master.key\"\n[tls]\ncert = \"/c.pem\"\n\
1044 key = \"/k.pem\"\n{last}"
1045 );
1046 crate::config::parse(&text).expect("a configuration")
1047 }
1048
1049 const OPERATOR: &str =
1050 "[operator]\nlisten = \"127.0.0.1:8444\"\npublic_origin = \"https://ops.example.com\"\n";
1051
1052 #[test]
1053 fn each_listener_takes_its_own_public_origin() {
1054 let config = configured("public_origin = \"https://vcon.example.com\"\n", OPERATOR);
1055 let origin = |plane| origin_for(&config, plane).map(|o| o.as_str().to_owned());
1056 assert_eq!(
1057 origin(Plane::Tenant).as_deref(),
1058 Some("https://vcon.example.com"),
1059 "`listen` takes public_origin"
1060 );
1061 assert_eq!(
1062 origin(Plane::Operator).as_deref(),
1063 Some("https://ops.example.com"),
1064 "`operator.listen` takes operator.public_origin"
1065 );
1066 }
1067
1068 #[test]
1069 fn the_one_listener_of_a_server_takes_public_origin_for_both_planes() {
1070 let config = configured("public_origin = \"https://vcon.example.com\"\n", "");
1071 assert_eq!(
1072 origin_for(&config, Plane::Both),
1073 crate::session::Origin::parse("https://vcon.example.com"),
1074 "tenants' and operators' sessions come from the one origin"
1075 );
1076 }
1077
1078 #[test]
1079 fn a_listener_with_no_public_origin_has_none_and_does_not_take_the_other_s() {
1080 let config = configured("", OPERATOR);
1081 assert_eq!(
1082 origin_for(&config, Plane::Tenant),
1083 None,
1084 "not the operator's"
1085 );
1086 let config = configured("public_origin = \"https://vcon.example.com\"\n", "");
1087 assert_eq!(
1088 origin_for(&config, Plane::Operator),
1089 None,
1090 "not the tenant's"
1091 );
1092 let config = configured("", "");
1093 assert_eq!(origin_for(&config, Plane::Both), None, "none is configured");
1094 }
1095
1096 mod sweeps {
1097 use std::sync::Arc;
1098 use std::sync::atomic::{AtomicUsize, Ordering};
1099 use std::time::Duration;
1100
1101 use time::macros::datetime;
1102 use uuid::Uuid;
1103
1104 use crate::audit::Actor;
1105 use crate::ids::{KeyId, TenantId};
1106 use crate::retention::Retention;
1107 use crate::serve::{
1108 PackRunReport, SweepReport, every, lead_pack, lead_sweep, lease_for, sweep, sweep_while,
1109 };
1110 use crate::store::Caller;
1111 use crate::store::testing::vcon;
1112 use crate::tenants::{Tenants, fixture};
1113
1114 const CALLER: Caller = Caller { key: KeyId([7; 8]) };
1115
1116 fn deleted(tenants: &Tenants, id: TenantId, uuid: &str) -> Uuid {
1119 let store = tenants.store(id).expect("its store");
1120 let (found, body) = vcon(uuid, "kept");
1121 store.create(&CALLER, &found, &body).expect("stored");
1122 store
1123 .delete(&CALLER, found.uuid, Retention::Years(7))
1124 .expect("deleted");
1125 found.uuid
1126 }
1127
1128 fn kept(tenants: &Tenants, id: TenantId) -> u64 {
1130 tenants
1131 .store(id)
1132 .expect("its store")
1133 .counts()
1134 .expect("counts")
1135 .versions
1136 }
1137
1138 #[test]
1139 fn a_sweep_purges_what_is_due_in_each_tenant_under_its_own_period() {
1140 let f = fixture();
1141 let own = f
1142 .tenants
1143 .create(Actor::Cli, "own", Some(Retention::Days(1)))
1144 .expect("made");
1145 let default = f.tenants.create(Actor::Cli, "default", None).expect("made");
1146 let long = f
1147 .tenants
1148 .create(Actor::Cli, "long", Some(Retention::Years(7)))
1149 .expect("made");
1150 deleted(&f.tenants, own, "0199e5c6-0d7a-7c11-8000-000000000001");
1151 deleted(&f.tenants, default, "0199e5c6-0d7a-7c11-8000-000000000002");
1152 deleted(&f.tenants, long, "0199e5c6-0d7a-7c11-8000-000000000003");
1153 f.clock.set(datetime!(2026-10-25 13:00 UTC));
1154
1155 let report = sweep(&f.tenants, Retention::Days(1), &|| false);
1156
1157 assert_eq!(
1158 report,
1159 SweepReport {
1160 purged: 2,
1161 failed: 0
1162 }
1163 );
1164 assert_eq!(kept(&f.tenants, own), 0);
1165 assert_eq!(kept(&f.tenants, default), 0);
1166 assert_eq!(kept(&f.tenants, long), 1, "seven years have not passed");
1167 }
1168
1169 #[test]
1170 fn a_lease_lasts_two_intervals_so_its_holder_renews_it_in_time() {
1171 assert_eq!(
1172 lease_for(Duration::from_secs(3_600)),
1173 Duration::from_secs(7_200),
1174 "an hour's sweep holds its lease two hours"
1175 );
1176 }
1177
1178 #[test]
1179 fn a_server_with_a_data_directory_always_leads_the_sweep() {
1180 let f = fixture();
1181 let own = f
1182 .tenants
1183 .create(Actor::Cli, "own", Some(Retention::Days(1)))
1184 .expect("made");
1185 deleted(&f.tenants, own, "0199e5c6-0d7a-7c11-8000-000000000001");
1186 f.clock.set(datetime!(2026-10-25 13:00 UTC));
1187 assert_eq!(
1188 lead_sweep(
1189 &f.tenants,
1190 Retention::Days(1),
1191 lease_for(Duration::from_secs(60)),
1192 &|| false
1193 ),
1194 Some(SweepReport {
1195 purged: 1,
1196 failed: 0
1197 }),
1198 "one process: it always holds the lease"
1199 );
1200 assert_eq!(kept(&f.tenants, own), 0, "purged");
1201 }
1202
1203 #[test]
1204 fn a_server_with_a_data_directory_always_leads_the_pack_run() {
1205 let f = fixture();
1206 let settings = crate::config::ParquetSettings {
1207 pack_interval: crate::config::PACK_INTERVAL,
1208 pack_limit: crate::config::PACK_LIMIT,
1209 reader_grace: crate::config::READER_GRACE,
1210 };
1211 assert_eq!(
1212 lead_pack(
1213 &f.tenants,
1214 &settings,
1215 lease_for(settings.pack_interval),
1216 &|| false
1217 ),
1218 Some(PackRunReport::default()),
1219 "no tenant, nothing packed, and the run was this server's"
1220 );
1221 }
1222
1223 #[test]
1224 fn a_sweep_stops_at_the_tenant_where_its_lease_was_lost() {
1225 let f = fixture();
1226 let first = f
1227 .tenants
1228 .create(Actor::Cli, "a-first", Some(Retention::Days(1)))
1229 .expect("made");
1230 let second = f
1231 .tenants
1232 .create(Actor::Cli, "b-second", Some(Retention::Days(1)))
1233 .expect("made");
1234 deleted(&f.tenants, first, "0199e5c6-0d7a-7c11-8000-000000000001");
1235 deleted(&f.tenants, second, "0199e5c6-0d7a-7c11-8000-000000000002");
1236 f.clock.set(datetime!(2026-10-25 13:00 UTC));
1237 let mut asked = 0;
1238 let report = sweep_while(&f.tenants, Retention::Days(1), &mut || {
1239 asked += 1;
1240 asked == 1
1241 });
1242 assert_eq!(report.purged, 1, "the first tenant only: {report:?}");
1243 assert_eq!(asked, 2, "asked before each tenant");
1244 assert_eq!(
1245 kept(&f.tenants, first) + kept(&f.tenants, second),
1246 1,
1247 "the other waits for the next holder"
1248 );
1249 }
1250
1251 #[test]
1252 fn a_sweep_that_does_not_hold_its_lease_at_the_start_sweeps_nothing() {
1253 let f = fixture();
1254 let own = f
1255 .tenants
1256 .create(Actor::Cli, "own", Some(Retention::Days(1)))
1257 .expect("made");
1258 deleted(&f.tenants, own, "0199e5c6-0d7a-7c11-8000-000000000001");
1259 f.clock.set(datetime!(2026-10-25 13:00 UTC));
1260 let report = sweep_while(&f.tenants, Retention::Days(1), &mut || false);
1261 assert_eq!(report, SweepReport::default(), "nothing");
1262 assert_eq!(kept(&f.tenants, own), 1, "kept for the holder");
1263 }
1264
1265 #[test]
1266 fn a_pack_run_stops_at_the_tenant_where_its_lease_was_lost() {
1267 let f = fixture();
1268 for name in ["a-first", "b-second"] {
1269 f.tenants.create(Actor::Cli, name, None).expect("made");
1270 }
1271 let settings = crate::config::ParquetSettings {
1272 pack_interval: crate::config::PACK_INTERVAL,
1273 pack_limit: crate::config::PACK_LIMIT,
1274 reader_grace: crate::config::READER_GRACE,
1275 };
1276 let mut asked = 0;
1279 super::super::pack_while(&f.tenants, &settings, &mut || {
1280 asked += 1;
1281 true
1282 });
1283 assert_eq!(asked, 2, "asked before each tenant");
1284 let mut asked = 0;
1285 let none = super::super::pack_while(&f.tenants, &settings, &mut || {
1286 asked += 1;
1287 false
1288 });
1289 assert_eq!(asked, 1, "the run stopped at the first tenant");
1290 assert_eq!(none, PackRunReport::default(), "nothing done: {none:?}");
1291 }
1292
1293 #[test]
1294 fn a_lease_never_lasts_less_than_a_minute() {
1295 assert_eq!(
1296 lease_for(Duration::from_secs(10)),
1297 Duration::from_secs(60),
1298 "a short interval still gives a renewal time to arrive"
1299 );
1300 assert_eq!(lease_for(Duration::ZERO), Duration::from_secs(60), "zero");
1301 }
1302
1303 #[test]
1304 fn a_lease_of_the_longest_interval_does_not_overflow() {
1305 assert_eq!(lease_for(Duration::MAX), Duration::MAX, "saturates");
1306 }
1307
1308 #[test]
1309 fn a_sweep_goes_on_past_a_tenant_it_cannot_sweep() {
1310 let f = fixture();
1311 let damaged = f.tenants.create(Actor::Cli, "damaged", None).expect("made");
1312 let fine = f.tenants.create(Actor::Cli, "fine", None).expect("made");
1313 deleted(&f.tenants, damaged, "0199e5c6-0d7a-7c11-8000-000000000001");
1314 deleted(&f.tenants, fine, "0199e5c6-0d7a-7c11-8000-000000000002");
1315 f.tenants
1316 .conn_for_test()
1317 .execute(
1318 "UPDATE tenant SET retention = '7w' WHERE id = ?1",
1319 [damaged.0],
1320 )
1321 .expect("damaged");
1322 f.clock.set(datetime!(2026-10-25 13:00 UTC));
1323
1324 let report = sweep(&f.tenants, Retention::Days(1), &|| false);
1325
1326 assert_eq!(
1327 report,
1328 SweepReport {
1329 purged: 1,
1330 failed: 1
1331 }
1332 );
1333 assert_eq!(kept(&f.tenants, fine), 0);
1334 assert_eq!(kept(&f.tenants, damaged), 1, "left for a later sweep");
1335 }
1336
1337 #[tokio::test(start_paused = true)]
1338 async fn every_runs_at_start_then_after_each_interval_until_shutdown() {
1339 let runs = Arc::new(AtomicUsize::new(0));
1340 let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
1341 let counted = runs.clone();
1342 let task = tokio::spawn(every(
1343 Duration::from_secs(60),
1344 async move {
1345 let _ = stopped.await;
1346 },
1347 move || {
1348 counted.fetch_add(1, Ordering::SeqCst);
1349 async {}
1350 },
1351 ));
1352 let settle = || async {
1353 for _ in 0..10 {
1354 tokio::task::yield_now().await;
1355 }
1356 };
1357
1358 settle().await;
1359 assert_eq!(runs.load(Ordering::SeqCst), 1, "at start");
1360 tokio::time::advance(Duration::from_secs(59)).await;
1361 settle().await;
1362 assert_eq!(runs.load(Ordering::SeqCst), 1, "not before the interval");
1363 tokio::time::advance(Duration::from_secs(1)).await;
1364 settle().await;
1365 assert_eq!(runs.load(Ordering::SeqCst), 2, "after the interval");
1366
1367 stop.send(()).expect("still running");
1368 task.await.expect("ends on shutdown");
1369 tokio::time::advance(Duration::from_secs(600)).await;
1370 assert_eq!(runs.load(Ordering::SeqCst), 2, "none after shutdown");
1371 }
1372
1373 #[tokio::test(start_paused = true)]
1376 async fn every_returns_only_after_a_run_going_at_shutdown_has_ended() {
1377 let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
1378 let (release, released) = tokio::sync::oneshot::channel::<()>();
1379 let released = Arc::new(tokio::sync::Mutex::new(Some(released)));
1380 let ended = Arc::new(AtomicUsize::new(0));
1381 let (held, done) = (released.clone(), ended.clone());
1382 let task = tokio::spawn(every(
1383 Duration::from_secs(60),
1384 async move {
1385 let _ = stopped.await;
1386 },
1387 move || {
1388 let (held, done) = (held.clone(), done.clone());
1389 async move {
1390 if let Some(released) = held.lock().await.take() {
1391 let _ = released.await;
1392 }
1393 done.fetch_add(1, Ordering::SeqCst);
1394 }
1395 },
1396 ));
1397 for _ in 0..10 {
1398 tokio::task::yield_now().await;
1399 }
1400 stop.send(()).expect("still running");
1401 for _ in 0..10 {
1402 tokio::task::yield_now().await;
1403 }
1404 assert!(
1405 !task.is_finished(),
1406 "every waits for the run going at shutdown"
1407 );
1408 release.send(()).expect("the run waits");
1409 task.await.expect("ends once the run has");
1410 assert_eq!(
1411 ended.load(Ordering::SeqCst),
1412 1,
1413 "the run ended, and no other began"
1414 );
1415 }
1416 }
1417}