laravel-nestedset 0.2.2

Nested set trees for Laravel Rust models: fast subtree and ancestor queries, safe under concurrent writes.
Documentation
//! Rearranging a tree from a nested list of keys, such as a drag-and-drop editor sends.

use std::collections::{HashMap, HashSet};

use laravel::db::IntoExpr;
use laravel::model::__query;
use serde::{Deserialize, Serialize};

use crate::check::write_rebuilt;
use crate::error::NestedSetError;
use crate::event::{TreeChange, changed};
use crate::locks::Locks;
use crate::node::NestedSet;
use crate::ops::{ATTEMPTS, connection, find};

/// A node's place in a new arrangement: its key and its children, in order. It deserializes from
/// the JSON a drag-and-drop tree editor sends, with the key as `key` or `id`:
///
/// ```json
/// [{ "id": 1, "children": [{ "id": 3 }, { "id": 2, "children": [] }] }]
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Arrangement<K> {
    /// The node's key.
    #[serde(alias = "id")]
    pub key: K,
    /// The node's children, in order.
    #[serde(default)]
    pub children: Vec<Arrangement<K>>,
}

impl<K> Arrangement<K> {
    /// The node with `key`, without children yet.
    pub fn new(key: K) -> Self {
        Self {
            key,
            children: Vec::new(),
        }
    }

    /// Adds `children` after the node's other children.
    #[must_use]
    pub fn children(mut self, children: impl IntoIterator<Item = Arrangement<K>>) -> Self {
        self.children.extend(children);
        self
    }
}

/// A listed node still to place, with the parent it goes under.
type Pending<K> = (Arrangement<K>, Option<K>);

/// Puts the listed nodes where `items` says, under `anchor` or as roots, and rebuilds the tree.
pub(crate) async fn arrange<M: NestedSet>(anchor: Option<&M>, items: Vec<Arrangement<M::Key>>) -> laravel::Result<u64>
where
    Option<M::Key>: IntoExpr,
{
    // Each listed node's parent and its place in the list, depth first.
    let anchor_key = anchor.map(|anchor| anchor.node_key().clone());
    let mut placed: HashMap<M::Key, (Option<M::Key>, usize)> = HashMap::new();
    let mut stack: Vec<Pending<M::Key>> = items.into_iter().rev().map(|item| (item, anchor_key.clone())).collect();
    while let Some((item, parent)) = stack.pop() {
        let order = placed.len();
        if placed.insert(item.key.clone(), (parent, order)).is_some() {
            return Err(NestedSetError::DuplicateKey {
                model: M::META.name,
                key: item.key.to_string(),
            }
            .into());
        }
        let key = item.key;
        stack.extend(item.children.into_iter().rev().map(|child| (child, Some(key.clone()))));
    }
    let Some(first) = placed.keys().next().cloned() else {
        return Ok(0);
    };

    // The tree, read before the transaction: inside it, every read comes after the locks.
    let scope = match anchor {
        Some(anchor) => anchor.scope(),
        None => find::<M>(&first).await?.scope(),
    };
    connection::<M>()?
        .transaction_with_attempts(ATTEMPTS, async |tx| {
            let mut locks = Locks::open::<M>(tx).await?;
            locks.roots::<M>(tx).await?;
            locks.tree(tx, &scope).await?;
            let tree = locks
                .fresh(scope.apply(__query::<M>()))
                .order_by(M::lft_column().asc())
                .get()
                .await?;

            let present: HashSet<&M::Key> = tree.iter().map(NestedSet::node_key).collect();
            if let Some(missing) = placed.keys().find(|key| !present.contains(key)) {
                return Err(NestedSetError::NodeNotFound {
                    model: M::META.name,
                    key: missing.to_string(),
                }
                .into());
            }
            if let Some(anchor_key) = &anchor_key {
                let anchor = tree.iter().find(|node| node.node_key() == anchor_key).ok_or_else(|| {
                    NestedSetError::NodeNotFound {
                        model: M::META.name,
                        key: anchor_key.to_string(),
                    }
                })?;
                // The anchor can't go below itself: it and its ancestors stay out of the list.
                if let Some(around) = tree
                    .iter()
                    .find(|node| placed.contains_key(node.node_key()) && anchor.is_descendant_of(node))
                    .or_else(|| placed.contains_key(anchor_key).then_some(anchor))
                {
                    return Err(NestedSetError::MoveIntoOwnSubtree {
                        model: M::META.name,
                        key: around.node_key().to_string(),
                        target: anchor_key.to_string(),
                    }
                    .into());
                }
            }

            // Listed nodes come first among their siblings, in the list's order; the others keep
            // their order after them.
            let mut ordered: Vec<&M> = tree.iter().collect();
            ordered.sort_by_key(|node| placed.get(node.node_key()).map_or(usize::MAX, |(_, order)| *order));
            let nodes: Vec<M> = ordered.into_iter().cloned().collect();
            let parents: Vec<Option<M::Key>> = nodes
                .iter()
                .map(|node| match placed.get(node.node_key()) {
                    Some((parent, _)) => parent.clone(),
                    None => node.parent_key().cloned(),
                })
                .collect();
            let changed_rows = write_rebuilt(&nodes, &parents).await?;
            changed::<M>(TreeChange::Arranged, None).await?;
            locks.release_after_commit(tx).await?;
            Ok(changed_rows)
        })
        .await
}