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    let order = tenants.key_order().map_err(ServeError::Registry)?;
237    if !order.is_sound() {
238        return Err(ServeError::KeysOutOfOrder(order));
239    }
240    // Packed versions need Parquet storage kept on: nothing turns them
241    // back into objects, and only with it is the bucket checked for what
242    // would keep a purged row's bytes.
243    if config.storage.parquet.is_none() {
244        let tenants = tenants
245            .tenants_with_packed_versions()
246            .map_err(ServeError::Registry)?;
247        if tenants > 0 {
248            return Err(ServeError::ParquetRemoved { tenants });
249        }
250    }
251    Ok(tenants)
252}
253
254/// Serves the opened registry until `shutdown` completes or a listener
255/// fails.
256async fn serve_opened(
257    config: &Config,
258    tenants: Tenants,
259    shutdown: impl Future<Output = ()>,
260) -> Result<(), ServeError> {
261    let tls = api::tls_config(&config.tls_cert, &config.tls_key).map_err(ServeError::Tls)?;
262    let listener = TcpListener::bind(config.listen)
263        .await
264        .map_err(ServeError::Listen)?;
265    // The address bound, which names the port the system chose when the
266    // configuration gives port 0.
267    let bound = listener.local_addr().map_err(ServeError::Listen)?;
268    // The operator listener, when the configuration has one: bound before
269    // anything is served, so a start that cannot have both serves neither.
270    let operator = match &config.operator {
271        Some(operator) => {
272            let tls = api::tls_config_named(
273                &operator.tls_cert,
274                &operator.tls_key,
275                operator_key_name(config, operator),
276            )
277            .map_err(ServeError::OperatorTls)?;
278            let listener = TcpListener::bind(operator.listen)
279                .await
280                .map_err(ServeError::OperatorListen)?;
281            let bound = listener.local_addr().map_err(ServeError::OperatorListen)?;
282            Some((listener, tls, bound))
283        }
284        None => None,
285    };
286    let tenants = Arc::new(tenants);
287    // Kept to give up this server's leases when it stops.
288    let leaving = tenants.clone();
289    // The start's lines, logged before any background job is spawned: whoever
290    // waits for the serving line finds every listener bound, and no line of
291    // the sweep, the pack run or the rotation warning before it.
292    if let Some((_, _, operator_bound)) = &operator {
293        tracing::info!(operator_listen = %operator_bound, "the operator listener is bound");
294    }
295    tracing::info!(listen = %bound, "serving");
296    // The background jobs, each at start and then its interval after each
297    // run ends, until the server stops: the purge sweep, the pack run with
298    // Parquet storage, and the rotation warning. On a database that several
299    // servers serve, the sweep and the pack run are done by the one that
300    // holds the job's lease.
301    let (swept, default) = (tenants.clone(), config.retention_default);
302    let ttl = lease_for(config.purge_interval);
303    let mut jobs = vec![Background::start(
304        "purge sweep",
305        config.purge_interval,
306        move |stopping| {
307            lead_sweep(&swept, default, ttl, stopping);
308        },
309    )];
310    if let Some(parquet) = config.storage.parquet {
311        let packed = tenants.clone();
312        let ttl = lease_for(parquet.pack_interval);
313        jobs.push(Background::start(
314            "pack run",
315            parquet.pack_interval,
316            move |stopping| {
317                lead_pack(&packed, &parquet, ttl, stopping);
318            },
319        ));
320    }
321    let (watched, rotation_warn) = (tenants.clone(), config.rotation_warn);
322    jobs.push(Background::start(
323        "rotation warning",
324        ROTATION_CHECK,
325        move |_| warn_if_rotation_overdue(&watched, rotation_warn),
326    ));
327    // With an operator listener each listener serves one kind of key;
328    // without one, the one listener serves both.
329    let (halt, halted) = tokio::sync::watch::channel(());
330    let until_halted = |mut halted: tokio::sync::watch::Receiver<()>| async move {
331        // An error is the sender dropped: halted as well.
332        let _ = halted.changed().await;
333    };
334    // Each time a listener finds every place held, that is counted in the
335    // admin log under the listener's configuration key. The count is
336    // written off the listener's task, which goes on to wait for a place.
337    let counted = tenants.clone();
338    let counts_full = move |key: &'static str| {
339        let tenants = counted.clone();
340        move || {
341            let tenants = tenants.clone();
342            tokio::task::spawn_blocking(move || tenants.count_listener_full(key));
343        }
344    };
345    let both = async {
346        let Some((operator_listener, operator_tls, _)) = operator else {
347            let full = counts_full("listen");
348            let app = app_from(config, tenants, Plane::Both);
349            return api::serve_observed(
350                listener,
351                tls,
352                api::router(Arc::new(app)),
353                until_halted(halted),
354                config.connection,
355                full,
356            )
357            .await;
358        };
359        let (tenant_full, operator_full) = (counts_full("listen"), counts_full("operator.listen"));
360        let tenant_app = app_from(config, tenants.clone(), Plane::Tenant);
361        let operator_app = app_from(config, tenants, Plane::Operator);
362        let (tenant, operator) = tokio::join!(
363            api::serve_observed(
364                listener,
365                tls,
366                api::router(Arc::new(tenant_app)),
367                until_halted(halted.clone()),
368                config.connection,
369                tenant_full,
370            ),
371            api::serve_observed(
372                operator_listener,
373                operator_tls,
374                api::router(Arc::new(operator_app)),
375                until_halted(halted),
376                config.connection,
377                operator_full,
378            ),
379        );
380        tenant.and(operator)
381    };
382    let mut both = std::pin::pin!(both);
383    let served = tokio::select! {
384        served = &mut both => served,
385        () = shutdown => {
386            let _ = halt.send(());
387            both.await
388        }
389    };
390    Background::stop_all(jobs).await;
391    // After every run has ended: a run going could renew a lease given up
392    // before it.
393    blocking(move || give_up_leases(&leaving)).await;
394    served.map_err(ServeError::Serve)
395}
396
397/// How long a stop waits for a background job's run before it logs that it
398/// still waits; it logs again each time this passes, and goes on waiting.
399const STOP_WARN: Duration = Duration::from_secs(30);
400
401/// One of the server's background jobs: runs of its work on the blocking
402/// pool, its interval apart, until it is stopped.
403struct Background {
404    /// The job's name in the stop's lines.
405    name: &'static str,
406    /// Set as the stop is asked: the work reads it before each step.
407    stopping: Arc<AtomicBool>,
408    /// Whether a run is on the blocking pool now.
409    running: Arc<AtomicBool>,
410    /// Tells [`every`] to start no further run.
411    tell: Option<tokio::sync::oneshot::Sender<()>>,
412    task: tokio::task::JoinHandle<()>,
413}
414
415impl Background {
416    /// Runs `work` at once, then `interval` after each run ends. `work` is
417    /// given a test of whether the server is stopping, which it makes
418    /// before each step (a tenant) and ends its run on.
419    fn start(
420        name: &'static str,
421        interval: Duration,
422        work: impl Fn(&dyn Fn() -> bool) + Send + Sync + 'static,
423    ) -> Background {
424        let stopping = Arc::new(AtomicBool::new(false));
425        let running = Arc::new(AtomicBool::new(false));
426        let (tell, told) = tokio::sync::oneshot::channel::<()>();
427        let work = Arc::new(work);
428        let (asked, busy) = (stopping.clone(), running.clone());
429        let task = tokio::spawn(every(
430            interval,
431            async {
432                let _ = told.await;
433            },
434            move || {
435                let (work, asked, busy) = (work.clone(), asked.clone(), busy.clone());
436                async move {
437                    busy.store(true, Ordering::SeqCst);
438                    let ran = tokio::task::spawn_blocking(move || {
439                        work(&|| asked.load(Ordering::SeqCst));
440                    })
441                    .await;
442                    busy.store(false, Ordering::SeqCst);
443                    if let Err(error) = ran {
444                        tracing::error!(job = name, error = %error, "a background job's run failed");
445                    }
446                }
447            },
448        ));
449        Background {
450            name,
451            stopping,
452            running,
453            tell: Some(tell),
454            task,
455        }
456    }
457
458    /// Asks the job to stop: a run going ends at its next step, and no
459    /// run begins after it. The flag is set before [`every`] is told, so a
460    /// run that begins in between ends before its first step.
461    fn ask(&mut self) {
462        self.stopping.store(true, Ordering::SeqCst);
463        if let Some(tell) = self.tell.take() {
464            let _ = tell.send(());
465        }
466    }
467
468    /// Waits for the job to end, after [`Background::ask`], however long
469    /// the run going takes: the data directory stays locked until then.
470    /// Logs that it waits, and again each [`STOP_WARN`].
471    async fn join(self) {
472        let Background {
473            name,
474            running,
475            mut task,
476            ..
477        } = self;
478        if running.load(Ordering::SeqCst) {
479            tracing::info!(
480                job = name,
481                "stopping: waiting for a background job's run to end"
482            );
483        }
484        let mut waited = Duration::ZERO;
485        loop {
486            match tokio::time::timeout(STOP_WARN, &mut task).await {
487                Ok(Ok(())) => return,
488                Ok(Err(error)) => {
489                    tracing::error!(job = name, error = %error, "a background job's run failed");
490                    return;
491                }
492                Err(_) => {
493                    waited += STOP_WARN;
494                    tracing::warn!(
495                        job = name,
496                        waited_secs = waited.as_secs(),
497                        "stopping: a background job's run has not ended; the stop goes on waiting"
498                    );
499                }
500            }
501        }
502    }
503
504    /// Asks every job to stop, then waits for each to end.
505    async fn stop_all(mut jobs: Vec<Background>) {
506        for job in &mut jobs {
507            job.ask();
508        }
509        for job in jobs {
510            job.join().await;
511        }
512    }
513}
514
515/// What one pack run over every tenant did.
516#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
517pub struct PackRunReport {
518    /// Pack files written and recorded, over every tenant.
519    pub files: u64,
520    /// Versions moved into them.
521    pub versions: u64,
522    /// Tenants whose run failed; they wait for the next run.
523    pub failed: u64,
524}
525
526/// One pack run over every tenant, as `Store::pack` does for one, with the
527/// configured limit and reader grace. A tenant whose run fails is
528/// counted and left for the next run. `stopping` is asked before each
529/// tenant's step: once it answers true, the run ends there, and the rest
530/// wait for the next run. Logged with counts only, never a tenant.
531pub fn pack_all(
532    tenants: &Tenants,
533    settings: &ParquetSettings,
534    stopping: &dyn Fn() -> bool,
535) -> PackRunReport {
536    pack_while(tenants, settings, &mut || !stopping())
537}
538
539/// [`pack_all`], asking `held` before each tenant, and stopping when it
540/// answers false, as [`sweep_while`] does.
541fn pack_while(
542    tenants: &Tenants,
543    settings: &ParquetSettings,
544    held: &mut dyn FnMut() -> bool,
545) -> PackRunReport {
546    let mut report = PackRunReport::default();
547    let plan = crate::store::packer::PackPlan {
548        grace: settings.reader_grace,
549        ..crate::store::packer::PackPlan::with_limit(settings.pack_limit)
550    };
551    match tenants.ids() {
552        Ok(ids) => {
553            for id in ids {
554                if !held() {
555                    break;
556                }
557                #[cfg(test)]
558                tenants.job_steps_for_test("pack run");
559                match tenants.store(id).map(|store| store.pack(&plan)) {
560                    Ok(Ok(done)) => {
561                        report.files += done.files;
562                        report.versions += done.versions;
563                    }
564                    _ => report.failed += 1,
565                }
566            }
567        }
568        Err(_) => report.failed += 1,
569    }
570    tracing::info!(
571        files = report.files,
572        versions = report.versions,
573        failed = report.failed,
574        "pack run"
575    );
576    report
577}
578
579/// The shortest lease of a job: long enough for a renewal to arrive.
580const SHORTEST_LEASE: Duration = Duration::from_secs(60);
581
582/// The lease of a job that runs `interval` after each run ends: two
583/// intervals, and at least a minute. Its holder renews it at the start of
584/// each run and before each tenant, so it keeps the job while it runs;
585/// when it stops without a word, another server takes the job once the
586/// lease ends.
587#[must_use]
588pub fn lease_for(interval: Duration) -> Duration {
589    interval.saturating_mul(2).max(SHORTEST_LEASE)
590}
591
592/// One purge sweep: each tenant purges what is due under its own retention
593/// period, else `default`. A tenant that cannot be swept, such as one whose
594/// period does not read back or that is being removed, is counted and left
595/// for the next sweep. `stopping` is asked before each tenant's step: once
596/// it answers true, the sweep ends there, and the rest wait for the next
597/// sweep. The sweep is logged with counts only, never a tenant.
598pub fn sweep(tenants: &Tenants, default: Retention, stopping: &dyn Fn() -> bool) -> SweepReport {
599    sweep_while(tenants, default, &mut || !stopping())
600}
601
602/// Whether this server holds the lease of `job` for `ttl` now, taking or
603/// renewing it. A lease that cannot be read is not held.
604pub(crate) fn holds(tenants: &Tenants, job: Job, ttl: Duration) -> bool {
605    tenants.lead(job, ttl) == Ok(true)
606}
607
608/// The purge sweep, when this server holds its lease (several servers
609/// share one database; a data directory's server always holds it): the
610/// recovery of a running server first (`Tenants::recover_all`), then
611/// the sweep, which stops at a tenant where the lease is no longer held.
612/// `None` when another server holds the lease and does the sweep, or the
613/// server is stopping. `stopping` is asked before the lease each time,
614/// so a run of a stopping server takes and renews no lease: one given
615/// up at the stop stays given up.
616pub fn lead_sweep(
617    tenants: &Tenants,
618    default: Retention,
619    ttl: Duration,
620    stopping: &dyn Fn() -> bool,
621) -> Option<SweepReport> {
622    if stopping() {
623        return None;
624    }
625    if !holds(tenants, Job::Sweep, ttl) {
626        tracing::info!("purge sweep: another server holds it");
627        return None;
628    }
629    let recovery_failed = tenants.recover_all().unwrap_or(1);
630    let mut report = sweep_while(tenants, default, &mut || {
631        !stopping() && holds(tenants, Job::Sweep, ttl)
632    });
633    report.failed += recovery_failed;
634    Some(report)
635}
636
637/// The pack run, when this server holds its lease, as [`lead_sweep`]
638/// holds the sweep's; `None` when another server holds it, or the server
639/// is stopping.
640pub fn lead_pack(
641    tenants: &Tenants,
642    settings: &ParquetSettings,
643    ttl: Duration,
644    stopping: &dyn Fn() -> bool,
645) -> Option<PackRunReport> {
646    if stopping() {
647        return None;
648    }
649    if !holds(tenants, Job::Pack, ttl) {
650        tracing::info!("pack run: another server holds it");
651        return None;
652    }
653    Some(pack_while(tenants, settings, &mut || {
654        !stopping() && holds(tenants, Job::Pack, ttl)
655    }))
656}
657
658/// Gives up this server's leases, as a server that stops does, so the
659/// next server takes the jobs at once. A lease not given up ends by
660/// itself.
661///
662/// A give-up that fails (the database refused it, or its commit did not
663/// go through) is made again, up to [`GIVE_UP_TRIES`] times; one still
664/// not made is logged as a warning naming the job, since the next server
665/// then waits for the lease to end by the database's clock. Answers how
666/// many leases were not given up.
667pub(crate) fn give_up_leases(tenants: &Tenants) -> usize {
668    let mut kept = 0;
669    for job in [Job::Sweep, Job::Pack] {
670        let given_up = (0..GIVE_UP_TRIES).any(|_| tenants.step_down(job).is_ok());
671        if !given_up {
672            kept += 1;
673            tracing::warn!(
674                job = job_name(job),
675                tries = GIVE_UP_TRIES,
676                "the lease could not be given up: another server takes the job when it ends"
677            );
678        }
679    }
680    kept
681}
682
683/// How many times a stopping server tries to give up each lease.
684pub(crate) const GIVE_UP_TRIES: usize = 3;
685
686/// A job's name in a log line.
687fn job_name(job: Job) -> &'static str {
688    match job {
689        Job::Sweep => "purge sweep",
690        Job::Pack => "pack run",
691    }
692}
693
694/// [`sweep`], asking `held` before each tenant, and stopping when it
695/// answers false: the lease went to another server, which sweeps the
696/// rest, or the server is stopping.
697pub fn sweep_while(
698    tenants: &Tenants,
699    default: Retention,
700    held: &mut dyn FnMut() -> bool,
701) -> SweepReport {
702    let mut report = SweepReport::default();
703    match tenants.ids() {
704        Ok(ids) => {
705            for id in ids {
706                if !held() {
707                    break;
708                }
709                #[cfg(test)]
710                tenants.job_steps_for_test("purge sweep");
711                let purged = tenants.retention(id).and_then(|own| {
712                    let store = tenants.store(id)?;
713                    Ok(store.purge_due(crate::tenants::kept_for(own, default)))
714                });
715                match purged {
716                    Ok(Ok(done)) => report.purged += done.purged,
717                    _ => report.failed += 1,
718                }
719            }
720        }
721        Err(_) => report.failed += 1,
722    }
723    tracing::info!(
724        purged = report.purged,
725        failed = report.failed,
726        "purge sweep"
727    );
728    report
729}
730
731/// What one purge sweep did.
732#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
733pub struct SweepReport {
734    /// Versions purged, over every tenant.
735    pub purged: u64,
736    /// Tenants that could not be swept; they wait for the next sweep.
737    pub failed: u64,
738}
739
740/// Runs `job` at once, then again `interval` after each run ends, until
741/// `shutdown` completes. A run going when it does is awaited to its end,
742/// so whoever awaits `every` waits for the run; no run begins after it.
743pub async fn every<F, Fut>(interval: Duration, shutdown: impl Future<Output = ()>, mut job: F)
744where
745    F: FnMut() -> Fut,
746    Fut: Future<Output = ()>,
747{
748    tokio::pin!(shutdown);
749    loop {
750        tokio::select! {
751            biased;
752            () = &mut shutdown => return,
753            () = std::future::ready(()) => {}
754        }
755        job().await;
756        tokio::select! {
757            biased;
758            () = &mut shutdown => return,
759            () = tokio::time::sleep(interval) => {}
760        }
761    }
762}
763
764/// The configuration key that names the operator listener's key file:
765/// `operator.tls.key`, or `tls.key` when the `[operator]` table names no
766/// pair of its own and the listener takes the server's.
767fn operator_key_name(config: &Config, operator: &Operator) -> &'static str {
768    if operator.tls_key == config.tls_key && operator.tls_cert == config.tls_cert {
769        "tls.key"
770    } else {
771        "operator.tls.key"
772    }
773}
774
775/// What the API serves from on a listener of `plane`, as the
776/// configuration sets it.
777fn app_from(config: &Config, tenants: Arc<Tenants>, plane: Plane) -> App {
778    tenants.allow_no_expiry(config.keys_no_expiry);
779    App {
780        tenants,
781        limits: Limits {
782            body: config.body_limit,
783            inflated: config.inflated_limit,
784            body_timeout: config.read_timeout,
785        },
786        supported: config.supported_critical.clone(),
787        retention_default: config.retention_default,
788        mcp: config.mcp,
789        plane,
790        reports: crate::api::ReportGate::new(config.reports),
791        origin: origin_for(config, plane),
792    }
793}
794
795/// The public origin of the listener of `plane`: `operator.public_origin`
796/// for the operator listener, `public_origin` for the tenant listener and
797/// for the one listener of a server with no operator listener.
798fn origin_for(config: &Config, plane: Plane) -> Option<crate::session::Origin> {
799    match plane {
800        Plane::Both | Plane::Tenant => config.public_origin.clone(),
801        Plane::Operator => config
802            .operator
803            .as_ref()
804            .and_then(|operator| operator.public_origin.clone()),
805    }
806}
807
808/// Whether key rotation is overdue: the oldest purge or removal waiting
809/// for it is older than `rotation_warn`.
810pub fn rotation_overdue(
811    backlog: &RotationBacklog,
812    rotation_warn: Duration,
813    now: OffsetDateTime,
814) -> bool {
815    [backlog.oldest_purge, backlog.oldest_removal]
816        .into_iter()
817        .flatten()
818        .any(|at| now - at > rotation_warn)
819}
820
821/// How often `serve` looks at the rotation backlog.
822const ROTATION_CHECK: Duration = Duration::from_secs(86_400);
823
824/// Logs a warning, with counts only, when key rotation is overdue.
825fn warn_if_rotation_overdue(tenants: &Tenants, rotation_warn: Duration) {
826    match tenants.rotation_backlog() {
827        Ok(backlog) if rotation_overdue(&backlog, rotation_warn, SystemClock.now()) => {
828            tracing::warn!(
829                tenants_with_purges = backlog.tenants_with_purges,
830                purges = backlog.purges,
831                removals = backlog.removals,
832                "key rotation overdue: purged vCons and removed tenants stay readable on old copies until it"
833            );
834        }
835        Ok(_) => {}
836        Err(_) => tracing::warn!("the key rotation backlog could not be read"),
837    }
838}
839
840#[cfg(test)]
841mod start_tests;
842
843#[cfg(test)]
844mod stop_tests;
845
846#[cfg(test)]
847mod tests {
848    use std::time::Duration;
849
850    use super::*;
851
852    mod startup {
853        use time::macros::datetime;
854
855        use super::*;
856
857        /// The refusal names the table that was taken out, says what goes
858        /// wrong without it, and where the tenants are named.
859        #[test]
860        fn a_start_without_storage_parquet_over_packed_versions_names_the_table() {
861            assert_eq!(
862                ServeError::ParquetRemoved { tenants: 2 }.to_string(),
863                "2 tenant(s) have versions packed into Parquet files, and the configuration has no \
864                 [storage.parquet]: without it the server packs no more, and the start no longer \
865                 refuses a bucket with Object Lock or versioning, either of which keeps the bytes of \
866                 a pack file that a purge rewrote; put the [storage.parquet] table back, since packed \
867                 versions cannot be turned back into objects; vcon-server check names the tenants",
868                "the refusal's text"
869            );
870        }
871
872        const NOW: OffsetDateTime = datetime!(2026-10-25 12:00 UTC);
873        const DAY: Duration = Duration::from_secs(86_400);
874
875        #[test]
876        fn rotation_is_overdue_once_the_oldest_waiting_work_passes_rotation_warn() {
877            let backlog =
878                |purge: Option<OffsetDateTime>, removal: Option<OffsetDateTime>| RotationBacklog {
879                    tenants_with_purges: u64::from(purge.is_some()),
880                    purges: u64::from(purge.is_some()),
881                    oldest_purge: purge,
882                    removals: u64::from(removal.is_some()),
883                    oldest_removal: removal,
884                };
885            let day_ago = Some(datetime!(2026-10-24 12:00 UTC));
886            let older = Some(datetime!(2026-10-24 11:59:59 UTC));
887            for (b, overdue) in [
888                (backlog(None, None), false),
889                (backlog(day_ago, None), false),
890                (backlog(older, None), true),
891                (backlog(None, older), true),
892                (backlog(day_ago, older), true),
893            ] {
894                assert_eq!(rotation_overdue(&b, DAY, NOW), overdue, "{b:?}");
895            }
896        }
897
898        #[test]
899        fn a_refusal_for_keys_out_of_order_counts_and_points_at_check() {
900            let order = KeyOrder {
901                wrapped_elsewhere: 1,
902                rotations_stopped: 2,
903                data_under_other_keys: 3,
904                ..KeyOrder::default()
905            };
906            assert_eq!(
907                ServeError::KeysOutOfOrder(order).to_string(),
908                "1 tenant key(s) do not unwrap under the master key; \
909                 2 key rotation(s) stopped part way; run rekey tenant again; \
910                 3 tenant(s) with data under another key; \
911                 vcon-server check names the tenants",
912                "each count in its fixed place, then where to look"
913            );
914        }
915
916        /// Catalogs the server may not open are counted apart from keys,
917        /// with the system's error, and never a tenant or a path.
918        #[test]
919        fn a_refusal_for_catalogs_it_may_not_open_gives_the_error_not_a_key() {
920            let order = KeyOrder {
921                catalogs_unopened: 2,
922                unopened_error: Some("Permission denied (os error 13)".to_owned()),
923                ..KeyOrder::default()
924            };
925            assert_eq!(
926                ServeError::KeysOutOfOrder(order).to_string(),
927                "2 tenant catalog(s) cannot be opened: Permission denied (os error 13); vcon-server check names the tenants"
928            );
929        }
930    }
931    use crate::retention::Retention;
932
933    #[test]
934    fn the_api_takes_its_limits_and_extensions_from_the_configuration() {
935        let dir = tempfile::tempdir().expect("temp dir");
936        let tenants = Arc::new(
937            Tenants::open(
938                dir.path(),
939                Key::generate().expect("key"),
940                Arc::new(OsFs),
941                Arc::new(SystemClock),
942            )
943            .expect("opens"),
944        );
945        let config = Config {
946            listen: "127.0.0.1:8443".parse().expect("address"),
947            tls_cert: "cert.pem".into(),
948            tls_key: "key.pem".into(),
949            data_dir: dir.path().to_owned(),
950            master_key: "master.key".into(),
951            retention_default: Retention::Months(18),
952            purge_interval: Duration::from_secs(3600),
953            rotation_warn: Duration::from_secs(86400),
954            body_limit: 12_345,
955            inflated_limit: 67_890,
956            read_timeout: Duration::from_secs(17),
957            connection: crate::api::ConnectionLimits::default(),
958            supported_critical: ["known".to_owned()].into(),
959            mcp: crate::mcp::Limits {
960                calls_per_second: 3,
961                concurrent: 4,
962                response_bytes: 5,
963            },
964            reports: crate::api::ReportLimits::DEFAULT,
965            storage: crate::config::Storage::default(),
966            export: crate::config::Export::default(),
967            catalog: crate::config::CatalogStore::Local,
968            operator: None,
969            public_origin: None,
970            keys_no_expiry: false,
971        };
972        assert!(
973            tenants.no_expiry_allowed(),
974            "before the configuration is applied a key may have no expiry"
975        );
976        let app = app_from(&config, tenants.clone(), Plane::Tenant);
977        assert!(
978            !tenants.no_expiry_allowed(),
979            "keys.no_expiry = false reaches the registry the API makes keys in"
980        );
981        assert_eq!(app.plane, Plane::Tenant, "the plane it was given");
982        assert!(Arc::ptr_eq(&app.tenants, &tenants));
983        assert_eq!(app.limits.body, 12_345);
984        assert_eq!(app.limits.inflated, 67_890);
985        assert_eq!(app.limits.body_timeout, Duration::from_secs(17));
986        assert_eq!(app.supported, config.supported_critical);
987        assert_eq!(app.retention_default, config.retention_default);
988        assert_eq!(app.mcp, config.mcp);
989        assert_eq!(app.origin, None, "no public origin is configured");
990    }
991
992    /// A configuration with these lines before and after the least one.
993    fn configured(first: &str, last: &str) -> Config {
994        let text = format!(
995            "{first}listen = \"127.0.0.1:8443\"\ndata_dir = \"/var/lib/vcon-server\"\n\
996             master_key = \"/etc/vcon-server/master.key\"\n[tls]\ncert = \"/c.pem\"\n\
997             key = \"/k.pem\"\n{last}"
998        );
999        crate::config::parse(&text).expect("a configuration")
1000    }
1001
1002    const OPERATOR: &str =
1003        "[operator]\nlisten = \"127.0.0.1:8444\"\npublic_origin = \"https://ops.example.com\"\n";
1004
1005    #[test]
1006    fn each_listener_takes_its_own_public_origin() {
1007        let config = configured("public_origin = \"https://vcon.example.com\"\n", OPERATOR);
1008        let origin = |plane| origin_for(&config, plane).map(|o| o.as_str().to_owned());
1009        assert_eq!(
1010            origin(Plane::Tenant).as_deref(),
1011            Some("https://vcon.example.com"),
1012            "`listen` takes public_origin"
1013        );
1014        assert_eq!(
1015            origin(Plane::Operator).as_deref(),
1016            Some("https://ops.example.com"),
1017            "`operator.listen` takes operator.public_origin"
1018        );
1019    }
1020
1021    #[test]
1022    fn the_one_listener_of_a_server_takes_public_origin_for_both_planes() {
1023        let config = configured("public_origin = \"https://vcon.example.com\"\n", "");
1024        assert_eq!(
1025            origin_for(&config, Plane::Both),
1026            crate::session::Origin::parse("https://vcon.example.com"),
1027            "tenants' and operators' sessions come from the one origin"
1028        );
1029    }
1030
1031    #[test]
1032    fn a_listener_with_no_public_origin_has_none_and_does_not_take_the_other_s() {
1033        let config = configured("", OPERATOR);
1034        assert_eq!(
1035            origin_for(&config, Plane::Tenant),
1036            None,
1037            "not the operator's"
1038        );
1039        let config = configured("public_origin = \"https://vcon.example.com\"\n", "");
1040        assert_eq!(
1041            origin_for(&config, Plane::Operator),
1042            None,
1043            "not the tenant's"
1044        );
1045        let config = configured("", "");
1046        assert_eq!(origin_for(&config, Plane::Both), None, "none is configured");
1047    }
1048
1049    mod sweeps {
1050        use std::sync::Arc;
1051        use std::sync::atomic::{AtomicUsize, Ordering};
1052        use std::time::Duration;
1053
1054        use time::macros::datetime;
1055        use uuid::Uuid;
1056
1057        use crate::audit::Actor;
1058        use crate::ids::{KeyId, TenantId};
1059        use crate::retention::Retention;
1060        use crate::serve::{
1061            PackRunReport, SweepReport, every, lead_pack, lead_sweep, lease_for, sweep, sweep_while,
1062        };
1063        use crate::store::Caller;
1064        use crate::store::testing::vcon;
1065        use crate::tenants::{Tenants, fixture};
1066
1067        const CALLER: Caller = Caller { key: KeyId([7; 8]) };
1068
1069        /// A vCon stored and deleted in `id` while seven years apply, so
1070        /// it waits hidden for a sweep.
1071        fn deleted(tenants: &Tenants, id: TenantId, uuid: &str) -> Uuid {
1072            let store = tenants.store(id).expect("its store");
1073            let (found, body) = vcon(uuid, "kept");
1074            store.create(&CALLER, &found, &body).expect("stored");
1075            store
1076                .delete(&CALLER, found.uuid, Retention::Years(7))
1077                .expect("deleted");
1078            found.uuid
1079        }
1080
1081        /// How many versions `id` still keeps.
1082        fn kept(tenants: &Tenants, id: TenantId) -> u64 {
1083            tenants
1084                .store(id)
1085                .expect("its store")
1086                .counts()
1087                .expect("counts")
1088                .versions
1089        }
1090
1091        #[test]
1092        fn a_sweep_purges_what_is_due_in_each_tenant_under_its_own_period() {
1093            let f = fixture();
1094            let own = f
1095                .tenants
1096                .create(Actor::Cli, "own", Some(Retention::Days(1)))
1097                .expect("made");
1098            let default = f.tenants.create(Actor::Cli, "default", None).expect("made");
1099            let long = f
1100                .tenants
1101                .create(Actor::Cli, "long", Some(Retention::Years(7)))
1102                .expect("made");
1103            deleted(&f.tenants, own, "0199e5c6-0d7a-7c11-8000-000000000001");
1104            deleted(&f.tenants, default, "0199e5c6-0d7a-7c11-8000-000000000002");
1105            deleted(&f.tenants, long, "0199e5c6-0d7a-7c11-8000-000000000003");
1106            f.clock.set(datetime!(2026-10-25 13:00 UTC));
1107
1108            let report = sweep(&f.tenants, Retention::Days(1), &|| false);
1109
1110            assert_eq!(
1111                report,
1112                SweepReport {
1113                    purged: 2,
1114                    failed: 0
1115                }
1116            );
1117            assert_eq!(kept(&f.tenants, own), 0);
1118            assert_eq!(kept(&f.tenants, default), 0);
1119            assert_eq!(kept(&f.tenants, long), 1, "seven years have not passed");
1120        }
1121
1122        #[test]
1123        fn a_lease_lasts_two_intervals_so_its_holder_renews_it_in_time() {
1124            assert_eq!(
1125                lease_for(Duration::from_secs(3_600)),
1126                Duration::from_secs(7_200),
1127                "an hour's sweep holds its lease two hours"
1128            );
1129        }
1130
1131        #[test]
1132        fn a_server_with_a_data_directory_always_leads_the_sweep() {
1133            let f = fixture();
1134            let own = f
1135                .tenants
1136                .create(Actor::Cli, "own", Some(Retention::Days(1)))
1137                .expect("made");
1138            deleted(&f.tenants, own, "0199e5c6-0d7a-7c11-8000-000000000001");
1139            f.clock.set(datetime!(2026-10-25 13:00 UTC));
1140            assert_eq!(
1141                lead_sweep(
1142                    &f.tenants,
1143                    Retention::Days(1),
1144                    lease_for(Duration::from_secs(60)),
1145                    &|| false
1146                ),
1147                Some(SweepReport {
1148                    purged: 1,
1149                    failed: 0
1150                }),
1151                "one process: it always holds the lease"
1152            );
1153            assert_eq!(kept(&f.tenants, own), 0, "purged");
1154        }
1155
1156        #[test]
1157        fn a_server_with_a_data_directory_always_leads_the_pack_run() {
1158            let f = fixture();
1159            let settings = crate::config::ParquetSettings {
1160                pack_interval: crate::config::PACK_INTERVAL,
1161                pack_limit: crate::config::PACK_LIMIT,
1162                reader_grace: crate::config::READER_GRACE,
1163            };
1164            assert_eq!(
1165                lead_pack(
1166                    &f.tenants,
1167                    &settings,
1168                    lease_for(settings.pack_interval),
1169                    &|| false
1170                ),
1171                Some(PackRunReport::default()),
1172                "no tenant, nothing packed, and the run was this server's"
1173            );
1174        }
1175
1176        #[test]
1177        fn a_sweep_stops_at_the_tenant_where_its_lease_was_lost() {
1178            let f = fixture();
1179            let first = f
1180                .tenants
1181                .create(Actor::Cli, "a-first", Some(Retention::Days(1)))
1182                .expect("made");
1183            let second = f
1184                .tenants
1185                .create(Actor::Cli, "b-second", Some(Retention::Days(1)))
1186                .expect("made");
1187            deleted(&f.tenants, first, "0199e5c6-0d7a-7c11-8000-000000000001");
1188            deleted(&f.tenants, second, "0199e5c6-0d7a-7c11-8000-000000000002");
1189            f.clock.set(datetime!(2026-10-25 13:00 UTC));
1190            let mut asked = 0;
1191            let report = sweep_while(&f.tenants, Retention::Days(1), &mut || {
1192                asked += 1;
1193                asked == 1
1194            });
1195            assert_eq!(report.purged, 1, "the first tenant only: {report:?}");
1196            assert_eq!(asked, 2, "asked before each tenant");
1197            assert_eq!(
1198                kept(&f.tenants, first) + kept(&f.tenants, second),
1199                1,
1200                "the other waits for the next holder"
1201            );
1202        }
1203
1204        #[test]
1205        fn a_sweep_that_does_not_hold_its_lease_at_the_start_sweeps_nothing() {
1206            let f = fixture();
1207            let own = f
1208                .tenants
1209                .create(Actor::Cli, "own", Some(Retention::Days(1)))
1210                .expect("made");
1211            deleted(&f.tenants, own, "0199e5c6-0d7a-7c11-8000-000000000001");
1212            f.clock.set(datetime!(2026-10-25 13:00 UTC));
1213            let report = sweep_while(&f.tenants, Retention::Days(1), &mut || false);
1214            assert_eq!(report, SweepReport::default(), "nothing");
1215            assert_eq!(kept(&f.tenants, own), 1, "kept for the holder");
1216        }
1217
1218        #[test]
1219        fn a_pack_run_stops_at_the_tenant_where_its_lease_was_lost() {
1220            let f = fixture();
1221            for name in ["a-first", "b-second"] {
1222                f.tenants.create(Actor::Cli, name, None).expect("made");
1223            }
1224            let settings = crate::config::ParquetSettings {
1225                pack_interval: crate::config::PACK_INTERVAL,
1226                pack_limit: crate::config::PACK_LIMIT,
1227                reader_grace: crate::config::READER_GRACE,
1228            };
1229            // The lease is asked for before each tenant: a run that lost it
1230            // at the first is asked no more.
1231            let mut asked = 0;
1232            super::super::pack_while(&f.tenants, &settings, &mut || {
1233                asked += 1;
1234                true
1235            });
1236            assert_eq!(asked, 2, "asked before each tenant");
1237            let mut asked = 0;
1238            let none = super::super::pack_while(&f.tenants, &settings, &mut || {
1239                asked += 1;
1240                false
1241            });
1242            assert_eq!(asked, 1, "the run stopped at the first tenant");
1243            assert_eq!(none, PackRunReport::default(), "nothing done: {none:?}");
1244        }
1245
1246        #[test]
1247        fn a_lease_never_lasts_less_than_a_minute() {
1248            assert_eq!(
1249                lease_for(Duration::from_secs(10)),
1250                Duration::from_secs(60),
1251                "a short interval still gives a renewal time to arrive"
1252            );
1253            assert_eq!(lease_for(Duration::ZERO), Duration::from_secs(60), "zero");
1254        }
1255
1256        #[test]
1257        fn a_lease_of_the_longest_interval_does_not_overflow() {
1258            assert_eq!(lease_for(Duration::MAX), Duration::MAX, "saturates");
1259        }
1260
1261        #[test]
1262        fn a_sweep_goes_on_past_a_tenant_it_cannot_sweep() {
1263            let f = fixture();
1264            let damaged = f.tenants.create(Actor::Cli, "damaged", None).expect("made");
1265            let fine = f.tenants.create(Actor::Cli, "fine", None).expect("made");
1266            deleted(&f.tenants, damaged, "0199e5c6-0d7a-7c11-8000-000000000001");
1267            deleted(&f.tenants, fine, "0199e5c6-0d7a-7c11-8000-000000000002");
1268            f.tenants
1269                .conn_for_test()
1270                .execute(
1271                    "UPDATE tenant SET retention = '7w' WHERE id = ?1",
1272                    [damaged.0],
1273                )
1274                .expect("damaged");
1275            f.clock.set(datetime!(2026-10-25 13:00 UTC));
1276
1277            let report = sweep(&f.tenants, Retention::Days(1), &|| false);
1278
1279            assert_eq!(
1280                report,
1281                SweepReport {
1282                    purged: 1,
1283                    failed: 1
1284                }
1285            );
1286            assert_eq!(kept(&f.tenants, fine), 0);
1287            assert_eq!(kept(&f.tenants, damaged), 1, "left for a later sweep");
1288        }
1289
1290        #[tokio::test(start_paused = true)]
1291        async fn every_runs_at_start_then_after_each_interval_until_shutdown() {
1292            let runs = Arc::new(AtomicUsize::new(0));
1293            let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
1294            let counted = runs.clone();
1295            let task = tokio::spawn(every(
1296                Duration::from_secs(60),
1297                async move {
1298                    let _ = stopped.await;
1299                },
1300                move || {
1301                    counted.fetch_add(1, Ordering::SeqCst);
1302                    async {}
1303                },
1304            ));
1305            let settle = || async {
1306                for _ in 0..10 {
1307                    tokio::task::yield_now().await;
1308                }
1309            };
1310
1311            settle().await;
1312            assert_eq!(runs.load(Ordering::SeqCst), 1, "at start");
1313            tokio::time::advance(Duration::from_secs(59)).await;
1314            settle().await;
1315            assert_eq!(runs.load(Ordering::SeqCst), 1, "not before the interval");
1316            tokio::time::advance(Duration::from_secs(1)).await;
1317            settle().await;
1318            assert_eq!(runs.load(Ordering::SeqCst), 2, "after the interval");
1319
1320            stop.send(()).expect("still running");
1321            task.await.expect("ends on shutdown");
1322            tokio::time::advance(Duration::from_secs(600)).await;
1323            assert_eq!(runs.load(Ordering::SeqCst), 2, "none after shutdown");
1324        }
1325
1326        /// A run that is going when shutdown comes is awaited, so whoever
1327        /// awaits `every` waits for the run.
1328        #[tokio::test(start_paused = true)]
1329        async fn every_returns_only_after_a_run_going_at_shutdown_has_ended() {
1330            let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
1331            let (release, released) = tokio::sync::oneshot::channel::<()>();
1332            let released = Arc::new(tokio::sync::Mutex::new(Some(released)));
1333            let ended = Arc::new(AtomicUsize::new(0));
1334            let (held, done) = (released.clone(), ended.clone());
1335            let task = tokio::spawn(every(
1336                Duration::from_secs(60),
1337                async move {
1338                    let _ = stopped.await;
1339                },
1340                move || {
1341                    let (held, done) = (held.clone(), done.clone());
1342                    async move {
1343                        if let Some(released) = held.lock().await.take() {
1344                            let _ = released.await;
1345                        }
1346                        done.fetch_add(1, Ordering::SeqCst);
1347                    }
1348                },
1349            ));
1350            for _ in 0..10 {
1351                tokio::task::yield_now().await;
1352            }
1353            stop.send(()).expect("still running");
1354            for _ in 0..10 {
1355                tokio::task::yield_now().await;
1356            }
1357            assert!(
1358                !task.is_finished(),
1359                "every waits for the run going at shutdown"
1360            );
1361            release.send(()).expect("the run waits");
1362            task.await.expect("ends once the run has");
1363            assert_eq!(
1364                ended.load(Ordering::SeqCst),
1365                1,
1366                "the run ended, and no other began"
1367            );
1368        }
1369    }
1370}