Skip to main content

rustango_cms/
tree_ops.rs

1//! Tree mutation + read API on top of [`Page`].
2//!
3//! All operations are dialect-agnostic. Read-only queries accept
4//! `&rustango::sql::Pool`. Write operations that require atomic
5//! transactions (`create_root`, `create_child`, `move_to`,
6//! `cascade_url_path_to_descendants`) open a `PoolTx` via
7//! `write_transaction(&tenant.pool())` and use the `_tx` ORM helpers.
8//!
9//! Path generation is two-step: the materialized-path segment is the
10//! row's auto-assigned id, which we don't know until after INSERT. To
11//! avoid the brief window where `path = ""`, every create wraps the
12//! insert + path update in a transaction.
13//!
14//! `move_to` also takes a transaction because it rewrites every row
15//! in the moved subtree atomically.
16//!
17//! `created_at` / `updated_at` are framework-stamped (`auto_now_add`
18//! / `auto_now`); callers don't fill them.
19
20use 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/// Errors from tree operations.
33#[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
69/// Run `f` inside a framework [`rustango::sql::atomic`] scope while
70/// letting it return [`TreeError`] — the bridge that lets the
71/// `on_commit` cache-invalidation pattern reach the tree-write paths.
72///
73/// `rustango::sql::atomic` fixes its closure's error to [`ExecError`],
74/// but the tree helpers (`cascade_url_path_to_descendants`, `move_to`,
75/// …) speak `TreeError`, and there's no `TreeError -> ExecError`
76/// conversion (only the reverse, via [`TreeError::Db`]). This adapter
77/// closes that gap: a `TreeError` from `f` is stashed and a sentinel
78/// `ExecError` is returned to drive `atomic`'s rollback, then the real
79/// error is recovered afterwards. Recovery keys off the **stash**, not
80/// the sentinel value, so a genuine `ExecError` raised by `BEGIN` /
81/// `COMMIT` itself is never misread as a domain error.
82///
83/// `on_commit` callbacks queued by `f` (e.g. via
84/// [`crate::cache_invalidate::invalidate_urls_on_commit`]) fire only on
85/// the commit path — a `TreeError` rolls the transaction back and drops
86/// them, exactly like a native `atomic` block.
87///
88/// The cleaner long-term fix is a generic `atomic` in the framework
89/// (closure returning `Result<T, E: From<ExecError>>`); until that
90/// lands, this adapter keeps the rollout unblocked.
91///
92/// # Errors
93/// The first [`TreeError`] returned by `f`, or a `BEGIN` / `COMMIT`
94/// driver error surfaced as [`TreeError::Db`].
95pub 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                    // Sentinel: any ExecError drives atomic's rollback;
117                    // the value is never read (recovery uses the stash).
118                    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/// Builder for the user-supplied fields when creating a page. Tree
134/// fields (path, depth, parent_id, sort_order) and timestamps are
135/// computed by the create_* helpers — callers don't fill them.
136#[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        // #251 — first_published_at + last_published_at mirror on
172        // first publish (same instant). Subsequent edits bump only
173        // `last_published_at`; `published_at` stays as the
174        // chronological-ordering anchor.
175        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            // Empty means "follow url_path" — a new page inherits the
184            // frontend's default routing until someone says otherwise.
185            preview_path: String::new(),
186            // Empty means "use the page type's template" — a new page
187            // looks like its type until someone overrides it.
188            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
216/// Compute the public URL path a page is reachable at,
217/// given its parent's `url_path` (or `None` for root) and its own
218/// slug. Maintained on every create / slug-change / move.
219///
220/// Invariants:
221/// - Always starts with `/`.
222/// - No trailing slash, except for the empty-slug root which is `/`.
223/// - Empty slug under a non-root parent is treated as "use parent's
224///   path" (rare but useful for landing pages that share a parent's
225///   URL). Use sparingly — the resolver picks the highest-priority
226///   match among equal URLs.
227pub fn compute_url_path(parent_url_path: Option<&str>, slug: &str) -> String {
228    match parent_url_path {
229        None => {
230            // Root page.
231            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
249/// Recompute and persist `url_path` for every
250/// descendant of `root_page` after its own `url_path` changes.
251///
252/// Walks in path order so each descendant's parent has been updated
253/// before the descendant itself is processed. Caches each updated
254/// `(id → url_path)` in-memory to avoid re-fetching parents. Runs
255/// inside `conn` so callers can wrap the whole self-edit + cascade
256/// in one transaction.
257///
258/// # Errors
259/// Driver / query failures or ORM save errors.
260pub 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
297/// Recompute `url_path` for every page in the tenant
298/// from scratch. Walks all pages in `path` order so parents update
299/// before children. Useful as a one-shot recovery / backfill verb
300/// when external SQL has touched `cms_page` outside the admin.
301///
302/// # Errors
303/// Driver / query failures or ORM save errors.
304pub async fn rebuild_all_url_paths(pool: &Pool) -> Result<usize, TreeError> {
305    // #317 — stream pages in `path` order (a materialized path sorts
306    // parents before their children) in chunks rather than materializing
307    // every `Page` row up front: a 10k+ page tenant would otherwise
308    // buffer the entire tree of full Page structs in memory at once.
309    // Each page is only needed transiently to recompute its `url_path`;
310    // the sole cross-row state is the compact id→url_path map for parent
311    // lookups, so chunked iteration keeps peak memory bounded to one
312    // chunk + that map. Recomputing `url_path` never mutates `path` (the
313    // ORDER BY / cursor key), so the LIMIT/OFFSET window stays stable
314    // across chunks — no row is skipped or visited twice.
315    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    /// Insert a new root page. Returns the persisted row with `id`,
342    /// `path`, `depth`, and `sort_order` populated.
343    pub async fn create_root(tenant: &Tenant, new: NewPage) -> Result<Self, TreeError> {
344        Self::create_root_pool(tenant.pool(), new).await
345    }
346
347    /// Backend-agnostic [`Self::create_root`] — takes a `&Pool` directly,
348    /// so content can be seeded / scripted outside an HTTP request on any
349    /// dialect. `create_root` needs a `&Tenant`, but `Tenant` is only
350    /// publicly constructible on Postgres (test-gated), leaving no way to
351    /// seed pages on SQLite/MySQL; this is that way.
352    pub async fn create_root_pool(pool: &Pool, new: NewPage) -> Result<Self, TreeError> {
353        let mut tx = write_transaction(pool).await?;
354        // #317 — compute sort_order inside the tx under a FOR UPDATE lock
355        // on the existing roots so concurrent root inserts can't read the
356        // same max and collide.
357        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    /// Append a new child under `parent`. Sort order is the next
374    /// integer after the parent's existing children.
375    ///
376    /// Validates the type constraint in both directions before
377    /// inserting: the parent's `allowed_child_types` must permit
378    /// the child's type, and the child's `allowed_parent_types`
379    /// must permit the parent's type. Either failure short-circuits
380    /// the write.
381    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    /// Backend-agnostic [`Self::create_child`] — takes a `&Pool` directly
390    /// so content can be seeded / scripted outside an HTTP request on any
391    /// dialect (see [`Self::create_root_pool`]).
392    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        // #317 — serialize concurrent inserts under this parent. Lock the
402        // parent row (FOR UPDATE) so a second create_child blocks until
403        // the first commits; otherwise both read the same
404        // MAX(sort_order) and write duplicate sort_orders. Locking the
405        // parent (not the sibling set) covers the first child too, when
406        // there are no siblings to lock. The lock is held for the whole
407        // tx — dropping the result Vec doesn't release it. On SQLite the
408        // tx is opened with `write_transaction`, whose up-front write lock
409        // does the same job.
410        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    /// Immediate children, ordered by `sort_order`.
433    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    /// Pages that share this page's parent (excluding self), ordered
444    /// by `sort_order`. Roots return all other roots.
445    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    /// All ancestors of this page from root → immediate parent.
459    /// Empty for roots. Order is root-first.
460    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    /// All descendants (excluding self), ordered by `path` (which is
475    /// also tree-pre-order).
476    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    /// Move this page (and its entire subtree) under `new_parent`. Pass
488    /// `None` to promote it to a root. The subtree's `url_path`s follow in
489    /// the same transaction, so the tree and the URLs never disagree.
490    ///
491    /// Refuses cycles (moving under self or a descendant) and
492    /// type-constraint violations (re-checks both directions against
493    /// the new parent before writing).
494    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    /// Transaction-scoped core of [`move_to`](Self::move_to). Assumes cycle / placement
525    /// validation has already run and `subtree` (this page's descendants)
526    /// was read on the pool **before** the transaction opened — so this
527    /// makes **no pool reads**. That matters: reading the pool while
528    /// holding a tx connection can deadlock a single-connection SQLite
529    /// pool. Pre-reading lets a batch (bulk move) reparent many pages in
530    /// one transaction.
531    ///
532    /// # Errors
533    /// Driver errors from the lock / saves, or [`TreeError`] from path
534    /// math.
535    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        // #317 — compute the destination sort_order inside the tx, under a
552        // FOR UPDATE lock on the new parent row (or the roots set when
553        // promoting to a root), so a concurrent insert/move into the same
554        // parent can't hand out a duplicate sort_order.
555        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        // #706 — the URL moves with the tree, in this transaction. It used
574        // to be left to the admin handler, in a second transaction a
575        // library caller never ran, so a moved subtree kept its old URLs.
576        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        // `subtree` is in path order, so a parent's new URL is known
580        // before its children's.
581        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
601// ---------- helpers ----------
602
603fn page_id(page: &Page) -> Result<i64, TreeError> {
604    page.id.get().copied().ok_or(TreeError::MissingId)
605}
606
607/// Next `sort_order` for a new root, read inside `tx` after taking a
608/// `FOR UPDATE` lock on **one** deterministic root row (the lowest id) so
609/// concurrent root inserts serialize.
610///
611/// Roots have no parent row to lock, but we must NOT lock the whole roots
612/// set: concurrent transactions acquire the multiple row locks in
613/// conflicting orders and PG aborts one with a deadlock (40P01). Locking a
614/// single, always-the-same row (lowest id) can't deadlock — every tx
615/// contends on that one row — mirroring `create_child`'s single-parent
616/// lock. The subsequent max read is serialized by that lock.
617///
618/// Empty roots → nothing to lock → a narrow gap when the first couple of
619/// roots are created concurrently (rare; acceptable). `FOR UPDATE` is a
620/// no-op on SQLite, where callers open the tx with `write_transaction`.
621async 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
638/// Next `sort_order` for a new child of `parent_id`, read inside `tx`.
639/// The caller locks the parent row with `FOR UPDATE` first (see
640/// [`Page::create_child`]), which serializes every insert under that
641/// parent — including the first child, when no siblings exist to lock —
642/// so this is a plain read of the current max.
643async 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
652/// Check that the (parent_type, child_type) pairing is permitted by
653/// both handlers' whitelists. Skipped when either type's whitelist is
654/// empty (the convention for "no restriction"). Public to make it
655/// usable from admin form hooks and other write paths.
656///
657/// Fetches both `cms_page_type` rows in a single `WHERE id IN (..)`
658/// query, then dispatches to the in-process handler registry for the
659/// declared whitelists.
660///
661/// # Errors
662/// * [`TreeError::UnknownPageType`] when either id doesn't resolve to
663///   a `cms_page_type` row.
664/// * [`TreeError::DisallowedChildType`] when the parent rejects.
665/// * [`TreeError::DisallowedParentType`] when the child rejects.
666pub 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    // #448 — a leaf type (code only) accepts no children at all.
686    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    // The rows hold both lists for code and admin-made types alike (#843).
693    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
711// MaterializedPath::ancestors() returns Vec<String>; we want a static-style
712// helper available without an instance for the `ancestors` query above.
713impl 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// `atomic_tree`'s commit/rollback behavior is exercised against a
734// serverless SQLite-in-memory pool, so it's gated on the `sqlite`
735// feature:
736//   cargo test --lib --no-default-features --features sqlite atomic_tree
737#[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        // on_commit callbacks drain synchronously after COMMIT, before
764        // `atomic` returns — so the flag is already set here.
765        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        // The original `TreeError` is recovered from the stash — not the
784        // `ExecError` sentinel (which would surface as `TreeError::Db`).
785        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}