1use chrono::{DateTime, Utc};
7use rustango::sql::Auto;
8use rustango::Model;
9use serde::{Deserialize, Serialize};
10
11#[derive(Model, Debug, Clone, Serialize, Deserialize)]
14#[rustango(
15 table = "cms_revision",
16 app = "cms",
17 admin(
18 list_display = "page_id, sequence, created_by, created_at",
19 ordering = "-created_at",
20 list_filter = "page_id",
21 )
22)]
23pub struct Revision {
24 #[rustango(primary_key)]
25 pub id: Auto<i64>,
26
27 #[rustango(fk = "cms_page", on = "id", index)]
30 pub page_id: i64,
31
32 pub sequence: i32,
36
37 pub snapshot: serde_json::Value,
40
41 pub created_by: Option<i64>,
44
45 #[rustango(auto_now_add)]
46 pub created_at: Auto<DateTime<Utc>>,
47}
48
49impl Revision {
50 #[must_use]
53 pub fn label(&self) -> String {
54 let when = self
55 .created_at
56 .get()
57 .map(|t| t.format("%Y-%m-%d %H:%M UTC").to_string())
58 .unwrap_or_default();
59 format!("#{} · {}", self.sequence, when)
60 }
61}
62
63pub async fn capture(
73 pool: &rustango::sql::Pool,
74 page: &crate::page::Page,
75 created_by: Option<i64>,
76) -> Result<Revision, rustango::sql::ExecError> {
77 use rustango::core::Column as _;
78 use rustango::sql::{sqlx, Auto};
79
80 const ATTEMPTS: usize = 10;
82 let page_id = page.id.get().copied().unwrap_or_default();
83 let snapshot = serde_json::to_value(page)
84 .map_err(|e| rustango::sql::ExecError::Driver(sqlx::Error::Decode(Box::new(e))))?;
85
86 let mut attempt = 0;
87 loop {
88 attempt += 1;
89 let latest: Option<Revision> = Revision::objects()
91 .where_(Revision::page_id.eq(page_id))
92 .order_by(&[("sequence", true)])
93 .first(pool)
94 .await?;
95 let mut row = Revision {
96 id: Auto::Unset,
97 page_id,
98 sequence: latest.map_or(1, |r| r.sequence + 1),
99 snapshot: snapshot.clone(),
100 created_by,
101 created_at: Auto::Unset,
102 };
103 match row.insert_pool(pool).await {
104 Ok(()) => return Ok(row),
105 Err(e) if attempt < ATTEMPTS && is_unique_violation(&e) => continue,
106 Err(e) => return Err(e),
107 }
108 }
109}
110
111fn is_unique_violation(e: &rustango::sql::ExecError) -> bool {
113 let msg = e.to_string().to_ascii_lowercase();
114 msg.contains("unique constraint") || msg.contains("duplicate entry") || msg.contains("duplicate key value")
117}
118
119const UNIQUE_SEQUENCE_INDEX: &str = "cms_revision_page_sequence_uniq";
121
122pub async fn ensure_unique_sequence(
130 pool: &rustango::sql::Pool,
131) -> Result<(), rustango::sql::ExecError> {
132 if create_unique_sequence_index(pool).await.is_ok() {
133 return Ok(());
134 }
135 renumber_duplicate_sequences(pool).await?;
136 create_unique_sequence_index(pool).await
137}
138
139async fn create_unique_sequence_index(
140 pool: &rustango::sql::Pool,
141) -> Result<(), rustango::sql::ExecError> {
142 let if_not_exists = if pool.dialect().name() == "mysql" { "" } else { "IF NOT EXISTS " };
145 let sql = format!(
146 "CREATE UNIQUE INDEX {if_not_exists}{UNIQUE_SEQUENCE_INDEX} ON cms_revision (page_id, sequence)"
147 );
148 match rustango::sql::raw_execute_pool(pool, &sql, Vec::new()).await {
149 Ok(_) => Ok(()),
150 Err(e) if e.to_string().to_ascii_lowercase().contains("duplicate key name") => Ok(()),
151 Err(e) => Err(e),
152 }
153}
154
155async fn renumber_duplicate_sequences(
156 pool: &rustango::sql::Pool,
157) -> Result<(), rustango::sql::ExecError> {
158 use rustango::core::Column as _;
159 use rustango::sql::FetcherPool as _;
160
161 let pages: Vec<(i64,)> = rustango::sql::raw_query_pool(
162 "SELECT page_id FROM cms_revision GROUP BY page_id, sequence HAVING COUNT(*) > 1",
163 Vec::new(),
164 pool,
165 )
166 .await?;
167 let mut seen = std::collections::HashSet::new();
168 for (page_id,) in pages {
169 if !seen.insert(page_id) {
170 continue;
171 }
172 let rows: Vec<Revision> = Revision::objects()
173 .where_(Revision::page_id.eq(page_id))
174 .order_by(&[("sequence", false), ("id", false)])
175 .fetch(pool)
176 .await?;
177 for (n, mut row) in rows.into_iter().enumerate() {
178 let want = i32::try_from(n + 1).unwrap_or(i32::MAX);
179 if row.sequence != want {
180 row.sequence = want;
181 row.save_pool(pool).await?;
182 }
183 }
184 }
185 Ok(())
186}
187
188pub const DEFAULT_KEEP_LATEST: usize = 50;
201
202#[derive(Debug, Clone, Copy, Default)]
204pub struct PruneOutcome {
205 pub total: usize,
207 pub deleted: usize,
209}
210
211pub async fn prune(
217 pool: &rustango::sql::Pool,
218 page_id: i64,
219 keep_latest: usize,
220 keep_published: bool,
221) -> Result<PruneOutcome, rustango::sql::ExecError> {
222 use rustango::core::Column as _;
223 use rustango::sql::FetcherPool as _;
224 let mut rows: Vec<Revision> = Revision::objects()
225 .where_(Revision::page_id.eq(page_id))
226 .order_by(&[("sequence", true)]) .fetch(pool)
228 .await?;
229 let total = rows.len();
230 if total == 0 {
231 return Ok(PruneOutcome::default());
232 }
233 let keep = keep_latest.max(1);
234 let anchor_id: Option<i64> = rows
238 .iter()
239 .find(|r| r.snapshot.get("status").and_then(|v| v.as_str()) == Some("published"))
240 .and_then(|r| r.id.get().copied());
241 let mut deleted = 0;
242 rows.reverse();
245 let cutoff = total.saturating_sub(keep);
246 for (idx, row) in rows.into_iter().enumerate() {
247 if idx >= cutoff {
248 break;
249 }
250 if Some(row.id.get().copied().unwrap_or_default()) == anchor_id {
251 continue;
252 }
253 if keep_published
254 && (row.snapshot.get("status").and_then(|v| v.as_str()) == Some("published"))
255 {
256 continue;
257 }
258 row.delete_pool(pool).await?;
259 deleted += 1;
260 }
261 Ok(PruneOutcome { total, deleted })
262}
263
264pub async fn prune_all_pages(
272 pool: &rustango::sql::Pool,
273 keep_latest: usize,
274 keep_published: bool,
275) -> Result<(usize, usize), rustango::sql::ExecError> {
276 use rustango::sql::FetcherPool as _;
277 let pages: Vec<crate::page::Page> = crate::page::Page::objects().fetch(pool).await?;
278 let mut total_pages = 0;
279 let mut total_deleted = 0;
280 for p in pages {
281 let Some(pid) = p.id.get().copied() else {
282 continue;
283 };
284 total_pages += 1;
285 match prune(pool, pid, keep_latest, keep_published).await {
286 Ok(outcome) => total_deleted += outcome.deleted,
287 Err(e) => tracing::warn!(
288 target: "rustango_cms::revision",
289 page_id = pid,
290 error = %e,
291 "revision prune failed; continuing"
292 ),
293 }
294 }
295 Ok((total_pages, total_deleted))
296}
297
298#[derive(Debug, Clone, serde::Serialize)]
307#[serde(tag = "kind", rename_all = "snake_case")]
308pub enum FieldDiff {
309 Unchanged { field: String, value: String },
312 Changed { field: String, a: String, b: String },
314 Added { field: String, b: String },
316 Removed { field: String, a: String },
318}
319
320impl FieldDiff {
321 #[must_use]
323 pub fn field(&self) -> &str {
324 match self {
325 Self::Unchanged { field, .. }
326 | Self::Changed { field, .. }
327 | Self::Added { field, .. }
328 | Self::Removed { field, .. } => field,
329 }
330 }
331
332 #[must_use]
335 pub fn is_change(&self) -> bool {
336 !matches!(self, Self::Unchanged { .. })
337 }
338}
339
340#[cfg(test)]
341mod prune_tests {
342 use super::*;
343
344 fn cutoff_for(total: usize, keep: usize) -> usize {
347 total.saturating_sub(keep.max(1))
348 }
349
350 #[test]
351 fn no_cutoff_when_under_keep() {
352 assert_eq!(cutoff_for(10, 50), 0);
353 }
354
355 #[test]
356 fn cutoff_drops_oldest_only() {
357 assert_eq!(cutoff_for(100, 50), 50);
359 }
360
361 #[test]
362 fn keep_zero_treated_as_one() {
363 assert_eq!(cutoff_for(10, 0), 9);
364 }
365
366 #[test]
367 fn default_keep_latest_is_sensible() {
368 assert!((10..=200).contains(&DEFAULT_KEEP_LATEST));
369 }
370}
371
372const DIFF_FIELDS: &[&str] = &[
378 "title",
379 "slug",
380 "status",
381 "page_type_id",
382 "seo_title",
383 "seo_description",
384 "robots_index",
385 "sitemap_priority",
386 "theme_id",
387 "show_in_menus",
388 "go_live_at",
389 "expire_at",
390 "published_at",
391 "locale_variant_of",
392];
393
394fn format_value(value: &serde_json::Value) -> String {
399 use serde_json::Value;
400 match value {
401 Value::Null => "—".to_owned(),
402 Value::String(s) => s.clone(),
403 Value::Bool(b) => b.to_string(),
404 Value::Number(n) => n.to_string(),
405 other => serde_json::to_string_pretty(other).unwrap_or_else(|_| other.to_string()),
406 }
407}
408
409#[must_use]
416pub fn diff_snapshots(a: &serde_json::Value, b: &serde_json::Value) -> Vec<FieldDiff> {
417 use serde_json::Value;
418 DIFF_FIELDS
419 .iter()
420 .map(|field| {
421 let av = a.get(field).cloned().unwrap_or(Value::Null);
422 let bv = b.get(field).cloned().unwrap_or(Value::Null);
423 let a_null = matches!(av, Value::Null);
424 let b_null = matches!(bv, Value::Null);
425 let same = av == bv;
426 let field = (*field).to_owned();
427 if same {
428 FieldDiff::Unchanged {
429 field,
430 value: format_value(&av),
431 }
432 } else if a_null && !b_null {
433 FieldDiff::Added {
434 field,
435 b: format_value(&bv),
436 }
437 } else if b_null && !a_null {
438 FieldDiff::Removed {
439 field,
440 a: format_value(&av),
441 }
442 } else {
443 FieldDiff::Changed {
444 field,
445 a: format_value(&av),
446 b: format_value(&bv),
447 }
448 }
449 })
450 .collect()
451}