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(pool, move |tx| {
110 Box::pin(async move {
111 let mut guard = tx.lock().await?;
112 match f(&mut guard).await {
113 Ok(v) => Ok(v),
114 Err(e) => {
115 *stash_cb.lock().expect("atomic_tree stash poisoned") = Some(e);
116 Err(ExecError::EmptyReturning)
119 }
120 }
121 })
122 })
123 .await;
124 match out {
125 Ok(v) => Ok(v),
126 Err(commit_err) => {
127 let domain = stash.lock().expect("atomic_tree stash poisoned").take();
128 Err(domain.unwrap_or(TreeError::Db(commit_err)))
129 }
130 }
131}
132
133#[derive(Debug, Clone)]
137pub struct NewPage {
138 pub page_type_id: i64,
139 pub title: String,
140 pub slug: String,
141 pub status: PageStatus,
142 pub seo_title: String,
143 pub seo_description: String,
144}
145
146impl NewPage {
147 pub fn new(page_type_id: i64, title: impl Into<String>, slug: impl Into<String>) -> Self {
148 Self {
149 page_type_id,
150 title: title.into(),
151 slug: slug.into(),
152 status: PageStatus::Draft,
153 seo_title: String::new(),
154 seo_description: String::new(),
155 }
156 }
157
158 pub fn with_status(mut self, status: PageStatus) -> Self {
159 self.status = status;
160 self
161 }
162
163 pub fn with_seo(mut self, title: impl Into<String>, description: impl Into<String>) -> Self {
164 self.seo_title = title.into();
165 self.seo_description = description.into();
166 self
167 }
168
169 fn into_page(self, parent_id: Option<i64>, sort_order: i32) -> Page {
170 let published_at = matches!(self.status, PageStatus::Published).then(Utc::now);
171 let last_published_at = published_at;
176 Page {
177 id: Auto::Unset,
178 page_type_id: self.page_type_id,
179 title: self.title,
180 slug: self.slug,
181 path: String::new(),
182 url_path: String::new(),
183 preview_path: String::new(),
186 template_override: String::new(),
189 depth: 0,
190 parent_id,
191 locale_variant_of: None,
192 alias_of: None,
193 theme_id: None,
194 sort_order,
195 status: self.status.as_str().to_owned(),
196 published_at,
197 last_published_at,
198 go_live_at: None,
199 expire_at: None,
200 seo_title: self.seo_title,
201 seo_description: self.seo_description,
202 robots_index: true,
203 sitemap_priority: 0.5,
204 show_in_menus: false,
205 og_title: String::new(),
206 og_description: String::new(),
207 og_image_media_id: None,
208 twitter_card: "summary_large_image".to_owned(),
209 notification_pre_published_sent: false,
210 created_at: Auto::Unset,
211 updated_at: Auto::Unset,
212 }
213 }
214}
215
216pub fn compute_url_path(parent_url_path: Option<&str>, slug: &str) -> String {
228 match parent_url_path {
229 None => {
230 if slug.is_empty() {
232 "/".to_owned()
233 } else {
234 format!("/{slug}")
235 }
236 }
237 Some(parent) => {
238 if slug.is_empty() {
239 parent.to_owned()
240 } else if parent == "/" {
241 format!("/{slug}")
242 } else {
243 format!("{parent}/{slug}")
244 }
245 }
246 }
247}
248
249pub async fn cascade_url_path_to_descendants(
261 tx: &mut PoolTx<'_>,
262 root_page: &Page,
263) -> Result<usize, TreeError> {
264 let root_id = page_id(root_page)?;
265 let pattern = descendants_like(&root_page.path);
266 let descendants: Vec<Page> = Page::objects()
267 .where_(Page::path.like(pattern))
268 .where_(Page::path.ne(root_page.path.clone()))
269 .order_by(&[("path", false)])
270 .fetch_tx(tx)
271 .await?;
272
273 let mut by_id: std::collections::HashMap<i64, String> = std::collections::HashMap::new();
274 by_id.insert(root_id, root_page.url_path.clone());
275
276 let mut updated = 0usize;
277 for mut d in descendants {
278 let Some(parent_id) = d.parent_id else {
279 continue;
280 };
281 let parent_url_path = by_id.get(&parent_id).cloned().unwrap_or_default();
282 let new_url = compute_url_path(Some(parent_url_path.as_str()), &d.slug);
283 if d.url_path == new_url {
284 let did = d.id.get().copied().unwrap_or_default();
285 by_id.insert(did, new_url);
286 continue;
287 }
288 d.url_path = new_url.clone();
289 let did = d.id.get().copied().unwrap_or_default();
290 by_id.insert(did, new_url);
291 d.save_tx(tx).await?;
292 updated += 1;
293 }
294 Ok(updated)
295}
296
297pub async fn rebuild_all_url_paths(pool: &Pool) -> Result<usize, TreeError> {
305 let mut iter = Page::objects()
316 .order_by(&[("path", false)])
317 .iterator(2_000)?;
318
319 let mut by_id: std::collections::HashMap<i64, String> = std::collections::HashMap::new();
320 let mut updated = 0usize;
321 while let Some(mut p) = iter.next_row(pool).await? {
322 let id = page_id(&p)?;
323 let new_url = match p.parent_id {
324 None => compute_url_path(None, &p.slug),
325 Some(parent_id) => {
326 let parent_url = by_id.get(&parent_id).cloned().unwrap_or_default();
327 compute_url_path(Some(parent_url.as_str()), &p.slug)
328 }
329 };
330 if p.url_path != new_url {
331 p.url_path = new_url.clone();
332 p.save_pool(pool).await?;
333 updated += 1;
334 }
335 by_id.insert(id, new_url);
336 }
337 Ok(updated)
338}
339
340impl Page {
341 pub async fn create_root(tenant: &Tenant, new: NewPage) -> Result<Self, TreeError> {
344 Self::create_root_pool(tenant.pool(), new).await
345 }
346
347 pub async fn create_root_pool(pool: &Pool, new: NewPage) -> Result<Self, TreeError> {
353 let mut tx = write_transaction(pool).await?;
354 let sort_order = next_root_sort_order_tx(&mut tx).await?;
358 let mut page = new.into_page(None, sort_order);
359
360 page.insert_tx(&mut tx).await?;
361 let id = page_id(&page)?;
362
363 let path = MaterializedPath::root(id)?;
364 page.path = path.into_string();
365 page.depth = 1;
366 page.url_path = compute_url_path(None, &page.slug);
367 page.save_tx(&mut tx).await?;
368 tx.commit().await?;
369
370 Ok(page)
371 }
372
373 pub async fn create_child(
382 tenant: &Tenant,
383 parent: &Page,
384 new: NewPage,
385 ) -> Result<Self, TreeError> {
386 Self::create_child_pool(tenant.pool(), parent, new).await
387 }
388
389 pub async fn create_child_pool(
393 pool: &Pool,
394 parent: &Page,
395 new: NewPage,
396 ) -> Result<Self, TreeError> {
397 let parent_id = page_id(parent)?;
398 validate_child_placement(pool, parent.page_type_id, new.page_type_id).await?;
399
400 let mut tx = write_transaction(pool).await?;
401 let _locked_parent: Vec<Page> = Page::objects()
411 .where_(Page::id.eq(parent_id))
412 .select_for_update()
413 .silent_on_sqlite()
414 .fetch_tx(&mut tx)
415 .await?;
416 let sort_order = next_child_sort_order_tx(&mut tx, parent_id).await?;
417 let mut page = new.into_page(Some(parent_id), sort_order);
418
419 page.insert_tx(&mut tx).await?;
420 let id = page_id(&page)?;
421
422 let path = MaterializedPath::child_of(&parent.path, id)?;
423 page.depth = path.depth();
424 page.path = path.into_string();
425 page.url_path = compute_url_path(Some(parent.url_path.as_str()), &page.slug);
426 page.save_tx(&mut tx).await?;
427 tx.commit().await?;
428
429 Ok(page)
430 }
431
432 pub async fn children(&self, pool: &Pool) -> Result<Vec<Page>, TreeError> {
434 let id = page_id(self)?;
435 let rows = Page::objects()
436 .where_(Page::parent_id.eq(id))
437 .order_by(&[("sort_order", false), ("id", false)])
438 .fetch(pool)
439 .await?;
440 Ok(rows)
441 }
442
443 pub async fn siblings(&self, pool: &Pool) -> Result<Vec<Page>, TreeError> {
446 let id = page_id(self)?;
447 let qs = Page::objects().order_by(&[("sort_order", false), ("id", false)]);
448 let rows = match self.parent_id {
449 Some(pid) => qs.where_(Page::parent_id.eq(pid)).fetch(pool).await?,
450 None => qs.where_(Page::parent_id.is_null()).fetch(pool).await?,
451 };
452 Ok(rows
453 .into_iter()
454 .filter(|p| p.id.get().copied() != Some(id))
455 .collect())
456 }
457
458 pub async fn ancestors(&self, pool: &Pool) -> Result<Vec<Page>, TreeError> {
461 let paths = MaterializedPath::ancestors_of(&self.path);
462 if paths.is_empty() {
463 return Ok(Vec::new());
464 }
465 let mut rows = Page::objects()
466 .where_(Page::path.is_in(paths.iter().cloned()))
467 .order_by(&[("path", false)])
468 .fetch(pool)
469 .await?;
470 rows.sort_by(|a, b| a.path.cmp(&b.path));
471 Ok(rows)
472 }
473
474 pub async fn descendants(&self, pool: &Pool) -> Result<Vec<Page>, TreeError> {
477 let pattern = descendants_like(&self.path);
478 let rows = Page::objects()
479 .where_(Page::path.like(pattern))
480 .where_(Page::path.ne(self.path.clone()))
481 .order_by(&[("path", false)])
482 .fetch(pool)
483 .await?;
484 Ok(rows)
485 }
486
487 pub async fn move_to(
495 &mut self,
496 tenant: &Tenant,
497 new_parent: Option<&Page>,
498 ) -> Result<(), TreeError> {
499 let self_id = page_id(self)?;
500
501 if let Some(np) = new_parent {
502 let np_id = page_id(np)?;
503 if np_id == self_id || np.path.starts_with(&self.path) {
504 return Err(TreeError::CycleAttempt);
505 }
506 validate_child_placement(tenant.pool(), np.page_type_id, self.page_type_id).await?;
507 }
508
509 let new_id_path = match new_parent {
510 Some(np) => MaterializedPath::child_of(&np.path, self_id)?.into_string(),
511 None => MaterializedPath::root(self_id)?.into_string(),
512 };
513 if new_id_path == self.path {
514 return Ok(());
515 }
516
517 let subtree = self.descendants(tenant.pool()).await?;
518 let mut tx = write_transaction(tenant.pool()).await?;
519 self.move_to_in_tx(new_parent, subtree, &mut tx).await?;
520 tx.commit().await?;
521 Ok(())
522 }
523
524 pub async fn move_to_in_tx(
536 &mut self,
537 new_parent: Option<&Page>,
538 subtree: Vec<Page>,
539 tx: &mut PoolTx<'_>,
540 ) -> Result<(), TreeError> {
541 let self_id = page_id(self)?;
542 let new_id_path = match new_parent {
543 Some(np) => MaterializedPath::child_of(&np.path, self_id)?.into_string(),
544 None => MaterializedPath::root(self_id)?.into_string(),
545 };
546 if new_id_path == self.path {
547 return Ok(());
548 }
549 let old_prefix = self.path.clone();
550
551 let new_sort_order = match new_parent {
556 Some(np) => {
557 let np_id = page_id(np)?;
558 let _locked_parent: Vec<Page> = Page::objects()
559 .where_(Page::id.eq(np_id))
560 .select_for_update()
561 .silent_on_sqlite()
562 .fetch_tx(tx)
563 .await?;
564 next_child_sort_order_tx(tx, np_id).await?
565 }
566 None => next_root_sort_order_tx(tx).await?,
567 };
568
569 self.parent_id = new_parent.and_then(|p| p.id.get().copied());
570 self.sort_order = new_sort_order;
571 self.depth = depth_of(&new_id_path);
572 self.path = new_id_path.clone();
573 self.url_path = compute_url_path(new_parent.map(|p| p.url_path.as_str()), &self.slug);
577 self.save_tx(tx).await?;
578
579 let mut url_of: std::collections::HashMap<i64, String> = std::collections::HashMap::new();
582 url_of.insert(self_id, self.url_path.clone());
583 for mut row in subtree {
584 let suffix = row
585 .path
586 .strip_prefix(&old_prefix)
587 .expect("descendant path must start with old prefix");
588 row.path = format!("{new_id_path}{suffix}");
589 row.depth = depth_of(&row.path);
590 let parent_url = row.parent_id.and_then(|pid| url_of.get(&pid).cloned());
591 row.url_path = compute_url_path(parent_url.as_deref(), &row.slug);
592 if let Some(id) = row.id.get().copied() {
593 url_of.insert(id, row.url_path.clone());
594 }
595 row.save_tx(tx).await?;
596 }
597 Ok(())
598 }
599}
600
601fn page_id(page: &Page) -> Result<i64, TreeError> {
604 page.id.get().copied().ok_or(TreeError::MissingId)
605}
606
607async fn next_root_sort_order_tx(tx: &mut PoolTx<'_>) -> Result<i32, TreeError> {
622 let _lock: Vec<Page> = Page::objects()
623 .where_(Page::parent_id.is_null())
624 .order_by(&[("id", false)])
625 .limit(1)
626 .select_for_update()
627 .silent_on_sqlite()
628 .fetch_tx(tx)
629 .await?;
630 let rows = Page::objects()
631 .where_(Page::parent_id.is_null())
632 .order_by(&[("sort_order", true)])
633 .fetch_tx(tx)
634 .await?;
635 Ok(rows.first().map(|p| p.sort_order + 1).unwrap_or(0))
636}
637
638async fn next_child_sort_order_tx(tx: &mut PoolTx<'_>, parent_id: i64) -> Result<i32, TreeError> {
644 let rows = Page::objects()
645 .where_(Page::parent_id.eq(parent_id))
646 .order_by(&[("sort_order", true)])
647 .fetch_tx(tx)
648 .await?;
649 Ok(rows.first().map(|p| p.sort_order + 1).unwrap_or(0))
650}
651
652pub async fn validate_child_placement(
667 pool: &Pool,
668 parent_type_id: i64,
669 child_type_id: i64,
670) -> Result<(), TreeError> {
671 let rows: Vec<PageType> = PageType::objects()
672 .where_(PageType::id.is_in([parent_type_id, child_type_id]))
673 .fetch(pool)
674 .await?;
675
676 let parent = rows
677 .iter()
678 .find(|r| r.id.get().copied() == Some(parent_type_id))
679 .ok_or(TreeError::UnknownPageType(parent_type_id))?;
680 let child = rows
681 .iter()
682 .find(|r| r.id.get().copied() == Some(child_type_id))
683 .ok_or(TreeError::UnknownPageType(child_type_id))?;
684
685 if find_handler(&parent.type_name).is_some_and(|h| h.is_leaf()) {
687 return Err(TreeError::DisallowedChildType {
688 parent_type: parent.type_name.clone(),
689 child_type: child.type_name.clone(),
690 });
691 }
692 let allowed = parent.allowed_children();
694 if !allowed.is_empty() && !allowed.iter().any(|t| *t == child.type_name) {
695 return Err(TreeError::DisallowedChildType {
696 parent_type: parent.type_name.clone(),
697 child_type: child.type_name.clone(),
698 });
699 }
700 let allowed = child.allowed_parents();
701 if !allowed.is_empty() && !allowed.iter().any(|t| *t == parent.type_name) {
702 return Err(TreeError::DisallowedParentType {
703 parent_type: parent.type_name.clone(),
704 child_type: child.type_name.clone(),
705 });
706 }
707
708 Ok(())
709}
710
711impl MaterializedPath {
714 pub fn ancestors_of(path: &str) -> Vec<String> {
715 let mut out = Vec::new();
716 let mut acc = String::new();
717 for seg in path.split(crate::tree::SEPARATOR).filter(|s| !s.is_empty()) {
718 acc.push_str(seg);
719 acc.push(crate::tree::SEPARATOR);
720 if acc != path {
721 out.push(acc.clone());
722 }
723 }
724 if let Some(last) = out.last() {
725 if last == path {
726 out.pop();
727 }
728 }
729 out
730 }
731}
732
733#[cfg(all(test, feature = "sqlite"))]
738mod atomic_tree_tests {
739 use super::*;
740 use rustango::sql::Pool;
741 use std::sync::atomic::{AtomicBool, Ordering};
742 use std::sync::Arc;
743
744 async fn mem_pool() -> Pool {
745 Pool::connect("sqlite::memory:")
746 .await
747 .expect("sqlite in-memory pool")
748 }
749
750 #[tokio::test]
751 async fn commit_returns_value_and_fires_on_commit() {
752 let pool = mem_pool().await;
753 let fired = Arc::new(AtomicBool::new(false));
754 let f = fired.clone();
755 let out = atomic_tree(&pool, move |_tx| {
756 Box::pin(async move {
757 rustango::sql::on_commit(move || f.store(true, Ordering::SeqCst));
758 Ok::<i32, TreeError>(7)
759 })
760 })
761 .await;
762 assert_eq!(out.expect("commit"), 7);
763 assert!(
766 fired.load(Ordering::SeqCst),
767 "on_commit must fire on commit"
768 );
769 }
770
771 #[tokio::test]
772 async fn tree_error_propagates_unchanged_and_drops_on_commit() {
773 let pool = mem_pool().await;
774 let fired = Arc::new(AtomicBool::new(false));
775 let f = fired.clone();
776 let out: Result<(), TreeError> = atomic_tree(&pool, move |_tx| {
777 Box::pin(async move {
778 rustango::sql::on_commit(move || f.store(true, Ordering::SeqCst));
779 Err(TreeError::CycleAttempt)
780 })
781 })
782 .await;
783 assert!(matches!(out, Err(TreeError::CycleAttempt)), "got {out:?}");
786 assert!(
787 !fired.load(Ordering::SeqCst),
788 "on_commit must be dropped on a TreeError rollback"
789 );
790 }
791}