Skip to main content

rustango_cms/
redirect.rs

1//! Editor-managed 301/302 redirects.
2//!
3//! One row per redirect: `from_path` (the URL visitors hit) → `to_path`
4//! (the canonical destination). `is_permanent = true` emits `301 Moved
5//! Permanently`; `false` emits `302 Found`. The match is on the
6//! request path **including trailing-slash variance** — `/old` and
7//! `/old/` are distinct rows so admins can pick the right shape for
8//! their case.
9//!
10//! The public router consults the table whenever a slug lookup fails
11//! ([`crate::resolver::resolve_path`] returns `None`) — redirects hook
12//! into the 404 path.
13//! Live page URLs take precedence — a redirect from `/about` is
14//! ignored if a published page at `/about` exists.
15//!
16//! Per-request rendering uses [`rustango::redirects::build_redirect_response`]
17//! so the `Location` header preserves any query string the visitor
18//! arrived with (`/old?ref=ad → /new?ref=ad`).
19//!
20//! ## Migration
21//!
22//! Re-run `cargo run --example cms_demo -- makemigrations` after
23//! pulling this module so the framework generates the JSON file for
24//! `cms_redirect`. The Model derive registers the table via
25//! `inventory`; without the migration file the runtime DB schema
26//! stays unaware of the new table.
27
28use chrono::{DateTime, Utc};
29use rustango::sql::Auto;
30use rustango::Model;
31use serde::{Deserialize, Serialize};
32use serde_json::json;
33
34/// One redirect entry. Tenant-scoped — every row lives in the same
35/// per-tenant `cms_redirect` table as the rest of the CMS data.
36#[derive(Model, Debug, Clone, Serialize, Deserialize)]
37#[rustango(
38    table = "cms_redirect",
39    app = "cms",
40    display = "from_path",
41    admin(
42        list_display = "from_path, to_path, is_permanent, hit_count, updated_at",
43        search_fields = "from_path, to_path",
44        ordering = "from_path",
45        list_filter = "is_permanent",
46    )
47)]
48pub struct Redirect {
49    #[rustango(primary_key)]
50    pub id: Auto<i64>,
51
52    /// Incoming path with leading slash and no host (`/old-news`).
53    /// Indexed + unique so the resolver lookup is one query and so
54    /// admins can't accidentally create two rules for the same URL.
55    #[rustango(max_length = 510, index, unique)]
56    pub from_path: String,
57
58    /// Destination URL. Usually a same-host path (`/news`) but absolute
59    /// `https://...` URLs are accepted for cross-site moves; the
60    /// framework's [`build_redirect_response`] copies the value
61    /// verbatim into the `Location` header.
62    ///
63    /// [`build_redirect_response`]: rustango::redirects::build_redirect_response
64    #[rustango(max_length = 1024)]
65    pub to_path: String,
66
67    /// `true` → 301 Moved Permanently (canonical URL change; search
68    /// engines update their index). `false` → 302 Found (temporary
69    /// move). Default `true` — most editor-driven redirects are
70    /// canonical changes.
71    #[rustango(default = "true")]
72    pub is_permanent: bool,
73
74    /// Optional editor note for the admin list view ("renamed for
75    /// SEO", "old marketing campaign", …).
76    #[rustango(max_length = 255, default = "''")]
77    pub note: String,
78
79    /// Bumped every time the public router serves this redirect.
80    /// Useful for editors deciding which old URLs to keep around vs
81    /// retire. Best-effort — concurrent updates may lose a count.
82    #[rustango(default = "0")]
83    pub hit_count: i64,
84
85    /// Serve this rule even when a published page exists at
86    /// `from_path`. Default `false`: redirects normally fill in for
87    /// retired URLs only (live pages win).
88    #[rustango(default = "false")]
89    pub overrides_live: bool,
90
91    /// Source page whose `url_path` was snapshotted into
92    /// `from_path` at save time. Soft reference (no FK constraint —
93    /// the column is seed-added via [`ensure_columns`]); used to
94    /// auto-disable the rule when the page is deleted/unpublished.
95    pub from_page_id: Option<i64>,
96
97    /// Destination page. When set, the serve path resolves the
98    /// page's **current** `url_path` (follows moves/renames);
99    /// `to_path` holds the save-time snapshot
100    /// as display/fallback.
101    pub to_page_id: Option<i64>,
102
103    /// Disabled rules never serve. Flipped off automatically
104    /// (with [`Self::disabled_reason`]) when a linked page is deleted
105    /// or unpublished; re-enabled from the admin list.
106    #[rustango(default = "true")]
107    pub is_active: bool,
108
109    /// Why `is_active` was switched off ("Linked page … was
110    /// deleted"). Empty while active.
111    #[rustango(max_length = 255, default = "''")]
112    pub disabled_reason: String,
113
114    /// The most recent time this rule served a redirect. `None`
115    /// until the first hit flush. Drives the stale-redirect metric.
116    /// Written by the throttled hit-flush (`flush_tenant`) — never on
117    /// the request path.
118    pub last_hit_at: Option<DateTime<Utc>>,
119
120    #[rustango(auto_now_add)]
121    pub created_at: Auto<DateTime<Utc>>,
122    #[rustango(auto_now)]
123    pub updated_at: Auto<DateTime<Utc>>,
124}
125
126/// Add the page-link columns to a pre-existing `cms_redirect` table.
127/// Idempotent (duplicate-column errors are swallowed); called per
128/// tenant at boot from [`crate::seed::ensure_seeded`] — the same
129/// mechanism the seed-ensured tables use, since repo-wide
130/// `gen_migration` is blocked. Fresh databases get the whole table,
131/// these columns included, from the JSON migrations; this upgrades a
132/// table created before them.
133///
134/// No indexes on the page-id columns on purpose: `cms_redirect` is a
135/// small table and the only filtered reads are the (rare) disable
136/// sweeps.
137///
138/// # Errors
139/// Driver failures other than "column already exists".
140pub async fn ensure_columns(pool: &rustango::sql::Pool) -> Result<(), rustango::sql::ExecError> {
141    // #555 — nullable; no default (NULL = never hit). The type must be
142    // the one the model decodes `DateTime<Utc>` from (#745): a plain
143    // `TIMESTAMP` on Postgres is `timestamp without time zone`, which
144    // fails to decode once a hit writes a value; on MySQL it is
145    // whole-second with the 2038 ceiling.
146    let last_hit_at = match pool.dialect().name() {
147        "postgres" => "ALTER TABLE cms_redirect ADD COLUMN last_hit_at TIMESTAMPTZ",
148        "mysql" => "ALTER TABLE cms_redirect ADD COLUMN last_hit_at DATETIME(6) NULL",
149        _ => "ALTER TABLE cms_redirect ADD COLUMN last_hit_at TIMESTAMP",
150    };
151    let cols: &[&str] = &[
152        "ALTER TABLE cms_redirect ADD COLUMN overrides_live BOOLEAN NOT NULL DEFAULT FALSE",
153        "ALTER TABLE cms_redirect ADD COLUMN from_page_id BIGINT",
154        "ALTER TABLE cms_redirect ADD COLUMN to_page_id BIGINT",
155        "ALTER TABLE cms_redirect ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT TRUE",
156        "ALTER TABLE cms_redirect ADD COLUMN disabled_reason VARCHAR(255) NOT NULL DEFAULT ''",
157        last_hit_at,
158    ];
159    for stmt in cols {
160        if let Err(e) = rustango::sql::raw_execute_pool(pool, stmt, Vec::new()).await {
161            let msg = e.to_string().to_ascii_lowercase();
162            // sqlite: "duplicate column name"; mysql: "Duplicate column
163            // name"; postgres: "already exists".
164            if msg.contains("duplicate column") || msg.contains("already exists") {
165                continue;
166            }
167            return Err(e);
168        }
169    }
170    repair_pg_last_hit_at(pool).await
171}
172
173/// Databases upgraded by an older build got `last_hit_at` as
174/// `timestamp without time zone` on Postgres. Convert it in place (the
175/// values were written as UTC). A no-op once converted, and elsewhere.
176async fn repair_pg_last_hit_at(pool: &rustango::sql::Pool) -> Result<(), rustango::sql::ExecError> {
177    #[cfg(feature = "postgres")]
178    if let Some(pg) = pool.as_postgres() {
179        let data_type: Option<String> = rustango::sql::sqlx::query_scalar(
180            "SELECT data_type FROM information_schema.columns \
181             WHERE table_schema = current_schema() AND table_name = 'cms_redirect' \
182             AND column_name = 'last_hit_at'",
183        )
184        .fetch_optional(pg)
185        .await
186        .map_err(rustango::sql::ExecError::from)?;
187        if data_type.as_deref() == Some("timestamp without time zone") {
188            rustango::sql::raw_execute_pool(
189                pool,
190                "ALTER TABLE cms_redirect ALTER COLUMN last_hit_at TYPE TIMESTAMPTZ \
191                 USING last_hit_at AT TIME ZONE 'UTC'",
192                Vec::new(),
193            )
194            .await?;
195        }
196    }
197    #[cfg(not(feature = "postgres"))]
198    let _ = pool;
199    Ok(())
200}
201
202/// Look up a redirect for `path` in the current tenant. Returns
203/// `Ok(None)` when no row matches.
204///
205/// `path` should be the request URI's path component (no query
206/// string, no host). The lookup is exact-match — trailing-slash
207/// variance is intentional.
208pub async fn find_for_path(
209    pool: &rustango::sql::Pool,
210    path: &str,
211) -> Result<Option<Redirect>, rustango::sql::ExecError> {
212    use rustango::core::Column as _;
213    use rustango::sql::FetcherPool as _;
214    let rows: Vec<Redirect> = Redirect::objects()
215        .where_(Redirect::from_path.eq(path.to_owned()))
216        .where_(Redirect::is_active.eq(true))
217        .fetch(pool)
218        .await?;
219    Ok(rows.into_iter().next())
220}
221
222/// The active `overrides_live` rules for this tenant. Consulted by the
223/// public router BEFORE page resolution, so it must stay cheap: the
224/// set is tiny in practice (usually empty) and the cached variant
225/// below amortizes it to one query per TTL.
226///
227/// # Errors
228/// Driver / query failures.
229pub async fn override_rules(
230    pool: &rustango::sql::Pool,
231) -> Result<Vec<Redirect>, rustango::sql::ExecError> {
232    use rustango::core::Column as _;
233    use rustango::sql::FetcherPool as _;
234    Redirect::objects()
235        .where_(Redirect::overrides_live.eq(true))
236        .where_(Redirect::is_active.eq(true))
237        .fetch(pool)
238        .await
239}
240
241/// The cache key for one tenant's redirect rule set. Tenants on one host
242/// share the cache, so a fixed key served one tenant's rules — including
243/// override rules that hijack live pages — on every other host.
244fn rules_key(tenant_slug: &str, kind: &str) -> String {
245    format!("cms:redirect:{tenant_slug}:{kind}")
246}
247
248/// Cached variant of [`override_rules`] (mirrors
249/// [`crate::auto_menu::prefetch_cached`]): serves the rule set from
250/// `cache` under a per-tenant key, recomputing on miss. Cache failures
251/// degrade to a live query; query failures degrade to an empty set
252/// (the router then just resolves pages normally).
253pub async fn override_rules_cached(
254    tenant_slug: &str,
255    pool: &rustango::sql::Pool,
256    cache: &rustango::cache::BoxedCache,
257    ttl: Option<std::time::Duration>,
258) -> Vec<Redirect> {
259    let json = rustango::cache_fragment::cached_render(
260        cache.as_ref(),
261        &rules_key(tenant_slug, "overrides"),
262        ttl,
263        || async {
264            let rules = override_rules(pool).await.unwrap_or_default();
265            serde_json::to_string(&rules).unwrap_or_else(|_| "[]".to_owned())
266        },
267    )
268    .await;
269    serde_json::from_str(&json).unwrap_or_default()
270}
271
272/// Resolve the rule's destination at serve time: a `to_page_id` wins
273/// (the page's **current** `url_path`, so the rule follows moves and
274/// renames) with `to_path` as the fallback when the page is missing
275/// or not served — the resolver's rule, so an archived target is still
276/// followed.
277pub async fn resolve_destination(pool: &rustango::sql::Pool, r: &Redirect) -> String {
278    use rustango::core::Column as _;
279    if let Some(pid) = r.to_page_id {
280        let page = crate::page::Page::objects()
281            .where_(crate::page::Page::id.eq(pid))
282            .where_(crate::page::Page::status.is_in(crate::resolver::served_statuses()))
283            .first(pool)
284            .await
285            .ok()
286            .flatten()
287            .filter(|p| crate::resolver::visible_now(p, chrono::Utc::now()));
288        if let Some(p) = page {
289            return p.url_path;
290        }
291        tracing::warn!(
292            redirect_id = r.id.get().copied().unwrap_or_default(),
293            to_page_id = pid,
294            "redirect destination page missing/unpublished; using to_path fallback"
295        );
296    }
297    r.to_path.clone()
298}
299
300// ---------------------------------------------------------------------
301// #554 — wildcard rules (single `*` glob, prefix/suffix capture)
302// ---------------------------------------------------------------------
303
304/// A `from_path` is a wildcard PATTERN (vs an exact path) when it
305/// carries the single `*` glob.
306#[must_use]
307pub fn is_wildcard(from_path: &str) -> bool {
308    from_path.contains('*')
309}
310
311/// Match a wildcard `pattern` (exactly one `*`) against `path`.
312/// The pattern splits into a prefix + suffix around the star; a path
313/// matches when it starts with the prefix, ends with the suffix, and
314/// is long enough to leave a (possibly empty) capture between them.
315/// Returns the captured segment (`*`'s expansion) on a match.
316///
317/// `/old-blog/*` (prefix rule) → matches `/old-blog/a/b`, capture `a/b`.
318/// `*/feed` (suffix rule) → matches `/x/y/feed`, capture `/x/y`.
319#[must_use]
320pub fn match_wildcard(pattern: &str, path: &str) -> Option<String> {
321    let star = pattern.find('*')?;
322    let prefix = &pattern[..star];
323    let suffix = &pattern[star + 1..];
324    if path.len() < prefix.len() + suffix.len() {
325        return None;
326    }
327    if !path.starts_with(prefix) || !path.ends_with(suffix) {
328        return None;
329    }
330    Some(path[prefix.len()..path.len() - suffix.len()].to_owned())
331}
332
333/// Substitute a capture into a `to_path` template: its single `*` (if
334/// any) becomes `capture`; without a `*` the capture is dropped (the
335/// whole matched subtree funnels to one URL).
336#[must_use]
337pub fn apply_capture(to_path: &str, capture: &str) -> String {
338    match to_path.find('*') {
339        Some(star) => format!("{}{}{}", &to_path[..star], capture, &to_path[star + 1..]),
340        None => to_path.to_owned(),
341    }
342}
343
344/// Would a rule `from → to` send a visitor back into itself?
345///
346/// An exact rule loops when it targets its own path; a wildcard rule
347/// loops when its destination for a sample capture matches the pattern
348/// again (`/blog/* → /blog/archive/*`). Trailing slashes are ignored, as
349/// the resolver ignores them. An off-site `to` never loops here.
350#[must_use]
351pub fn redirect_loops(from: &str, to: &str) -> bool {
352    let norm = |p: &str| {
353        let t = p.trim().trim_end_matches('/');
354        if t.is_empty() { "/".to_owned() } else { t.to_owned() }
355    };
356    if !from.contains('*') {
357        return norm(from) == norm(to);
358    }
359    let dest = apply_capture(to, "x");
360    match_wildcard(from, &dest).is_some() || match_wildcard(from, &format!("{}/", norm(&dest))).is_some()
361}
362
363/// Most-specific wildcard rule matching `path` from a candidate set:
364/// the longest pre-`*` prefix wins (so `/docs/0.44/*` beats `/docs/*`);
365/// ties break to the lowest id for determinism. Returns the rule + its
366/// capture.
367fn best_wildcard_match<'a>(rules: &'a [Redirect], path: &str) -> Option<(&'a Redirect, String)> {
368    let mut best: Option<(&Redirect, String, usize, i64)> = None;
369    for r in rules {
370        if !is_wildcard(&r.from_path) {
371            continue;
372        }
373        let Some(cap) = match_wildcard(&r.from_path, path) else {
374            continue;
375        };
376        let prefix_len = r.from_path.find('*').unwrap_or(0);
377        let id = r.id.get().copied().unwrap_or(i64::MAX);
378        let take = match &best {
379            None => true,
380            Some((_, _, bp, bid)) => prefix_len > *bp || (prefix_len == *bp && id < *bid),
381        };
382        if take {
383            best = Some((r, cap, prefix_len, id));
384        }
385    }
386    best.map(|(r, cap, _, _)| (r, cap))
387}
388
389/// Build a rule's destination given an optional wildcard capture. A
390/// `to_page_id` (funnel-to-page) always resolves to the page's current
391/// URL and ignores the capture; otherwise the capture is substituted
392/// into `to_path`.
393async fn destination_for(
394    pool: &rustango::sql::Pool,
395    rule: &Redirect,
396    capture: Option<&str>,
397) -> String {
398    match (capture, rule.to_page_id) {
399        (Some(cap), None) => apply_capture(&rule.to_path, cap),
400        _ => resolve_destination(pool, rule).await,
401    }
402}
403
404/// The active wildcard (`from_path` contains `*`) rules for this
405/// tenant. Used on the exact-miss fallthrough.
406///
407/// # Errors
408/// Driver / query failures.
409pub async fn wildcard_rules(
410    pool: &rustango::sql::Pool,
411) -> Result<Vec<Redirect>, rustango::sql::ExecError> {
412    use rustango::core::Column as _;
413    use rustango::sql::FetcherPool as _;
414    // Filtered in SQL (#722): this runs on every 404 fall-through, and a
415    // migrated site can carry thousands of exact CSV-imported rules next
416    // to a handful of wildcards. `*` is not a LIKE metacharacter, and
417    // `contains` escapes the ones that are.
418    Redirect::objects()
419        .where_(Redirect::is_active.eq(true))
420        .where_(Redirect::from_path.contains("*"))
421        .fetch(pool)
422        .await
423}
424
425/// Cached variant of [`wildcard_rules`] — same short-TTL fragment
426/// cache as the override set, so tenants with no wildcard rules pay
427/// nothing per request.
428pub async fn wildcard_rules_cached(
429    tenant_slug: &str,
430    pool: &rustango::sql::Pool,
431    cache: &rustango::cache::BoxedCache,
432    ttl: Option<std::time::Duration>,
433) -> Vec<Redirect> {
434    let json = rustango::cache_fragment::cached_render(
435        cache.as_ref(),
436        &rules_key(tenant_slug, "wildcards"),
437        ttl,
438        || async {
439            let rules = wildcard_rules(pool).await.unwrap_or_default();
440            serde_json::to_string(&rules).unwrap_or_else(|_| "[]".to_owned())
441        },
442    )
443    .await;
444    serde_json::from_str(&json).unwrap_or_default()
445}
446
447fn build_response(to: String, permanent: bool, query: Option<&str>) -> axum::response::Response {
448    rustango::redirects::build_redirect_response(
449        &rustango::redirects::RedirectRule { to, permanent },
450        query,
451    )
452}
453
454/// Serve an `overrides_live` rule for `path` if one exists (exact match
455/// first, then most-specific wildcard). Called by the public router
456/// before page resolution; returns `None` on the (overwhelmingly
457/// common) no-rule path. Uses the router's fragment cache when
458/// available so cache-warm page views cost zero queries.
459pub(crate) async fn serve_override(
460    tenant: &rustango::extractors::Tenant,
461    cache: Option<(&rustango::cache::BoxedCache, std::time::Duration)>,
462    path: &str,
463    query: Option<&str>,
464) -> Option<axum::response::Response> {
465    let rules = match cache {
466        Some((c, ttl)) => override_rules_cached(&tenant.org.slug, tenant.pool(), c, Some(ttl)).await,
467        None => override_rules(tenant.pool()).await.unwrap_or_default(),
468    };
469    // Exact override beats a pattern override at the same path.
470    let (rule, capture): (Redirect, Option<String>) = if let Some(r) = rules
471        .iter()
472        .find(|r| !is_wildcard(&r.from_path) && r.from_path == path)
473    {
474        (r.clone(), None)
475    } else {
476        let (r, cap) = best_wildcard_match(&rules, path)?;
477        (r.clone(), Some(cap))
478    };
479    let to = destination_for(tenant.pool(), &rule, capture.as_deref()).await;
480    let resp = build_response(to, rule.is_permanent, query);
481    record_hit(
482        tenant.pool(),
483        &tenant.org.slug,
484        rule.id.get().copied().unwrap_or_default(),
485    );
486    Some(resp)
487}
488
489/// Serve a wildcard rule for `path` on the 404 fallthrough (no exact
490/// rule, no live page matched). Non-override wildcards behave like
491/// exact non-override rules — they only fill in for URLs with no live
492/// page. Returns the built response on a match.
493pub(crate) async fn serve_wildcard(
494    tenant: &rustango::extractors::Tenant,
495    cache: Option<(&rustango::cache::BoxedCache, std::time::Duration)>,
496    path: &str,
497    query: Option<&str>,
498) -> Option<axum::response::Response> {
499    let rules = match cache {
500        Some((c, ttl)) => wildcard_rules_cached(&tenant.org.slug, tenant.pool(), c, Some(ttl)).await,
501        None => wildcard_rules(tenant.pool()).await.unwrap_or_default(),
502    };
503    let (rule, capture) = best_wildcard_match(&rules, path)?;
504    let rule = rule.clone();
505    let to = destination_for(tenant.pool(), &rule, Some(&capture)).await;
506    let resp = build_response(to, rule.is_permanent, query);
507    record_hit(
508        tenant.pool(),
509        &tenant.org.slug,
510        rule.id.get().copied().unwrap_or_default(),
511    );
512    Some(resp)
513}
514
515/// After a rename (a slug change), keep every old address working: for
516/// each `(page_id, old_path, new_path)` a permanent rule from the old
517/// path to the page itself (`to_page_id`, so it keeps following later
518/// moves). A rule that already starts at the old path is re-pointed and
519/// re-enabled instead of duplicated. Runs in the rename's transaction.
520///
521/// The paths are the pages' `url_path`s — the public path on a
522/// single-site tenant (a hostname-mapped site strips its root prefix
523/// from public URLs, which these rules don't).
524///
525/// # Errors
526/// Driver / query failures.
527pub(crate) async fn record_renames_tx(
528    tx: &mut rustango::sql::PoolTx<'_>,
529    moves: &[(i64, String, String)],
530) -> Result<(), rustango::sql::ExecError> {
531    use rustango::core::Column as _;
532    use rustango::sql::FetcherTx as _;
533    for (page_id, old, new) in moves {
534        if old.is_empty() || old == new {
535            continue;
536        }
537        let existing = Redirect::objects()
538            .where_(Redirect::from_path.eq(old.clone()))
539            .fetch_tx(tx)
540            .await?
541            .into_iter()
542            .next();
543        let mut rule = existing.unwrap_or_else(|| Redirect {
544            id: Auto::Unset,
545            from_path: old.clone(),
546            to_path: String::new(),
547            is_permanent: true,
548            note: "Automatic: the page was renamed.".to_owned(),
549            hit_count: 0,
550            overrides_live: false,
551            from_page_id: None,
552            to_page_id: None,
553            is_active: true,
554            disabled_reason: String::new(),
555            last_hit_at: None,
556            created_at: Auto::Unset,
557            updated_at: Auto::Unset,
558        });
559        rule.to_path = new.clone();
560        rule.to_page_id = Some(*page_id);
561        rule.is_active = true;
562        rule.disabled_reason.clear();
563        rule.save_tx(tx).await?;
564    }
565    Ok(())
566}
567
568/// A descendant's address before its ancestor moved from `old_base` to
569/// `new_base`: its current `url` with the new base swapped for the old.
570pub(crate) fn rebase_path(url: &str, new_base: &str, old_base: &str) -> Option<String> {
571    let rest = if new_base == "/" {
572        url.strip_prefix('/')?
573    } else {
574        url.strip_prefix(new_base)?.strip_prefix('/')?
575    };
576    Some(if old_base == "/" {
577        format!("/{rest}")
578    } else {
579        format!("{}/{rest}", old_base.trim_end_matches('/'))
580    })
581}
582
583/// Disable every active rule that references `page_id` via
584/// `from_page_id` or `to_page_id`, recording `reason`. Called from the
585/// admin's page delete / unpublish paths so a rule never silently
586/// serves a dead source or points at a vanished destination. Returns
587/// how many rules were disabled.
588///
589/// # Errors
590/// Driver / query failures (the caller logs; the page action itself
591/// must not fail on redirect bookkeeping).
592pub async fn disable_for_page(
593    pool: &rustango::sql::Pool,
594    page_id: i64,
595    reason: &str,
596) -> Result<u64, rustango::sql::ExecError> {
597    use rustango::core::Column as _;
598    use rustango::sql::FetcherPool as _;
599    let mut rows: Vec<Redirect> = Redirect::objects()
600        .where_(Redirect::from_page_id.eq(Some(page_id)))
601        .where_(Redirect::is_active.eq(true))
602        .fetch(pool)
603        .await?;
604    let more: Vec<Redirect> = Redirect::objects()
605        .where_(Redirect::to_page_id.eq(Some(page_id)))
606        .where_(Redirect::is_active.eq(true))
607        .fetch(pool)
608        .await?;
609    let seen: std::collections::HashSet<i64> =
610        rows.iter().filter_map(|r| r.id.get().copied()).collect();
611    rows.extend(
612        more.into_iter()
613            .filter(|r| r.id.get().copied().map_or(true, |id| !seen.contains(&id))),
614    );
615    let mut disabled = 0u64;
616    for mut row in rows {
617        row.is_active = false;
618        row.disabled_reason = reason.chars().take(255).collect();
619        row.save(pool).await?;
620        disabled += 1;
621    }
622    Ok(disabled)
623}
624
625/// Convert a [`Redirect`] row into the framework's [`RedirectRule`](rustango::redirects::RedirectRule)
626/// shape so [`rustango::redirects::build_redirect_response`] can
627/// produce the 301/302.
628#[must_use]
629pub fn to_rule(r: &Redirect) -> rustango::redirects::RedirectRule {
630    rustango::redirects::RedirectRule {
631        to: r.to_path.clone(),
632        permanent: r.is_permanent,
633    }
634}
635
636/// Increment `hit_count` for a single redirect row. Failures are
637/// logged + swallowed — analytics counters shouldn't break the
638/// user-facing redirect.
639///
640/// Superseded on the request path by `record_hit` — kept for
641/// the public re-export and ad-hoc use.
642pub async fn bump_hit_count(pool: &rustango::sql::Pool, mut row: Redirect) {
643    row.hit_count = row.hit_count.saturating_add(1);
644    if let Err(e) = row.save(pool).await {
645        tracing::warn!(error = %e, "cms_redirect: failed to bump hit_count");
646    }
647}
648
649// ---------------------------------------------------------------------
650// #555 — hit telemetry without per-request DB writes
651// ---------------------------------------------------------------------
652//
653// Serving a redirect used to UPDATE the row per hit — a write on the
654// hot path that still answered no real question (no recency, no trend).
655// Instead we accumulate hits in a process-global map and flush the
656// deltas on a throttled, detached cadence, using the SERVING request's
657// own pool. The map is keyed by (tenant_slug, redirect_id), so each
658// tenant flushes its own deltas from its own traffic — no registry
659// access, no cross-tenant pools, no host wiring. A crash loses at most
660// one interval's counts (fine for a usage metric).
661
662/// Flush cadence — deltas older than this (per tenant) trigger a
663/// detached write on the next served redirect.
664const FLUSH_INTERVAL_SECS: i64 = 60;
665
666#[derive(Default)]
667struct HitAccum {
668    /// `(tenant_slug, redirect_id)` → `(pending_delta, last_hit_unix_secs)`.
669    pending: std::collections::HashMap<(String, i64), (u64, i64)>,
670    /// `tenant_slug` → last flush unix secs (throttle).
671    last_flush: std::collections::HashMap<String, i64>,
672}
673
674static HITS: std::sync::LazyLock<std::sync::Mutex<HitAccum>> =
675    std::sync::LazyLock::new(|| std::sync::Mutex::new(HitAccum::default()));
676
677fn lock_hits() -> std::sync::MutexGuard<'static, HitAccum> {
678    HITS.lock()
679        .unwrap_or_else(std::sync::PoisonError::into_inner)
680}
681
682/// Record a served-redirect hit — **zero DB I/O on the request path**
683/// (two map ops). When the tenant's throttle window has elapsed, spawn
684/// a detached flush that writes the accumulated deltas via the serving
685/// request's pool.
686pub(crate) fn record_hit(pool: &rustango::sql::Pool, tenant_slug: &str, redirect_id: i64) {
687    if redirect_id == 0 {
688        return; // unsaved row — nothing to attribute the hit to
689    }
690    let now = chrono::Utc::now().timestamp();
691    let due = {
692        let mut acc = lock_hits();
693        let e = acc
694            .pending
695            .entry((tenant_slug.to_owned(), redirect_id))
696            .or_insert((0, now));
697        e.0 = e.0.saturating_add(1);
698        e.1 = e.1.max(now);
699        let last = acc.last_flush.get(tenant_slug).copied().unwrap_or(0);
700        if now - last >= FLUSH_INTERVAL_SECS {
701            acc.last_flush.insert(tenant_slug.to_owned(), now);
702            true
703        } else {
704            false
705        }
706    };
707    if due {
708        let pool = pool.clone();
709        let slug = tenant_slug.to_owned();
710        rustango::__private_runtime::tokio::spawn(async move {
711            flush_tenant(&pool, &slug).await;
712        });
713    }
714}
715
716/// Drain one tenant's pending hit deltas and persist them with a
717/// targeted `UPDATE` — `hit_count += Δ` and `last_hit_at = greatest(…)`
718/// only, so the flush never bumps `updated_at` (which must stay the
719/// last *edit* time). Additive + idempotent-on-recency, so concurrent
720/// flushes from multiple processes can't double-count or regress the
721/// timestamp. Best-effort: a failed write drops that batch.
722pub(crate) async fn flush_tenant(pool: &rustango::sql::Pool, tenant_slug: &str) {
723    let drained: Vec<(i64, u64, i64)> = {
724        let mut acc = lock_hits();
725        let keys: Vec<(String, i64)> = acc
726            .pending
727            .keys()
728            .filter(|(s, _)| s == tenant_slug)
729            .cloned()
730            .collect();
731        keys.into_iter()
732            .filter_map(|k| acc.pending.remove(&k).map(|(d, ts)| (k.1, d, ts)))
733            .collect()
734    };
735    if drained.is_empty() {
736        return;
737    }
738    let dialect = pool.dialect();
739    let sqlite = dialect.name() == "sqlite";
740    let sql = format!(
741        "UPDATE cms_redirect SET hit_count = hit_count + {}, \
742         last_hit_at = CASE WHEN last_hit_at IS NULL OR last_hit_at < {} THEN {} ELSE last_hit_at END \
743         WHERE id = {}",
744        dialect.placeholder(1),
745        dialect.placeholder(2),
746        dialect.placeholder(3),
747        dialect.placeholder(4),
748    );
749    for (id, delta, ts) in drained {
750        let ts_dt = chrono::DateTime::from_timestamp(ts, 0).unwrap_or_else(chrono::Utc::now);
751        // SQLite stores auto timestamps as TEXT "YYYY-MM-DD HH:MM:SS";
752        // bind that shape so the lexical CASE comparison matches (same
753        // trick as analytics::retention).
754        let ts_bind = if sqlite {
755            rustango::core::SqlValue::String(ts_dt.format("%Y-%m-%d %H:%M:%S").to_string())
756        } else {
757            rustango::core::SqlValue::DateTime(ts_dt)
758        };
759        let binds = vec![
760            rustango::core::SqlValue::I64(delta as i64),
761            ts_bind.clone(),
762            ts_bind,
763            rustango::core::SqlValue::I64(id),
764        ];
765        if let Err(e) = rustango::sql::raw_execute_pool(pool, &sql, binds).await {
766            tracing::warn!(redirect_id = id, error = %e, "redirect hit flush failed");
767        }
768    }
769}
770
771/// Flush every tenant's pending deltas immediately (e.g. graceful
772/// shutdown). Best-effort. `pools` are the per-tenant pools to write
773/// through, matched to the accumulated slugs.
774///
775/// Most hosts don't need to call this — the throttled per-request
776/// flush keeps the map bounded — but it's available for a clean
777/// shutdown drain.
778pub async fn flush_all(pools: &[(String, rustango::sql::Pool)]) {
779    for (slug, pool) in pools {
780        flush_tenant(pool, slug).await;
781    }
782}
783
784// ---------------------------------------------------------------------
785// #555 — stale-redirect report
786// ---------------------------------------------------------------------
787
788/// A rule with no hit for this many days counts as **stale**; a rule
789/// never hit since (roughly) creation counts as **unused**. Editors
790/// use the report to prune rules nothing points at anymore.
791pub const STALE_AFTER_DAYS: i64 = 90;
792
793/// Classify a rule for the stale metric: `"disabled"` (auto-switched
794/// off), `"unused"` (never served), `"stale"` (no hit in
795/// [`STALE_AFTER_DAYS`]+), or `"active"`. Shared by the report and the
796/// admin list filter so both agree.
797#[must_use]
798pub(crate) fn staleness(r: &Redirect, now: DateTime<Utc>) -> &'static str {
799    let cutoff = now - chrono::Duration::days(STALE_AFTER_DAYS);
800    if !r.is_active {
801        "disabled"
802    } else if r.last_hit_at.is_none() {
803        "unused"
804    } else if r.last_hit_at.map_or(false, |t| t < cutoff) {
805        "stale"
806    } else {
807        "active"
808    }
809}
810
811/// Registry report surfacing which redirects are worth
812/// retiring: never-used, long-unused, or auto-disabled. Appears in the
813/// Reports nav automatically via [`crate::register_report!`].
814#[derive(Default)]
815pub struct StaleRedirectsReport;
816
817#[async_trait::async_trait]
818impl crate::admin::report::Report for StaleRedirectsReport {
819    fn slug(&self) -> &'static str {
820        "stale-redirects"
821    }
822    fn title(&self) -> &'static str {
823        "Stale redirects"
824    }
825    fn description(&self) -> Option<&'static str> {
826        Some("Redirects nothing has used recently — candidates to retire. 'unused' never served; 'stale' hasn't served in 90+ days; 'disabled' was switched off when a linked page was removed.")
827    }
828    fn icon(&self) -> Option<&'static str> {
829        Some("link_off")
830    }
831    fn columns(&self) -> Vec<crate::admin::report::ReportColumn> {
832        use crate::admin::report::ReportColumn;
833        vec![
834            ReportColumn::text("from", "From"),
835            ReportColumn::text("to", "To"),
836            ReportColumn::status("verdict", "Status"),
837            ReportColumn::number("hits", "Hits"),
838            ReportColumn::datetime("last_used", "Last used"),
839        ]
840    }
841    async fn rows(
842        &self,
843        pool: &rustango::sql::Pool,
844        _user_id: Option<i64>,
845    ) -> Vec<serde_json::Value> {
846        use rustango::sql::FetcherPool as _;
847        let now = chrono::Utc::now();
848        let mut rows: Vec<Redirect> = Redirect::objects().fetch(pool).await.unwrap_or_default();
849        // Rank: disabled, then unused, then stale, then active; within a
850        // rank, oldest last-used first (most worth reviewing at the top).
851        let rank = |v: &str| -> u8 {
852            match v {
853                "disabled" => 0,
854                "unused" => 1,
855                "stale" => 2,
856                _ => 3,
857            }
858        };
859        rows.sort_by(|a, b| {
860            rank(staleness(a, now))
861                .cmp(&rank(staleness(b, now)))
862                .then_with(|| a.last_hit_at.cmp(&b.last_hit_at))
863        });
864        rows.into_iter()
865            .filter(|r| rank(staleness(r, now)) < 3) // omit healthy "active" rows
866            .map(|r| {
867                let v = staleness(&r, now);
868                let id = r.id.get().copied().unwrap_or_default();
869                json!({
870                    "from": r.from_path,
871                    "to": r.to_path,
872                    // The status pill class comes from this value; reuse
873                    // the archived/scheduled/draft tokens the report table
874                    // already styles.
875                    "verdict": match v { "disabled" => "archived", "unused" => "draft", _ => "scheduled" },
876                    "hits": r.hit_count,
877                    "last_used": r.last_hit_at.map(|t| t.to_rfc3339()),
878                    "edit_url": format!("/cms-admin/redirects/{id}/edit"),
879                })
880            })
881            .collect()
882    }
883}
884
885crate::register_report!(StaleRedirectsReport);
886
887#[cfg(all(test, feature = "sqlite"))]
888mod tests {
889    use super::*;
890    #[test]
891    fn rule_sets_are_cached_per_tenant() {
892        // #681 — one tenant's override rules must never be served on another host.
893        assert_ne!(super::rules_key("acme", "overrides"), super::rules_key("globex", "overrides"));
894        assert_ne!(super::rules_key("acme", "overrides"), super::rules_key("acme", "wildcards"));
895    }
896
897    use rustango::core::Column as _;
898    use rustango::core::Model as _;
899    use rustango::sql::FetcherPool as _;
900    use rustango::sql::Pool;
901
902    async fn mem_pool() -> Pool {
903        let pool = Pool::connect("sqlite::memory:")
904            .await
905            .expect("in-memory sqlite");
906        // cms_page + its FK parents (needed by resolve_destination) and
907        // cms_redirect, straight from each model's SCHEMA.
908        for schema in [
909            &crate::page_type_model::PageType::SCHEMA,
910            &crate::media::Media::SCHEMA,
911            &crate::theme::Theme::SCHEMA,
912            &crate::page::Page::SCHEMA,
913            &Redirect::SCHEMA,
914        ] {
915            let ddl = rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect(
916                pool.dialect(),
917                schema,
918            );
919            for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
920                rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
921                    .await
922                    .expect("ddl");
923            }
924        }
925        pool
926    }
927
928    fn mk_redirect(from: &str, to: &str) -> Redirect {
929        Redirect {
930            id: Auto::Unset,
931            from_path: from.to_owned(),
932            to_path: to.to_owned(),
933            is_permanent: true,
934            note: String::new(),
935            hit_count: 0,
936            overrides_live: false,
937            from_page_id: None,
938            to_page_id: None,
939            is_active: true,
940            disabled_reason: String::new(),
941            last_hit_at: None,
942            created_at: Auto::Unset,
943            updated_at: Auto::Unset,
944        }
945    }
946
947    #[test]
948    fn staleness_classifies_all_four_verdicts() {
949        let now = chrono::Utc::now();
950        let mut r = mk_redirect("/a", "/b");
951        // Recently served → active.
952        r.last_hit_at = Some(now - chrono::Duration::days(1));
953        assert_eq!(staleness(&r, now), "active");
954        // No hit inside the window → stale.
955        r.last_hit_at = Some(now - chrono::Duration::days(STALE_AFTER_DAYS + 5));
956        assert_eq!(staleness(&r, now), "stale");
957        // Never served → unused.
958        r.last_hit_at = None;
959        assert_eq!(staleness(&r, now), "unused");
960        // Disabled beats any hit history.
961        r.is_active = false;
962        r.last_hit_at = Some(now);
963        assert_eq!(staleness(&r, now), "disabled");
964    }
965
966    async fn mk_page(pool: &Pool, slug: &str, status: &str) -> i64 {
967        let mut page = crate::page::Page {
968            id: Auto::Unset,
969            page_type_id: 1,
970            title: format!("Page {slug}"),
971            slug: slug.to_owned(),
972            path: format!("0001{slug}/"),
973            url_path: format!("/{slug}"),
974            preview_path: String::new(),
975            template_override: String::new(),
976            depth: 1,
977            parent_id: None,
978            locale_variant_of: None,
979            alias_of: None,
980            theme_id: None,
981            sort_order: 0,
982            status: status.to_owned(),
983            published_at: None,
984            last_published_at: None,
985            go_live_at: None,
986            expire_at: None,
987            seo_title: String::new(),
988            seo_description: String::new(),
989            robots_index: true,
990            sitemap_priority: 0.5,
991            show_in_menus: false,
992            og_title: String::new(),
993            og_description: String::new(),
994            og_image_media_id: None,
995            twitter_card: "summary_large_image".to_owned(),
996            notification_pre_published_sent: false,
997            created_at: Auto::Unset,
998            updated_at: Auto::Unset,
999        };
1000        // Satisfy the page_type FK.
1001        let existing = crate::page_type_model::PageType::objects()
1002            .fetch(pool)
1003            .await
1004            .expect("pt fetch");
1005        if existing.is_empty() {
1006            let mut pt = crate::page_type_model::PageType {
1007                id: Auto::Unset,
1008                app_label: "cms".to_owned(),
1009                type_name: "TestPage".to_owned(),
1010                verbose_name: "Test page".to_owned(),
1011                default_template: "page.html".to_owned(),
1012                view_mode: "auto".to_owned(),
1013                is_creatable: true,
1014                allowed_parent_types: serde_json::json!([]),
1015                allowed_child_types: serde_json::json!([]),
1016                workflow: String::new(),
1017                created_at: Auto::Unset,
1018                updated_at: Auto::Unset,
1019            };
1020            pt.insert(pool).await.expect("insert page type");
1021        }
1022        page.insert(pool).await.expect("insert page");
1023        page.id.get().copied().expect("page id")
1024    }
1025
1026    /// `ensure_columns` must no-op on a table that already has the
1027    /// page-link columns (fresh SCHEMA) — the duplicate-column error paths
1028    /// are swallowed on every dialect message shape.
1029    #[test]
1030    fn rebase_path_swaps_the_moved_base() {
1031        assert_eq!(rebase_path("/shop/moon-jar", "/shop", "/store").as_deref(), Some("/store/moon-jar"));
1032        assert_eq!(rebase_path("/a/b/c", "/a/b", "/x").as_deref(), Some("/x/c"));
1033        // A home page (base "/") renamed into a slug, and back.
1034        assert_eq!(rebase_path("/shop", "/", "/home").as_deref(), Some("/home/shop"));
1035        assert_eq!(rebase_path("/home/shop", "/home", "/").as_deref(), Some("/shop"));
1036        // Not under the new base, or a sibling that merely shares a prefix.
1037        assert_eq!(rebase_path("/other", "/shop", "/store"), None);
1038        assert_eq!(rebase_path("/shopping", "/shop", "/store"), None);
1039    }
1040
1041    /// A rename leaves a rule that follows the page; a second rename of
1042    /// the same old address re-points that rule instead of duplicating it.
1043    #[tokio::test]
1044    async fn renames_leave_rules_that_follow_the_page() {
1045        let pool = mem_pool().await;
1046        let mut stale = mk_redirect("/old-jar", "/nowhere");
1047        stale.is_active = false;
1048        stale.disabled_reason = "Linked page was unpublished".to_owned();
1049        stale.save(&pool).await.expect("stale rule");
1050
1051        let moves = vec![
1052            (7, "/old-jar".to_owned(), "/shop/jar".to_owned()),
1053            (8, "/shop/vase".to_owned(), "/shop/vase".to_owned()), // unchanged: skipped
1054            (9, "/shop/bowl".to_owned(), "/store/bowl".to_owned()),
1055        ];
1056        let mut tx = rustango::sql::transaction_pool(&pool).await.expect("tx");
1057        record_renames_tx(&mut tx, &moves).await.expect("record");
1058        tx.commit().await.expect("commit");
1059
1060        let rules: Vec<Redirect> = Redirect::objects().fetch(&pool).await.expect("rules");
1061        assert_eq!(rules.len(), 2, "one per moved address, the stale one reused: {rules:?}");
1062        let jar = rules.iter().find(|r| r.from_path == "/old-jar").expect("re-pointed");
1063        assert_eq!((jar.to_path.as_str(), jar.to_page_id, jar.is_active), ("/shop/jar", Some(7), true));
1064        assert!(jar.disabled_reason.is_empty());
1065        let bowl = rules.iter().find(|r| r.from_path == "/shop/bowl").expect("created");
1066        assert_eq!((bowl.to_page_id, bowl.is_permanent), (Some(9), true));
1067    }
1068
1069    #[tokio::test]
1070    async fn ensure_columns_is_idempotent() {
1071        let pool = mem_pool().await;
1072        ensure_columns(&pool).await.expect("first ensure");
1073        ensure_columns(&pool).await.expect("second ensure");
1074    }
1075
1076    /// `ensure_columns` upgrades an older table shape in place.
1077    #[tokio::test]
1078    async fn ensure_columns_upgrades_old_table() {
1079        let pool = Pool::connect("sqlite::memory:").await.expect("pool");
1080        rustango::sql::raw_execute_pool(
1081            &pool,
1082            "CREATE TABLE cms_redirect (
1083                id INTEGER PRIMARY KEY AUTOINCREMENT,
1084                from_path VARCHAR(510) NOT NULL UNIQUE,
1085                to_path VARCHAR(1024) NOT NULL,
1086                is_permanent BOOLEAN NOT NULL DEFAULT TRUE,
1087                note VARCHAR(255) NOT NULL DEFAULT '',
1088                hit_count BIGINT NOT NULL DEFAULT 0,
1089                created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
1090                updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
1091            )",
1092            Vec::new(),
1093        )
1094        .await
1095        .expect("old-shape table");
1096        ensure_columns(&pool).await.expect("upgrade");
1097        // Full-model round-trip decodes the new columns with defaults.
1098        let mut row = mk_redirect("/old", "/new");
1099        row.insert(&pool).await.expect("insert");
1100        let got = find_for_path(&pool, "/old").await.expect("query");
1101        let got = got.expect("row found");
1102        assert!(got.is_active);
1103        assert!(!got.overrides_live);
1104        assert_eq!(got.disabled_reason, "");
1105    }
1106
1107    #[tokio::test]
1108    async fn find_for_path_skips_disabled_rules() {
1109        let pool = mem_pool().await;
1110        let mut row = mk_redirect("/dead", "/alive");
1111        row.is_active = false;
1112        row.disabled_reason = "Linked page was deleted".to_owned();
1113        row.insert(&pool).await.expect("insert");
1114        assert!(
1115            find_for_path(&pool, "/dead")
1116                .await
1117                .expect("query")
1118                .is_none(),
1119            "disabled rules must never serve"
1120        );
1121    }
1122
1123    #[tokio::test]
1124    async fn override_rules_returns_only_active_overrides() {
1125        let pool = mem_pool().await;
1126        let mut normal = mk_redirect("/a", "/b");
1127        normal.insert(&pool).await.expect("insert normal");
1128        let mut over = mk_redirect("/live", "/elsewhere");
1129        over.overrides_live = true;
1130        over.insert(&pool).await.expect("insert override");
1131        let mut dead_over = mk_redirect("/live2", "/elsewhere2");
1132        dead_over.overrides_live = true;
1133        dead_over.is_active = false;
1134        dead_over.insert(&pool).await.expect("insert dead");
1135        let rules = override_rules(&pool).await.expect("query");
1136        assert_eq!(rules.len(), 1);
1137        assert_eq!(rules[0].from_path, "/live");
1138    }
1139
1140    #[tokio::test]
1141    async fn resolve_destination_follows_current_page_url() {
1142        let pool = mem_pool().await;
1143        let pid = mk_page(&pool, "target", "published").await;
1144        let mut rule = mk_redirect("/old", "/stale-snapshot");
1145        rule.to_page_id = Some(pid);
1146        // Destination follows the page's CURRENT url_path…
1147        assert_eq!(resolve_destination(&pool, &rule).await, "/target");
1148        // …including after a move/rename.
1149        let mut page = crate::page::Page::objects()
1150            .where_(crate::page::Page::id.eq(pid))
1151            .first(&pool)
1152            .await
1153            .expect("q")
1154            .expect("page");
1155        page.url_path = "/moved/target".to_owned();
1156        page.save(&pool).await.expect("save");
1157        assert_eq!(resolve_destination(&pool, &rule).await, "/moved/target");
1158    }
1159
1160    /// An archived page is still served, so a rule targeting it
1161    /// keeps following it instead of falling back to a stale path.
1162    #[tokio::test]
1163    async fn resolve_destination_follows_an_archived_page() {
1164        let pool = mem_pool().await;
1165        let pid = mk_page(&pool, "kept", "archived").await;
1166        let mut rule = mk_redirect("/old", "/stale-snapshot");
1167        rule.to_page_id = Some(pid);
1168        assert_eq!(resolve_destination(&pool, &rule).await, "/kept");
1169    }
1170
1171    #[tokio::test]
1172    async fn resolve_destination_falls_back_when_page_unpublished() {
1173        let pool = mem_pool().await;
1174        let pid = mk_page(&pool, "gone", "draft").await;
1175        let mut rule = mk_redirect("/old", "/fallback");
1176        rule.to_page_id = Some(pid);
1177        assert_eq!(
1178            resolve_destination(&pool, &rule).await,
1179            "/fallback",
1180            "unpublished target page must fall back to to_path"
1181        );
1182    }
1183
1184    // ---- #554 wildcard matcher (pure) ----
1185
1186    #[test]
1187    fn wildcard_prefix_match_and_capture() {
1188        assert_eq!(
1189            match_wildcard("/old-blog/*", "/old-blog/2024/hi").as_deref(),
1190            Some("2024/hi")
1191        );
1192        assert_eq!(
1193            match_wildcard("/old-blog/*", "/old-blog/").as_deref(),
1194            Some("")
1195        );
1196        // strict: no remainder / different prefix → no match
1197        assert_eq!(match_wildcard("/old-blog/*", "/old-blog"), None);
1198        assert_eq!(match_wildcard("/old-blog/*", "/other/x"), None);
1199    }
1200
1201    #[test]
1202    fn wildcard_suffix_match_and_capture() {
1203        assert_eq!(
1204            match_wildcard("*/feed", "/blog/feed").as_deref(),
1205            Some("/blog")
1206        );
1207        assert_eq!(
1208            match_wildcard("*/feed", "/a/b/feed").as_deref(),
1209            Some("/a/b")
1210        );
1211        assert_eq!(match_wildcard("*/feed", "/feedx"), None);
1212    }
1213
1214    #[test]
1215    fn loops_are_detected_and_ordinary_rules_are_not() {
1216        assert!(redirect_loops("/a", "/a"));
1217        assert!(redirect_loops("/a/", "/a"));
1218        assert!(redirect_loops("/blog/*", "/blog/archive/*"));
1219        assert!(redirect_loops("/blog/*", "/blog/"));
1220        assert!(redirect_loops("*/feed", "/new/*/feed"));
1221        assert!(!redirect_loops("/a", "/b"));
1222        assert!(!redirect_loops("/old-blog/*", "/blog/*"));
1223        assert!(!redirect_loops("/blog/*", "https://example.test/blog/*"));
1224        assert!(!redirect_loops("*/feed", "*/rss"));
1225    }
1226
1227    #[test]
1228    fn apply_capture_substitutes_or_drops() {
1229        assert_eq!(apply_capture("/blog/*", "2024/hi"), "/blog/2024/hi");
1230        assert_eq!(apply_capture("/archive", "2024/hi"), "/archive"); // no star → drop
1231    }
1232
1233    #[test]
1234    fn best_wildcard_match_prefers_longest_prefix_then_lowest_id() {
1235        let mut broad = mk_redirect("/docs/*", "/d/*");
1236        broad.id = Auto::Set(2);
1237        let mut specific = mk_redirect("/docs/0.44/*", "/d44/*");
1238        specific.id = Auto::Set(5);
1239        let rules = vec![broad, specific];
1240        let (r, cap) = best_wildcard_match(&rules, "/docs/0.44/intro").expect("match");
1241        assert_eq!(r.from_path, "/docs/0.44/*");
1242        assert_eq!(cap, "intro");
1243        // A path only the broad rule covers falls to the broad rule.
1244        let (r2, cap2) = best_wildcard_match(&rules, "/docs/other").expect("match");
1245        assert_eq!(r2.from_path, "/docs/*");
1246        assert_eq!(cap2, "other");
1247    }
1248
1249    #[tokio::test]
1250    async fn wildcard_rules_query_returns_only_active_patterns() {
1251        let pool = mem_pool().await;
1252        mk_redirect("/exact", "/x")
1253            .insert(&pool)
1254            .await
1255            .expect("exact");
1256        mk_redirect("/glob/*", "/g/*")
1257            .insert(&pool)
1258            .await
1259            .expect("glob");
1260        let mut dead = mk_redirect("/dead/*", "/d/*");
1261        dead.is_active = false;
1262        dead.insert(&pool).await.expect("dead");
1263        let rules = wildcard_rules(&pool).await.expect("query");
1264        assert_eq!(rules.len(), 1, "only the active pattern");
1265        assert_eq!(rules[0].from_path, "/glob/*");
1266    }
1267
1268    #[tokio::test]
1269    async fn disable_for_page_hits_both_link_columns_and_records_reason() {
1270        let pool = mem_pool().await;
1271        let mut from_linked = mk_redirect("/f", "/x");
1272        from_linked.from_page_id = Some(7);
1273        from_linked.insert(&pool).await.expect("i1");
1274        let mut to_linked = mk_redirect("/t", "/y");
1275        to_linked.to_page_id = Some(7);
1276        to_linked.insert(&pool).await.expect("i2");
1277        let mut unrelated = mk_redirect("/u", "/z");
1278        unrelated.from_page_id = Some(8);
1279        unrelated.insert(&pool).await.expect("i3");
1280
1281        let n = disable_for_page(&pool, 7, "Linked page “X” was deleted")
1282            .await
1283            .expect("disable");
1284        assert_eq!(n, 2, "both linked rules disabled, unrelated untouched");
1285        assert!(find_for_path(&pool, "/f").await.expect("q").is_none());
1286        assert!(find_for_path(&pool, "/t").await.expect("q").is_none());
1287        assert!(find_for_path(&pool, "/u").await.expect("q").is_some());
1288        // Reason recorded; second sweep is a no-op.
1289        let rows: Vec<Redirect> = Redirect::objects()
1290            .where_(Redirect::from_path.eq("/f".to_owned()))
1291            .fetch(&pool)
1292            .await
1293            .expect("fetch");
1294        assert_eq!(rows[0].disabled_reason, "Linked page “X” was deleted");
1295        let again = disable_for_page(&pool, 7, "x").await.expect("again");
1296        assert_eq!(again, 0);
1297    }
1298
1299    #[tokio::test]
1300    async fn flush_tenant_applies_deltas_additively_and_sets_last_hit() {
1301        let pool = mem_pool().await;
1302        let mut r = mk_redirect("/flush", "/dest");
1303        r.insert(&pool).await.expect("insert");
1304        let id = Redirect::objects()
1305            .where_(Redirect::from_path.eq("/flush".to_owned()))
1306            .fetch(&pool)
1307            .await
1308            .expect("fetch")[0]
1309            .id
1310            .get()
1311            .copied()
1312            .expect("id");
1313
1314        // Prime the accumulator directly under a unique slug — avoids the
1315        // throttled detached spawn inside record_hit racing this test.
1316        let ts = chrono::Utc::now().timestamp();
1317        {
1318            let mut acc = lock_hits();
1319            acc.pending
1320                .insert(("flushtest_555".to_owned(), id), (3, ts));
1321        }
1322        flush_tenant(&pool, "flushtest_555").await;
1323
1324        let row = Redirect::objects()
1325            .where_(Redirect::id.eq(id))
1326            .fetch(&pool)
1327            .await
1328            .expect("refetch")
1329            .remove(0);
1330        assert_eq!(row.hit_count, 3, "delta applied");
1331        assert!(row.last_hit_at.is_some(), "last_hit_at stamped");
1332
1333        // Draining is idempotent: a second flush over an empty queue is a
1334        // no-op — no double counting.
1335        flush_tenant(&pool, "flushtest_555").await;
1336        let row2 = Redirect::objects()
1337            .where_(Redirect::id.eq(id))
1338            .fetch(&pool)
1339            .await
1340            .expect("refetch2")
1341            .remove(0);
1342        assert_eq!(row2.hit_count, 3, "no double count on empty flush");
1343    }
1344}
1345
1346#[cfg(all(test, feature = "postgres"))]
1347mod pg_tests {
1348    use rustango::sql::sqlx;
1349
1350    /// An upgraded Postgres table gets `last_hit_at` as a type the
1351    /// model decodes, and one added as plain `TIMESTAMP` by an older
1352    /// build is converted. Runs with `--ignored` against
1353    /// `RCMS_TEST_PG_URL`, in a schema of its own.
1354    #[tokio::test]
1355    #[ignore = "needs RCMS_TEST_PG_URL"]
1356    async fn last_hit_at_is_timestamptz_after_ensure() {
1357        let url = std::env::var("RCMS_TEST_PG_URL")
1358            .expect("set RCMS_TEST_PG_URL to a throwaway Postgres database to run this");
1359        let schema = format!("rcms_test_redirect_{}", std::process::id());
1360        let admin = sqlx::PgPool::connect(&url).await.expect("connect");
1361        sqlx::query(&format!("CREATE SCHEMA {schema}")).execute(&admin).await.expect("schema");
1362        let sep = if url.contains('?') { '&' } else { '?' };
1363        let pool = rustango::sql::Pool::connect(&format!(
1364            "{url}{sep}options=-c%20search_path%3D{schema}"
1365        ))
1366        .await
1367        .expect("scoped");
1368        let pg = pool.as_postgres().expect("pg");
1369        // The pre-#555 table, plus the column exactly as the old
1370        // ensure_columns added it.
1371        sqlx::query(
1372            "CREATE TABLE cms_redirect (id BIGSERIAL PRIMARY KEY, \
1373             from_path VARCHAR(510) NOT NULL UNIQUE, to_path VARCHAR(1024) NOT NULL, \
1374             is_permanent BOOLEAN NOT NULL DEFAULT TRUE, note VARCHAR(255) NOT NULL DEFAULT '', \
1375             hit_count BIGINT NOT NULL DEFAULT 0, last_hit_at TIMESTAMP, \
1376             created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now())",
1377        )
1378        .execute(pg)
1379        .await
1380        .expect("old table");
1381        sqlx::query("INSERT INTO cms_redirect (from_path, to_path, last_hit_at) VALUES ('/a', '/b', '2026-01-02 03:04:05')")
1382            .execute(pg)
1383            .await
1384            .expect("hit row");
1385
1386        super::ensure_columns(&pool).await.expect("ensure");
1387        super::ensure_columns(&pool).await.expect("idempotent");
1388
1389        let data_type: String = sqlx::query_scalar(
1390            "SELECT data_type FROM information_schema.columns WHERE table_schema = $1 \
1391             AND table_name = 'cms_redirect' AND column_name = 'last_hit_at'",
1392        )
1393        .bind(&schema)
1394        .fetch_one(pg)
1395        .await
1396        .expect("type");
1397        let found = super::find_for_path(&pool, "/a").await;
1398        sqlx::query(&format!("DROP SCHEMA {schema} CASCADE")).execute(&admin).await.expect("drop");
1399
1400        assert_eq!(data_type, "timestamp with time zone");
1401        let row = found.expect("a hit row decodes").expect("row");
1402        assert_eq!(row.last_hit_at.map(|t| t.to_rfc3339()).as_deref(), Some("2026-01-02T03:04:05+00:00"));
1403    }
1404}