Skip to main content

rustango_cms/
schedule.rs

1//! Background driver for scheduled publishing and expiry.
2//!
3//! [`crate::page::run_schedule_sweep`] flips `scheduled` pages live and
4//! takes expired ones down, but nothing ran it except an editor opening
5//! the admin page list — on a quiet site a page could sit past its go-live
6//! time indefinitely. [`spawn_schedule_sweeper`] runs it on a timer for
7//! every active tenant.
8//!
9//! The public resolver no longer depends on this to decide visibility —
10//! it checks the dates itself ([`crate::resolver::visible_now`]). The
11//! sweeper persists the status change and purges the page cache, so
12//! listings, feeds and cached pages catch up too.
13
14use std::sync::Arc;
15use std::time::Duration;
16
17use rustango::sql::sqlx;
18use rustango::tenancy::{Org, TenantPools};
19
20use crate::cache_invalidate::PageCacheInvalidator;
21
22/// Run the schedule sweep for every active tenant every `interval`.
23///
24/// Call it once at boot with the registry pool — the same pool the
25/// `Cli::seed` hook receives — and the host's page-cache invalidator
26/// (`cache_invalidate::noop()` when the host has no page cache). A tenant
27/// whose sweep fails is logged and retried next tick; it never stops the
28/// others. Returns immediately; the loop runs on the Tokio runtime.
29pub fn spawn_schedule_sweeper(
30    registry: &rustango::sql::Pool,
31    interval: Duration,
32    invalidator: Arc<dyn PageCacheInvalidator>,
33) {
34    let registry = registry.clone();
35    rustango::__private_runtime::tokio::spawn(async move {
36        let mut tick = rustango::__private_runtime::tokio::time::interval(interval);
37        loop {
38            tick.tick().await;
39            sweep_all(&registry, &invalidator).await;
40        }
41    });
42}
43
44/// One pass over every active tenant.
45async fn sweep_all(registry: &rustango::sql::Pool, invalidator: &Arc<dyn PageCacheInvalidator>) {
46    match registry {
47        #[cfg(feature = "postgres")]
48        rustango::sql::Pool::Postgres(pg) => {
49            sweep_orgs(TenantPools::<sqlx::Postgres>::new(pg.clone()), invalidator).await;
50        }
51        #[cfg(feature = "sqlite")]
52        rustango::sql::Pool::Sqlite(sq) => {
53            sweep_orgs(TenantPools::<sqlx::Sqlite>::new(sq.clone()), invalidator).await;
54        }
55        #[cfg(feature = "mysql")]
56        rustango::sql::Pool::Mysql(my) => {
57            sweep_orgs(TenantPools::<sqlx::MySql>::new(my.clone()), invalidator).await;
58        }
59    }
60}
61
62async fn sweep_orgs<DB>(pools: TenantPools<DB>, invalidator: &Arc<dyn PageCacheInvalidator>)
63where
64    DB: sqlx::Database,
65    rustango::sql::Pool: From<sqlx::Pool<DB>>,
66{
67    use rustango::sql::FetcherPool as _;
68    let orgs: Vec<Org> = match Org::objects().fetch(&pools.registry_pool()).await {
69        Ok(o) => o,
70        Err(e) => {
71            tracing::warn!(target: "rustango_cms::schedule", error = %e, "could not list tenants");
72            return;
73        }
74    };
75    for org in orgs.into_iter().filter(|o| o.active) {
76        let pool = match pools.scoped_pool_dyn(&org).await {
77            Ok(p) => p,
78            Err(e) => {
79                tracing::warn!(target: "rustango_cms::schedule", tenant = %org.slug, error = %e, "no pool");
80                continue;
81            }
82        };
83        // Registry orgs always carry an id; one without cannot be keyed.
84        let Some(tenant) = rustango::tenancy::TenantSlug::of(&org) else { continue };
85        match crate::page::run_schedule_sweep_and_purge(&pool, &tenant, Arc::clone(invalidator)).await {
86            Ok(r) if r.published + r.expired > 0 => tracing::info!(
87                target: "rustango_cms::schedule",
88                tenant = %org.slug, published = r.published, expired = r.expired,
89                "schedule sweep"
90            ),
91            Ok(_) => {}
92            Err(e) => {
93                tracing::warn!(target: "rustango_cms::schedule", tenant = %org.slug, error = %e, "sweep failed");
94            }
95        }
96    }
97}