1use chrono::Utc;
21use rustango::core::Column as _;
22use rustango::extractors::Tenant;
23use rustango::sql::{
24 sqlx, transaction_pool, 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 = transaction_pool(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 = transaction_pool(pool).await?;
401 let _locked_parent: Vec<Page> = Page::objects()
410 .where_(Page::id.eq(parent_id))
411 .select_for_update()
412 .fetch_tx(&mut tx)
413 .await?;
414 let sort_order = next_child_sort_order_tx(&mut tx, parent_id).await?;
415 let mut page = new.into_page(Some(parent_id), sort_order);
416
417 page.insert_tx(&mut tx).await?;
418 let id = page_id(&page)?;
419
420 let path = MaterializedPath::child_of(&parent.path, id)?;
421 page.depth = path.depth();
422 page.path = path.into_string();
423 page.url_path = compute_url_path(Some(parent.url_path.as_str()), &page.slug);
424 page.save_tx(&mut tx).await?;
425 tx.commit().await?;
426
427 Ok(page)
428 }
429
430 pub async fn children(&self, pool: &Pool) -> Result<Vec<Page>, TreeError> {
432 let id = page_id(self)?;
433 let rows = Page::objects()
434 .where_(Page::parent_id.eq(id))
435 .order_by(&[("sort_order", false), ("id", false)])
436 .fetch(pool)
437 .await?;
438 Ok(rows)
439 }
440
441 pub async fn siblings(&self, pool: &Pool) -> Result<Vec<Page>, TreeError> {
444 let id = page_id(self)?;
445 let qs = Page::objects().order_by(&[("sort_order", false), ("id", false)]);
446 let rows = match self.parent_id {
447 Some(pid) => qs.where_(Page::parent_id.eq(pid)).fetch(pool).await?,
448 None => qs.where_(Page::parent_id.is_null()).fetch(pool).await?,
449 };
450 Ok(rows
451 .into_iter()
452 .filter(|p| p.id.get().copied() != Some(id))
453 .collect())
454 }
455
456 pub async fn ancestors(&self, pool: &Pool) -> Result<Vec<Page>, TreeError> {
459 let paths = MaterializedPath::ancestors_of(&self.path);
460 if paths.is_empty() {
461 return Ok(Vec::new());
462 }
463 let mut rows = Page::objects()
464 .where_(Page::path.is_in(paths.iter().cloned()))
465 .order_by(&[("path", false)])
466 .fetch(pool)
467 .await?;
468 rows.sort_by(|a, b| a.path.cmp(&b.path));
469 Ok(rows)
470 }
471
472 pub async fn descendants(&self, pool: &Pool) -> Result<Vec<Page>, TreeError> {
475 let pattern = descendants_like(&self.path);
476 let rows = Page::objects()
477 .where_(Page::path.like(pattern))
478 .where_(Page::path.ne(self.path.clone()))
479 .order_by(&[("path", false)])
480 .fetch(pool)
481 .await?;
482 Ok(rows)
483 }
484
485 pub async fn move_to(
493 &mut self,
494 tenant: &Tenant,
495 new_parent: Option<&Page>,
496 ) -> Result<(), TreeError> {
497 let self_id = page_id(self)?;
498
499 if let Some(np) = new_parent {
500 let np_id = page_id(np)?;
501 if np_id == self_id || np.path.starts_with(&self.path) {
502 return Err(TreeError::CycleAttempt);
503 }
504 validate_child_placement(tenant.pool(), np.page_type_id, self.page_type_id).await?;
505 }
506
507 let new_id_path = match new_parent {
508 Some(np) => MaterializedPath::child_of(&np.path, self_id)?.into_string(),
509 None => MaterializedPath::root(self_id)?.into_string(),
510 };
511 if new_id_path == self.path {
512 return Ok(());
513 }
514
515 let subtree = self.descendants(tenant.pool()).await?;
516 let mut tx = transaction_pool(tenant.pool()).await?;
517 self.move_to_in_tx(new_parent, subtree, &mut tx).await?;
518 tx.commit().await?;
519 Ok(())
520 }
521
522 pub async fn move_to_in_tx(
534 &mut self,
535 new_parent: Option<&Page>,
536 subtree: Vec<Page>,
537 tx: &mut PoolTx<'_>,
538 ) -> Result<(), TreeError> {
539 let self_id = page_id(self)?;
540 let new_id_path = match new_parent {
541 Some(np) => MaterializedPath::child_of(&np.path, self_id)?.into_string(),
542 None => MaterializedPath::root(self_id)?.into_string(),
543 };
544 if new_id_path == self.path {
545 return Ok(());
546 }
547 let old_prefix = self.path.clone();
548
549 let new_sort_order = match new_parent {
554 Some(np) => {
555 let np_id = page_id(np)?;
556 let _locked_parent: Vec<Page> = Page::objects()
557 .where_(Page::id.eq(np_id))
558 .select_for_update()
559 .fetch_tx(tx)
560 .await?;
561 next_child_sort_order_tx(tx, np_id).await?
562 }
563 None => next_root_sort_order_tx(tx).await?,
564 };
565
566 self.parent_id = new_parent.and_then(|p| p.id.get().copied());
567 self.sort_order = new_sort_order;
568 self.depth = depth_of(&new_id_path);
569 self.path = new_id_path.clone();
570 self.url_path = compute_url_path(new_parent.map(|p| p.url_path.as_str()), &self.slug);
574 self.save_tx(tx).await?;
575
576 let mut url_of: std::collections::HashMap<i64, String> = std::collections::HashMap::new();
579 url_of.insert(self_id, self.url_path.clone());
580 for mut row in subtree {
581 let suffix = row
582 .path
583 .strip_prefix(&old_prefix)
584 .expect("descendant path must start with old prefix");
585 row.path = format!("{new_id_path}{suffix}");
586 row.depth = depth_of(&row.path);
587 let parent_url = row.parent_id.and_then(|pid| url_of.get(&pid).cloned());
588 row.url_path = compute_url_path(parent_url.as_deref(), &row.slug);
589 if let Some(id) = row.id.get().copied() {
590 url_of.insert(id, row.url_path.clone());
591 }
592 row.save_tx(tx).await?;
593 }
594 Ok(())
595 }
596}
597
598fn page_id(page: &Page) -> Result<i64, TreeError> {
601 page.id.get().copied().ok_or(TreeError::MissingId)
602}
603
604async fn next_root_sort_order_tx(tx: &mut PoolTx<'_>) -> Result<i32, TreeError> {
619 let _lock: Vec<Page> = Page::objects()
620 .where_(Page::parent_id.is_null())
621 .order_by(&[("id", false)])
622 .limit(1)
623 .select_for_update()
624 .fetch_tx(tx)
625 .await?;
626 let rows = Page::objects()
627 .where_(Page::parent_id.is_null())
628 .order_by(&[("sort_order", true)])
629 .fetch_tx(tx)
630 .await?;
631 Ok(rows.first().map(|p| p.sort_order + 1).unwrap_or(0))
632}
633
634async fn next_child_sort_order_tx(tx: &mut PoolTx<'_>, parent_id: i64) -> Result<i32, TreeError> {
640 let rows = Page::objects()
641 .where_(Page::parent_id.eq(parent_id))
642 .order_by(&[("sort_order", true)])
643 .fetch_tx(tx)
644 .await?;
645 Ok(rows.first().map(|p| p.sort_order + 1).unwrap_or(0))
646}
647
648pub async fn validate_child_placement(
663 pool: &Pool,
664 parent_type_id: i64,
665 child_type_id: i64,
666) -> Result<(), TreeError> {
667 let rows: Vec<PageType> = PageType::objects()
668 .where_(PageType::id.is_in([parent_type_id, child_type_id]))
669 .fetch(pool)
670 .await?;
671
672 let parent = rows
673 .iter()
674 .find(|r| r.id.get().copied() == Some(parent_type_id))
675 .ok_or(TreeError::UnknownPageType(parent_type_id))?;
676 let child = rows
677 .iter()
678 .find(|r| r.id.get().copied() == Some(child_type_id))
679 .ok_or(TreeError::UnknownPageType(child_type_id))?;
680
681 if find_handler(&parent.type_name).is_some_and(|h| h.is_leaf()) {
683 return Err(TreeError::DisallowedChildType {
684 parent_type: parent.type_name.clone(),
685 child_type: child.type_name.clone(),
686 });
687 }
688 let allowed = parent.allowed_children();
690 if !allowed.is_empty() && !allowed.iter().any(|t| *t == child.type_name) {
691 return Err(TreeError::DisallowedChildType {
692 parent_type: parent.type_name.clone(),
693 child_type: child.type_name.clone(),
694 });
695 }
696 let allowed = child.allowed_parents();
697 if !allowed.is_empty() && !allowed.iter().any(|t| *t == parent.type_name) {
698 return Err(TreeError::DisallowedParentType {
699 parent_type: parent.type_name.clone(),
700 child_type: child.type_name.clone(),
701 });
702 }
703
704 Ok(())
705}
706
707impl MaterializedPath {
710 pub fn ancestors_of(path: &str) -> Vec<String> {
711 let mut out = Vec::new();
712 let mut acc = String::new();
713 for seg in path.split(crate::tree::SEPARATOR).filter(|s| !s.is_empty()) {
714 acc.push_str(seg);
715 acc.push(crate::tree::SEPARATOR);
716 if acc != path {
717 out.push(acc.clone());
718 }
719 }
720 if let Some(last) = out.last() {
721 if last == path {
722 out.pop();
723 }
724 }
725 out
726 }
727}
728
729#[cfg(all(test, feature = "sqlite"))]
734mod atomic_tree_tests {
735 use super::*;
736 use rustango::sql::Pool;
737 use std::sync::atomic::{AtomicBool, Ordering};
738 use std::sync::Arc;
739
740 async fn mem_pool() -> Pool {
741 Pool::connect("sqlite::memory:")
742 .await
743 .expect("sqlite in-memory pool")
744 }
745
746 #[tokio::test]
747 async fn commit_returns_value_and_fires_on_commit() {
748 let pool = mem_pool().await;
749 let fired = Arc::new(AtomicBool::new(false));
750 let f = fired.clone();
751 let out = atomic_tree(&pool, move |_tx| {
752 Box::pin(async move {
753 rustango::sql::on_commit(move || f.store(true, Ordering::SeqCst));
754 Ok::<i32, TreeError>(7)
755 })
756 })
757 .await;
758 assert_eq!(out.expect("commit"), 7);
759 assert!(
762 fired.load(Ordering::SeqCst),
763 "on_commit must fire on commit"
764 );
765 }
766
767 #[tokio::test]
768 async fn tree_error_propagates_unchanged_and_drops_on_commit() {
769 let pool = mem_pool().await;
770 let fired = Arc::new(AtomicBool::new(false));
771 let f = fired.clone();
772 let out: Result<(), TreeError> = atomic_tree(&pool, move |_tx| {
773 Box::pin(async move {
774 rustango::sql::on_commit(move || f.store(true, Ordering::SeqCst));
775 Err(TreeError::CycleAttempt)
776 })
777 })
778 .await;
779 assert!(matches!(out, Err(TreeError::CycleAttempt)), "got {out:?}");
782 assert!(
783 !fired.load(Ordering::SeqCst),
784 "on_commit must be dropped on a TreeError rollback"
785 );
786 }
787}