1use chrono::Utc;
21use rustango::core::Column as _;
22use rustango::extractors::Tenant;
23use rustango::sql::{
24 sqlx, write_transaction, Auto, ExecError, FetcherPool as _, FetcherTx as _, Pool, PoolTx,
25};
26
27use crate::page::{Page, PageStatus};
28use crate::page_type::find_handler;
29use crate::page_type_model::PageType;
30use crate::tree::{depth_of, descendants_like, MaterializedPath, PathError};
31
32#[derive(Debug, thiserror::Error)]
34pub enum TreeError {
35 #[error(transparent)]
36 Db(#[from] ExecError),
37 #[error(transparent)]
38 Sqlx(#[from] sqlx::Error),
39 #[error(transparent)]
40 Path(#[from] PathError),
41 #[error(transparent)]
42 Query(#[from] rustango::core::QueryError),
43 #[error("page id was not assigned after insert")]
44 MissingId,
45 #[error("page {0} not found")]
46 NotFound(i64),
47 #[error("cms_page_type row {0} not found — has `ensure_seeded` run for this tenant?")]
48 UnknownPageType(i64),
49 #[error("cannot move a page beneath itself or its own descendant")]
50 CycleAttempt,
51 #[error(
52 "page-type `{child_type}` is not in `{parent_type}.allowed_child_types` — \
53 parent refuses this child"
54 )]
55 DisallowedChildType {
56 parent_type: String,
57 child_type: String,
58 },
59 #[error(
60 "page-type `{child_type}.allowed_parent_types` does not include \
61 `{parent_type}` — child refuses this parent"
62 )]
63 DisallowedParentType {
64 parent_type: String,
65 child_type: String,
66 },
67}
68
69pub async fn atomic_tree<T, F>(pool: &Pool, f: F) -> Result<T, TreeError>
96where
97 T: Send + 'static,
98 F: Send
99 + 'static
100 + for<'tx> FnOnce(
101 &'tx mut PoolTx<'_>,
102 ) -> std::pin::Pin<
103 Box<dyn std::future::Future<Output = Result<T, TreeError>> + Send + 'tx>,
104 >,
105{
106 let stash: std::sync::Arc<std::sync::Mutex<Option<TreeError>>> =
107 std::sync::Arc::new(std::sync::Mutex::new(None));
108 let stash_cb = std::sync::Arc::clone(&stash);
109 let out = rustango::sql::atomic_immediate(pool, move |tx| {
113 Box::pin(async move {
114 let mut guard = tx.lock().await?;
115 match f(&mut guard).await {
116 Ok(v) => Ok(v),
117 Err(e) => {
118 *stash_cb.lock().expect("atomic_tree stash poisoned") = Some(e);
119 Err(ExecError::EmptyReturning)
122 }
123 }
124 })
125 })
126 .await;
127 match out {
128 Ok(v) => Ok(v),
129 Err(commit_err) => {
130 let domain = stash.lock().expect("atomic_tree stash poisoned").take();
131 Err(domain.unwrap_or(TreeError::Db(commit_err)))
132 }
133 }
134}
135
136#[derive(Debug, Clone)]
140pub struct NewPage {
141 pub page_type_id: i64,
142 pub title: String,
143 pub slug: String,
144 pub status: PageStatus,
145 pub seo_title: String,
146 pub seo_description: String,
147}
148
149impl NewPage {
150 pub fn new(page_type_id: i64, title: impl Into<String>, slug: impl Into<String>) -> Self {
151 Self {
152 page_type_id,
153 title: title.into(),
154 slug: slug.into(),
155 status: PageStatus::Draft,
156 seo_title: String::new(),
157 seo_description: String::new(),
158 }
159 }
160
161 pub fn with_status(mut self, status: PageStatus) -> Self {
162 self.status = status;
163 self
164 }
165
166 pub fn with_seo(mut self, title: impl Into<String>, description: impl Into<String>) -> Self {
167 self.seo_title = title.into();
168 self.seo_description = description.into();
169 self
170 }
171
172 fn into_page(self, parent_id: Option<i64>, sort_order: i32) -> Page {
173 let published_at = matches!(self.status, PageStatus::Published).then(Utc::now);
174 let last_published_at = published_at;
179 Page {
180 id: Auto::Unset,
181 page_type_id: self.page_type_id,
182 title: self.title,
183 slug: self.slug,
184 path: String::new(),
185 url_path: String::new(),
186 preview_path: String::new(),
189 template_override: String::new(),
192 depth: 0,
193 parent_id,
194 locale_variant_of: None,
195 alias_of: None,
196 theme_id: None,
197 sort_order,
198 status: self.status.as_str().to_owned(),
199 published_at,
200 last_published_at,
201 go_live_at: None,
202 expire_at: None,
203 seo_title: self.seo_title,
204 seo_description: self.seo_description,
205 robots_index: true,
206 sitemap_priority: 0.5,
207 show_in_menus: false,
208 og_title: String::new(),
209 og_description: String::new(),
210 og_image_media_id: None,
211 twitter_card: "summary_large_image".to_owned(),
212 notification_pre_published_sent: false,
213 created_at: Auto::Unset,
214 updated_at: Auto::Unset,
215 }
216 }
217}
218
219pub fn compute_url_path(parent_url_path: Option<&str>, slug: &str) -> String {
231 match parent_url_path {
232 None => {
233 if slug.is_empty() {
235 "/".to_owned()
236 } else {
237 format!("/{slug}")
238 }
239 }
240 Some(parent) => {
241 if slug.is_empty() {
242 parent.to_owned()
243 } else if parent == "/" {
244 format!("/{slug}")
245 } else {
246 format!("{parent}/{slug}")
247 }
248 }
249 }
250}
251
252pub async fn cascade_url_path_to_descendants(
264 tx: &mut PoolTx<'_>,
265 root_page: &Page,
266) -> Result<usize, TreeError> {
267 let root_id = page_id(root_page)?;
268 let pattern = descendants_like(&root_page.path);
269 let descendants: Vec<Page> = Page::objects()
270 .where_(Page::path.like(pattern))
271 .where_(Page::path.ne(root_page.path.clone()))
272 .order_by(&[("path", false)])
273 .fetch_tx(tx)
274 .await?;
275
276 let mut by_id: std::collections::HashMap<i64, String> = std::collections::HashMap::new();
277 by_id.insert(root_id, root_page.url_path.clone());
278
279 let mut updated = 0usize;
280 for mut d in descendants {
281 let Some(parent_id) = d.parent_id else {
282 continue;
283 };
284 let parent_url_path = by_id.get(&parent_id).cloned().unwrap_or_default();
285 let new_url = compute_url_path(Some(parent_url_path.as_str()), &d.slug);
286 if d.url_path == new_url {
287 let did = d.id.get().copied().unwrap_or_default();
288 by_id.insert(did, new_url);
289 continue;
290 }
291 d.url_path = new_url.clone();
292 let did = d.id.get().copied().unwrap_or_default();
293 by_id.insert(did, new_url);
294 d.save_tx(tx).await?;
295 updated += 1;
296 }
297 Ok(updated)
298}
299
300pub async fn rebuild_all_url_paths(pool: &Pool) -> Result<usize, TreeError> {
308 let mut iter = Page::objects()
319 .order_by(&[("path", false)])
320 .iterator(2_000)?;
321
322 let mut by_id: std::collections::HashMap<i64, String> = std::collections::HashMap::new();
323 let mut updated = 0usize;
324 while let Some(mut p) = iter.next_row(pool).await? {
325 let id = page_id(&p)?;
326 let new_url = match p.parent_id {
327 None => compute_url_path(None, &p.slug),
328 Some(parent_id) => {
329 let parent_url = by_id.get(&parent_id).cloned().unwrap_or_default();
330 compute_url_path(Some(parent_url.as_str()), &p.slug)
331 }
332 };
333 if p.url_path != new_url {
334 p.url_path = new_url.clone();
335 p.save(pool).await?;
336 updated += 1;
337 }
338 by_id.insert(id, new_url);
339 }
340 Ok(updated)
341}
342
343impl Page {
344 pub async fn create_root(tenant: &Tenant, new: NewPage) -> Result<Self, TreeError> {
347 Self::create_root_pool(tenant.pool(), new).await
348 }
349
350 pub async fn create_root_pool(pool: &Pool, new: NewPage) -> Result<Self, TreeError> {
356 let mut tx = write_transaction(pool).await?;
357 let sort_order = next_root_sort_order_tx(&mut tx).await?;
361 let mut page = new.into_page(None, sort_order);
362
363 page.insert_tx(&mut tx).await?;
364 let id = page_id(&page)?;
365
366 let path = MaterializedPath::root(id)?;
367 page.path = path.into_string();
368 page.depth = 1;
369 page.url_path = compute_url_path(None, &page.slug);
370 page.save_tx(&mut tx).await?;
371 tx.commit().await?;
372
373 Ok(page)
374 }
375
376 pub async fn create_child(
385 tenant: &Tenant,
386 parent: &Page,
387 new: NewPage,
388 ) -> Result<Self, TreeError> {
389 Self::create_child_pool(tenant.pool(), parent, new).await
390 }
391
392 pub async fn create_child_pool(
396 pool: &Pool,
397 parent: &Page,
398 new: NewPage,
399 ) -> Result<Self, TreeError> {
400 let parent_id = page_id(parent)?;
401 validate_child_placement(pool, parent.page_type_id, new.page_type_id).await?;
402
403 let mut tx = write_transaction(pool).await?;
404 let _locked_parent: Vec<Page> = Page::objects()
414 .where_(Page::id.eq(parent_id))
415 .select_for_update()
416 .silent_on_sqlite()
417 .fetch_tx(&mut tx)
418 .await?;
419 let sort_order = next_child_sort_order_tx(&mut tx, parent_id).await?;
420 let mut page = new.into_page(Some(parent_id), sort_order);
421
422 page.insert_tx(&mut tx).await?;
423 let id = page_id(&page)?;
424
425 let path = MaterializedPath::child_of(&parent.path, id)?;
426 page.depth = path.depth();
427 page.path = path.into_string();
428 page.url_path = compute_url_path(Some(parent.url_path.as_str()), &page.slug);
429 page.save_tx(&mut tx).await?;
430 tx.commit().await?;
431
432 Ok(page)
433 }
434
435 pub async fn children(&self, pool: &Pool) -> Result<Vec<Page>, TreeError> {
437 let id = page_id(self)?;
438 let rows = Page::objects()
439 .where_(Page::parent_id.eq(id))
440 .order_by(&[("sort_order", false), ("id", false)])
441 .fetch(pool)
442 .await?;
443 Ok(rows)
444 }
445
446 pub async fn siblings(&self, pool: &Pool) -> Result<Vec<Page>, TreeError> {
449 let id = page_id(self)?;
450 let qs = Page::objects().order_by(&[("sort_order", false), ("id", false)]);
451 let rows = match self.parent_id {
452 Some(pid) => qs.where_(Page::parent_id.eq(pid)).fetch(pool).await?,
453 None => qs.where_(Page::parent_id.is_null()).fetch(pool).await?,
454 };
455 Ok(rows
456 .into_iter()
457 .filter(|p| p.id.get().copied() != Some(id))
458 .collect())
459 }
460
461 pub async fn ancestors(&self, pool: &Pool) -> Result<Vec<Page>, TreeError> {
464 let paths = MaterializedPath::ancestors_of(&self.path);
465 if paths.is_empty() {
466 return Ok(Vec::new());
467 }
468 let mut rows = Page::objects()
469 .where_(Page::path.is_in(paths.iter().cloned()))
470 .order_by(&[("path", false)])
471 .fetch(pool)
472 .await?;
473 rows.sort_by(|a, b| a.path.cmp(&b.path));
474 Ok(rows)
475 }
476
477 pub async fn descendants(&self, pool: &Pool) -> Result<Vec<Page>, TreeError> {
480 let pattern = descendants_like(&self.path);
481 let rows = Page::objects()
482 .where_(Page::path.like(pattern))
483 .where_(Page::path.ne(self.path.clone()))
484 .order_by(&[("path", false)])
485 .fetch(pool)
486 .await?;
487 Ok(rows)
488 }
489
490 pub async fn move_to(
498 &mut self,
499 tenant: &Tenant,
500 new_parent: Option<&Page>,
501 ) -> Result<(), TreeError> {
502 let self_id = page_id(self)?;
503
504 if let Some(np) = new_parent {
505 let np_id = page_id(np)?;
506 if np_id == self_id || np.path.starts_with(&self.path) {
507 return Err(TreeError::CycleAttempt);
508 }
509 validate_child_placement(tenant.pool(), np.page_type_id, self.page_type_id).await?;
510 }
511
512 let new_id_path = match new_parent {
513 Some(np) => MaterializedPath::child_of(&np.path, self_id)?.into_string(),
514 None => MaterializedPath::root(self_id)?.into_string(),
515 };
516 if new_id_path == self.path {
517 return Ok(());
518 }
519
520 let subtree = self.descendants(tenant.pool()).await?;
521 let mut tx = write_transaction(tenant.pool()).await?;
522 self.move_to_in_tx(new_parent, subtree, &mut tx).await?;
523 tx.commit().await?;
524 Ok(())
525 }
526
527 pub async fn move_to_in_tx(
539 &mut self,
540 new_parent: Option<&Page>,
541 subtree: Vec<Page>,
542 tx: &mut PoolTx<'_>,
543 ) -> Result<(), TreeError> {
544 let self_id = page_id(self)?;
545 let new_id_path = match new_parent {
546 Some(np) => MaterializedPath::child_of(&np.path, self_id)?.into_string(),
547 None => MaterializedPath::root(self_id)?.into_string(),
548 };
549 if new_id_path == self.path {
550 return Ok(());
551 }
552 let old_prefix = self.path.clone();
553
554 let new_sort_order = match new_parent {
559 Some(np) => {
560 let np_id = page_id(np)?;
561 let _locked_parent: Vec<Page> = Page::objects()
562 .where_(Page::id.eq(np_id))
563 .select_for_update()
564 .silent_on_sqlite()
565 .fetch_tx(tx)
566 .await?;
567 next_child_sort_order_tx(tx, np_id).await?
568 }
569 None => next_root_sort_order_tx(tx).await?,
570 };
571
572 self.parent_id = new_parent.and_then(|p| p.id.get().copied());
573 self.sort_order = new_sort_order;
574 self.depth = depth_of(&new_id_path);
575 self.path = new_id_path.clone();
576 self.url_path = compute_url_path(new_parent.map(|p| p.url_path.as_str()), &self.slug);
580 self.save_tx(tx).await?;
581
582 let mut url_of: std::collections::HashMap<i64, String> = std::collections::HashMap::new();
585 url_of.insert(self_id, self.url_path.clone());
586 for mut row in subtree {
587 let suffix = row
588 .path
589 .strip_prefix(&old_prefix)
590 .expect("descendant path must start with old prefix");
591 row.path = format!("{new_id_path}{suffix}");
592 row.depth = depth_of(&row.path);
593 let parent_url = row.parent_id.and_then(|pid| url_of.get(&pid).cloned());
594 row.url_path = compute_url_path(parent_url.as_deref(), &row.slug);
595 if let Some(id) = row.id.get().copied() {
596 url_of.insert(id, row.url_path.clone());
597 }
598 row.save_tx(tx).await?;
599 }
600 Ok(())
601 }
602}
603
604fn page_id(page: &Page) -> Result<i64, TreeError> {
607 page.id.get().copied().ok_or(TreeError::MissingId)
608}
609
610async fn next_root_sort_order_tx(tx: &mut PoolTx<'_>) -> Result<i32, TreeError> {
625 let _lock: Vec<Page> = Page::objects()
626 .where_(Page::parent_id.is_null())
627 .order_by(&[("id", false)])
628 .limit(1)
629 .select_for_update()
630 .silent_on_sqlite()
631 .fetch_tx(tx)
632 .await?;
633 let rows = Page::objects()
634 .where_(Page::parent_id.is_null())
635 .order_by(&[("sort_order", true)])
636 .fetch_tx(tx)
637 .await?;
638 Ok(rows.first().map(|p| p.sort_order + 1).unwrap_or(0))
639}
640
641async fn next_child_sort_order_tx(tx: &mut PoolTx<'_>, parent_id: i64) -> Result<i32, TreeError> {
647 let rows = Page::objects()
648 .where_(Page::parent_id.eq(parent_id))
649 .order_by(&[("sort_order", true)])
650 .fetch_tx(tx)
651 .await?;
652 Ok(rows.first().map(|p| p.sort_order + 1).unwrap_or(0))
653}
654
655pub async fn validate_child_placement(
670 pool: &Pool,
671 parent_type_id: i64,
672 child_type_id: i64,
673) -> Result<(), TreeError> {
674 let rows: Vec<PageType> = PageType::objects()
675 .where_(PageType::id.is_in([parent_type_id, child_type_id]))
676 .fetch(pool)
677 .await?;
678
679 let parent = rows
680 .iter()
681 .find(|r| r.id.get().copied() == Some(parent_type_id))
682 .ok_or(TreeError::UnknownPageType(parent_type_id))?;
683 let child = rows
684 .iter()
685 .find(|r| r.id.get().copied() == Some(child_type_id))
686 .ok_or(TreeError::UnknownPageType(child_type_id))?;
687
688 if find_handler(&parent.type_name).is_some_and(|h| h.is_leaf()) {
690 return Err(TreeError::DisallowedChildType {
691 parent_type: parent.type_name.clone(),
692 child_type: child.type_name.clone(),
693 });
694 }
695 let allowed = parent.allowed_children();
697 if !allowed.is_empty() && !allowed.iter().any(|t| *t == child.type_name) {
698 return Err(TreeError::DisallowedChildType {
699 parent_type: parent.type_name.clone(),
700 child_type: child.type_name.clone(),
701 });
702 }
703 let allowed = child.allowed_parents();
704 if !allowed.is_empty() && !allowed.iter().any(|t| *t == parent.type_name) {
705 return Err(TreeError::DisallowedParentType {
706 parent_type: parent.type_name.clone(),
707 child_type: child.type_name.clone(),
708 });
709 }
710
711 Ok(())
712}
713
714impl MaterializedPath {
717 pub fn ancestors_of(path: &str) -> Vec<String> {
718 let mut out = Vec::new();
719 let mut acc = String::new();
720 for seg in path.split(crate::tree::SEPARATOR).filter(|s| !s.is_empty()) {
721 acc.push_str(seg);
722 acc.push(crate::tree::SEPARATOR);
723 if acc != path {
724 out.push(acc.clone());
725 }
726 }
727 if let Some(last) = out.last() {
728 if last == path {
729 out.pop();
730 }
731 }
732 out
733 }
734}
735
736#[cfg(all(test, feature = "sqlite"))]
741mod atomic_tree_tests {
742 use super::*;
743 use rustango::sql::Pool;
744 use std::sync::atomic::{AtomicBool, Ordering};
745 use std::sync::Arc;
746
747 async fn mem_pool() -> Pool {
748 Pool::connect("sqlite::memory:")
749 .await
750 .expect("sqlite in-memory pool")
751 }
752
753 #[tokio::test]
754 async fn commit_returns_value_and_fires_on_commit() {
755 let pool = mem_pool().await;
756 let fired = Arc::new(AtomicBool::new(false));
757 let f = fired.clone();
758 let out = atomic_tree(&pool, move |_tx| {
759 Box::pin(async move {
760 rustango::sql::on_commit(move || f.store(true, Ordering::SeqCst));
761 Ok::<i32, TreeError>(7)
762 })
763 })
764 .await;
765 assert_eq!(out.expect("commit"), 7);
766 assert!(
769 fired.load(Ordering::SeqCst),
770 "on_commit must fire on commit"
771 );
772 }
773
774 #[tokio::test]
775 async fn tree_error_propagates_unchanged_and_drops_on_commit() {
776 let pool = mem_pool().await;
777 let fired = Arc::new(AtomicBool::new(false));
778 let f = fired.clone();
779 let out: Result<(), TreeError> = atomic_tree(&pool, move |_tx| {
780 Box::pin(async move {
781 rustango::sql::on_commit(move || f.store(true, Ordering::SeqCst));
782 Err(TreeError::CycleAttempt)
783 })
784 })
785 .await;
786 assert!(matches!(out, Err(TreeError::CycleAttempt)), "got {out:?}");
789 assert!(
790 !fired.load(Ordering::SeqCst),
791 "on_commit must be dropped on a TreeError rollback"
792 );
793 }
794}