1use chrono::{DateTime, Utc};
29use rustango::sql::Auto;
30use rustango::Model;
31use serde::{Deserialize, Serialize};
32use serde_json::json;
33
34#[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 #[rustango(max_length = 510, index, unique)]
56 pub from_path: String,
57
58 #[rustango(max_length = 1024)]
65 pub to_path: String,
66
67 #[rustango(default = "true")]
72 pub is_permanent: bool,
73
74 #[rustango(max_length = 255, default = "''")]
77 pub note: String,
78
79 #[rustango(default = "0")]
83 pub hit_count: i64,
84
85 #[rustango(default = "false")]
89 pub overrides_live: bool,
90
91 pub from_page_id: Option<i64>,
96
97 pub to_page_id: Option<i64>,
102
103 #[rustango(default = "true")]
107 pub is_active: bool,
108
109 #[rustango(max_length = 255, default = "''")]
112 pub disabled_reason: String,
113
114 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
126pub async fn ensure_columns(pool: &rustango::sql::Pool) -> Result<(), rustango::sql::ExecError> {
141 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 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
173async 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
202pub 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
222pub 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
241fn rules_key(tenant_slug: &str, kind: &str) -> String {
245 format!("cms:redirect:{tenant_slug}:{kind}")
246}
247
248pub 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
272pub 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#[must_use]
307pub fn is_wildcard(from_path: &str) -> bool {
308 from_path.contains('*')
309}
310
311#[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#[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#[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
363fn 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
389async 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
404pub 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 Redirect::objects()
419 .where_(Redirect::is_active.eq(true))
420 .where_(Redirect::from_path.contains("*"))
421 .fetch(pool)
422 .await
423}
424
425pub 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
454pub(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 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
489pub(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
515pub(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
568pub(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
583pub 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#[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
636pub 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
649const FLUSH_INTERVAL_SECS: i64 = 60;
665
666#[derive(Default)]
667struct HitAccum {
668 pending: std::collections::HashMap<(String, i64), (u64, i64)>,
670 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
682pub(crate) fn record_hit(pool: &rustango::sql::Pool, tenant_slug: &str, redirect_id: i64) {
687 if redirect_id == 0 {
688 return; }
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
716pub(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 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
771pub async fn flush_all(pools: &[(String, rustango::sql::Pool)]) {
779 for (slug, pool) in pools {
780 flush_tenant(pool, slug).await;
781 }
782}
783
784pub const STALE_AFTER_DAYS: i64 = 90;
792
793#[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#[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 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) .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 "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 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 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 r.last_hit_at = Some(now - chrono::Duration::days(1));
953 assert_eq!(staleness(&r, now), "active");
954 r.last_hit_at = Some(now - chrono::Duration::days(STALE_AFTER_DAYS + 5));
956 assert_eq!(staleness(&r, now), "stale");
957 r.last_hit_at = None;
959 assert_eq!(staleness(&r, now), "unused");
960 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 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 #[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 assert_eq!(rebase_path("/shop", "/", "/home").as_deref(), Some("/home/shop"));
1035 assert_eq!(rebase_path("/home/shop", "/home", "/").as_deref(), Some("/shop"));
1036 assert_eq!(rebase_path("/other", "/shop", "/store"), None);
1038 assert_eq!(rebase_path("/shopping", "/shop", "/store"), None);
1039 }
1040
1041 #[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()), (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 #[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 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 assert_eq!(resolve_destination(&pool, &rule).await, "/target");
1148 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 #[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 #[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 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"); }
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 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 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 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 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 #[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 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}