Skip to main content

vcon_server/
serve.rs

1//! `vcon-server serve`: the server, run from its configuration.
2
3use std::future::Future;
4use std::sync::Arc;
5use std::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/// Why the server did not start, or stopped.
24#[derive(Debug)]
25pub enum ServeError {
26    /// The data directory could not be taken.
27    DataDir(LockError),
28    /// The master key file could not be read.
29    MasterKey(KeyError),
30    /// server.sqlite was made under another master key.
31    WrongMasterKey,
32    /// The registry in the catalog database was made under another master
33    /// key.
34    WrongDatabaseKey,
35    /// The registry could not be opened.
36    Open(RegistryError),
37    /// server.sqlite could not be read.
38    Registry(TenantError),
39    /// The storage the configuration names cannot be used.
40    Storage(StorageError),
41    /// Some tenant's data is not under its current key.
42    KeysOutOfOrder(KeyOrder),
43    /// `tenants` tenants have packed versions, and the configuration has no
44    /// `[storage.parquet]`.
45    ParquetRemoved {
46        /// How many tenants have packed versions.
47        tenants: u64,
48    },
49    /// The certificate or key could not be used.
50    Tls(TlsError),
51    /// The listening address could not be bound.
52    Listen(io::Error),
53    /// The operator listener's certificate or key could not be used.
54    OperatorTls(TlsError),
55    /// The operator listener's address could not be bound.
56    OperatorListen(io::Error),
57    /// Serving failed.
58    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
145/// Runs the server until `shutdown` completes: locks the data directory,
146/// opens the registry under the master key, and serves the API over TLS.
147///
148/// The opening runs on a blocking task: the registry and the catalogs are
149/// read there, and a PostgreSQL catalog waits on a runtime of its own,
150/// which no async worker may do. A server that stops, or whose start is
151/// refused after the catalogs were reached, gives its locks on the
152/// database up before it ends.
153pub 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
159/// [`run`], with the data directory locked and the registry opened: serves
160/// until `shutdown` completes or a listener fails, and then gives up the
161/// locks on the catalog database, while its connections still answer, so
162/// the next server finds the database free at once.
163pub(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
178/// Runs `work`, which reads files or waits on the catalog database, off
179/// the async workers.
180async 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
187/// What a start opens before it listens: the data directory's lock, where
188/// the catalogs are, and the registry, checked.
189pub(crate) type Opened = (datadir::DataDirLock, backend::Catalogs, Tenants);
190
191/// Locks the data directory, reads the master key, reaches the catalogs
192/// and then the objects, and opens the registry. A start refused after the
193/// catalogs were reached gives its locks on the database up.
194fn 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
204/// [`open_on`], and for a start it refuses, the locks on the catalog
205/// database given up while the connections still answer.
206pub(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
214/// The registry on `catalogs`, with the objects bound to them, and the
215/// checks a start makes of it before it listens.
216fn 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    // Packed versions need Parquet storage kept on: nothing turns them
242    // back into objects, and only with it is the bucket checked for what
243    // would keep a purged row's bytes.
244    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
255/// Serves the opened registry until `shutdown` completes or a listener
256/// fails.
257async 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    // The address bound, which names the port the system chose when the
267    // configuration gives port 0.
268    let bound = listener.local_addr().map_err(ServeError::Listen)?;
269    // The operator listener, when the configuration has one: bound before
270    // anything is served, so a start that cannot have both serves neither.
271    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    // Kept to give up this server's leases when it stops.
289    let leaving = tenants.clone();
290    // The start's lines, logged before any background job is spawned: whoever
291    // waits for the serving line finds every listener bound, and no line of
292    // the sweep, the pack run or the rotation warning before it.
293    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    // The background jobs, each at start and then its interval after each
298    // run ends, until the server stops: the purge sweep, the pack run with
299    // Parquet storage, and the rotation warning. On a database that several
300    // servers serve, the sweep and the pack run are done by the one that
301    // holds the job's lease.
302    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    // With an operator listener each listener serves one kind of key;
329    // without one, the one listener serves both.
330    let (halt, halted) = tokio::sync::watch::channel(());
331    let until_halted = |mut halted: tokio::sync::watch::Receiver<()>| async move {
332        // An error is the sender dropped: halted as well.
333        let _ = halted.changed().await;
334    };
335    // Each time a listener finds every place held, that is counted in the
336    // admin log under the listener's configuration key. The count is
337    // written off the listener's task, which goes on to wait for a place.
338    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    // After every run has ended: a run going could renew a lease given up
393    // before it.
394    blocking(move || give_up_leases(&leaving)).await;
395    served.map_err(ServeError::Serve)
396}
397
398/// How long a stop waits for a background job's run before it logs that it
399/// still waits; it logs again each time this passes, and goes on waiting.
400const STOP_WARN: Duration = Duration::from_secs(30);
401
402/// One of the server's background jobs: runs of its work on the blocking
403/// pool, its interval apart, until it is stopped.
404struct Background {
405    /// The job's name in the stop's lines.
406    name: &'static str,
407    /// Set as the stop is asked: the work reads it before each step.
408    stopping: Arc<AtomicBool>,
409    /// Whether a run is on the blocking pool now.
410    running: Arc<AtomicBool>,
411    /// Tells [`every`] to start no further run.
412    tell: Option<tokio::sync::oneshot::Sender<()>>,
413    task: tokio::task::JoinHandle<()>,
414}
415
416impl Background {
417    /// Runs `work` at once, then `interval` after each run ends. `work` is
418    /// given a test of whether the server is stopping, which it makes
419    /// before each step (a tenant) and ends its run on.
420    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    /// Asks the job to stop: a run going ends at its next step, and no
460    /// run begins after it. The flag is set before [`every`] is told, so a
461    /// run that begins in between ends before its first step.
462    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    /// Waits for the job to end, after [`Background::ask`], however long
470    /// the run going takes: the data directory stays locked until then.
471    /// Logs that it waits, and again each [`STOP_WARN`].
472    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    /// Asks every job to stop, then waits for each to end.
506    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/// What one pack run over every tenant did.
517#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
518pub struct PackRunReport {
519    /// Pack files written and recorded, over every tenant.
520    pub files: u64,
521    /// Versions moved into them.
522    pub versions: u64,
523    /// Tenants whose run failed; they wait for the next run.
524    pub failed: u64,
525}
526
527/// One pack run over every tenant, as `Store::pack` does for one, with the
528/// configured limit and reader grace. A tenant whose run fails is
529/// counted and left for the next run. `stopping` is asked before each
530/// tenant's step: once it answers true, the run ends there, and the rest
531/// wait for the next run. Logged with counts only, never a tenant.
532pub 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
540/// [`pack_all`], asking `held` before each tenant, and stopping when it
541/// answers false, as [`sweep_while`] does.
542fn 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
580/// The shortest lease of a job: long enough for a renewal to arrive.
581const SHORTEST_LEASE: Duration = Duration::from_secs(60);
582
583/// The lease of a job that runs `interval` after each run ends: two
584/// intervals, and at least a minute. Its holder renews it at the start of
585/// each run and before each tenant, so it keeps the job while it runs;
586/// when it stops without a word, another server takes the job once the
587/// lease ends.
588#[must_use]
589pub fn lease_for(interval: Duration) -> Duration {
590    interval.saturating_mul(2).max(SHORTEST_LEASE)
591}
592
593/// One purge sweep: each tenant purges what is due under its own retention
594/// period, else `default`. A tenant that cannot be swept, such as one whose
595/// period does not read back or that is being removed, is counted and left
596/// for the next sweep. `stopping` is asked before each tenant's step: once
597/// it answers true, the sweep ends there, and the rest wait for the next
598/// sweep. The sweep is logged with counts only, never a tenant.
599pub fn sweep(tenants: &Tenants, default: Retention, stopping: &dyn Fn() -> bool) -> SweepReport {
600    sweep_while(tenants, default, &mut || !stopping())
601}
602
603/// Whether this server holds the lease of `job` for `ttl` now, taking or
604/// renewing it. A lease that cannot be read is not held.
605pub(crate) fn holds(tenants: &Tenants, job: Job, ttl: Duration) -> bool {
606    tenants.lead(job, ttl) == Ok(true)
607}
608
609/// The purge sweep, when this server holds its lease (several servers
610/// share one database; a data directory's server always holds it): the
611/// recovery of a running server first (`Tenants::recover_all`), then
612/// the sweep, which stops at a tenant where the lease is no longer held.
613/// `None` when another server holds the lease and does the sweep, or the
614/// server is stopping. `stopping` is asked before the lease each time,
615/// so a run of a stopping server takes and renews no lease: one given
616/// up at the stop stays given up.
617pub 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
638/// The pack run, when this server holds its lease, as [`lead_sweep`]
639/// holds the sweep's; `None` when another server holds it, or the server
640/// is stopping.
641pub 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
659/// Gives up this server's leases, as a server that stops does, so the
660/// next server takes the jobs at once. A lease not given up ends by
661/// itself.
662///
663/// A give-up that fails (the database refused it, or its commit did not
664/// go through) is made again, up to [`GIVE_UP_TRIES`] times; one still
665/// not made is logged as a warning naming the job, since the next server
666/// then waits for the lease to end by the database's clock. Answers how
667/// many leases were not given up.
668pub(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
684/// How many times a stopping server tries to give up each lease.
685pub(crate) const GIVE_UP_TRIES: usize = 3;
686
687/// A job's name in a log line.
688fn job_name(job: Job) -> &'static str {
689    match job {
690        Job::Sweep => "purge sweep",
691        Job::Pack => "pack run",
692    }
693}
694
695/// [`sweep`], asking `held` before each tenant, and stopping when it
696/// answers false: the lease went to another server, which sweeps the
697/// rest, or the server is stopping.
698pub 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/// What one purge sweep did.
733#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
734pub struct SweepReport {
735    /// Versions purged, over every tenant.
736    pub purged: u64,
737    /// Tenants that could not be swept; they wait for the next sweep.
738    pub failed: u64,
739}
740
741/// Runs `job` at once, then again `interval` after each run ends, until
742/// `shutdown` completes. A run going when it does is awaited to its end,
743/// so whoever awaits `every` waits for the run; no run begins after it.
744pub 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
765/// The configuration key that names the operator listener's key file:
766/// `operator.tls.key`, or `tls.key` when the `[operator]` table names no
767/// pair of its own and the listener takes the server's.
768fn 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
776/// What the API serves from on a listener of `plane`, as the
777/// configuration sets it.
778fn 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
796/// The public origin of the listener of `plane`: `operator.public_origin`
797/// for the operator listener, `public_origin` for the tenant listener and
798/// for the one listener of a server with no operator listener.
799fn 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
809/// Whether key rotation is overdue: the oldest purge or removal waiting
810/// for it is older than `rotation_warn`.
811pub 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
822/// How often `serve` looks at the rotation backlog.
823const ROTATION_CHECK: Duration = Duration::from_secs(86_400);
824
825/// Logs a warning, with counts only, when key rotation is overdue.
826fn 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        /// The refusal names the table that was taken out, says what goes
859        /// wrong without it, and where the tenants are named.
860        #[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        /// Catalogs the server may not open are counted apart from keys,
918        /// with the system's error, and never a tenant or a path.
919        #[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    /// The registry a server's start opens serves each tenant on local
1011    /// objects with the group sync of its commits (synchronous NORMAL), as
1012    /// #280 made it; release 0.4.18 served them with FULL.
1013    #[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    /// A configuration with these lines before and after the least one.
1040    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        /// A vCon stored and deleted in `id` while seven years apply, so
1117        /// it waits hidden for a sweep.
1118        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        /// How many versions `id` still keeps.
1129        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            // The lease is asked for before each tenant: a run that lost it
1277            // at the first is asked no more.
1278            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        /// A run that is going when shutdown comes is awaited, so whoever
1374        /// awaits `every` waits for the run.
1375        #[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}