laravel-nestedset 0.3.0

Nested set trees for Laravel Rust models: fast subtree and ancestor queries, safe under concurrent writes.
Documentation
//! Checking a table's trees for broken bounds and rebuilding the bounds from `parent_id`.

use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;

use laravel::db::sqlx::AssertSqlSafe;
use laravel::db::{self, IntoExpr, Values};
use laravel::model::__query;

use crate::chain::integer_key;
use crate::event::{TreeChange, changed};
use crate::locks::Locks;
use crate::node::NestedSet;
use crate::ops::{ATTEMPTS, connection, quote, untouched};

/// What [`NestedSet::check_tree`] found: the keys of the broken nodes, by kind of damage.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TreeReport<K> {
    /// Nodes whose bounds can't be right: `lft` below 1, `lft >= rgt`, or an even width.
    pub oddness: Vec<K>,
    /// Nodes that share a bound with another node of their tree.
    pub duplicates: Vec<K>,
    /// Nodes whose `parent_id` isn't the nearest node around them.
    pub wrong_parent: Vec<K>,
    /// Nodes whose `parent_id` names a row that isn't in their tree.
    pub missing_parent: Vec<K>,
    /// Nodes whose stored depth doesn't match their place, when the model has a
    /// [`depth_column`](NestedSet::depth_column).
    pub wrong_depth: Vec<K>,
}

impl<K> TreeReport<K> {
    /// Whether any node is broken.
    #[must_use]
    pub fn is_broken(&self) -> bool {
        !(self.oddness.is_empty()
            && self.duplicates.is_empty()
            && self.wrong_parent.is_empty()
            && self.missing_parent.is_empty()
            && self.wrong_depth.is_empty())
    }
}

/// Splits the table's rows into their trees, each in bound order.
async fn trees<M: NestedSet>(locks: Option<&Locks>) -> laravel::Result<Vec<Vec<M>>> {
    let query = __query::<M>();
    let query = match locks {
        Some(locks) => locks.fresh(query),
        None => query,
    };
    let rows = query
        .order_by(M::lft_column().asc())
        .order_by(M::META.key.asc())
        .get()
        .await?;
    let mut order: Vec<String> = Vec::new();
    let mut trees: HashMap<String, Vec<M>> = HashMap::new();
    for row in rows {
        let name = row.scope().lock_name();
        if !trees.contains_key(&name) {
            order.push(name.clone());
        }
        trees.entry(name).or_default().push(row);
    }
    Ok(order.into_iter().filter_map(|name| trees.remove(&name)).collect())
}

pub(crate) async fn check_tree<M: NestedSet>() -> laravel::Result<TreeReport<M::Key>> {
    let mut report = TreeReport {
        oddness: Vec::new(),
        duplicates: Vec::new(),
        wrong_parent: Vec::new(),
        missing_parent: Vec::new(),
        wrong_depth: Vec::new(),
    };
    for tree in trees::<M>(None).await? {
        check(&tree, &mut report);
    }
    Ok(report)
}

/// Checks one tree, whose nodes are in bound order.
fn check<M: NestedSet>(nodes: &[M], report: &mut TreeReport<M::Key>) {
    let keys: HashSet<&M::Key> = nodes.iter().map(NestedSet::node_key).collect();
    let mut seen: HashMap<i64, usize> = HashMap::new();
    for node in nodes {
        *seen.entry(node.lft()).or_default() += 1;
        *seen.entry(node.rgt()).or_default() += 1;
    }

    // The nodes still open around the current one, innermost last.
    let mut open: Vec<&M> = Vec::new();
    for node in nodes {
        let key = node.node_key();
        let odd = node.lft() < 1 || node.lft() >= node.rgt() || (node.rgt() - node.lft()) % 2 == 0;
        if odd {
            report.oddness.push(key.clone());
        }
        if seen[&node.lft()] > 1 || seen[&node.rgt()] > 1 {
            report.duplicates.push(key.clone());
        }
        while open.last().is_some_and(|around| around.rgt() < node.lft()) {
            open.pop();
        }
        let around = open
            .last()
            .filter(|around| around.rgt() > node.rgt())
            .map(|around| around.node_key());
        match node.parent_key() {
            Some(parent) if !keys.contains(parent) => report.missing_parent.push(key.clone()),
            parent if !odd && around != parent => report.wrong_parent.push(key.clone()),
            _ => {}
        }
        if let Some(column) = M::depth_column() {
            let depth = open.iter().filter(|around| around.rgt() > node.rgt()).count();
            if !odd && usize::try_from(*column.get(node)).ok() != Some(depth) {
                report.wrong_depth.push(key.clone());
            }
        }
        if !odd {
            open.push(node);
        }
    }
}

pub(crate) async fn fix_tree<M: NestedSet>() -> laravel::Result<u64>
where
    Option<M::Key>: IntoExpr,
{
    // Which trees there are, read before the transaction: inside it, every read comes after the
    // locks.
    let mut scopes: Vec<_> = trees::<M>(None).await?.iter().map(|tree| tree[0].scope()).collect();
    scopes.sort_by_key(crate::scope::Scope::lock_name);
    connection::<M>()?
        .transaction_with_attempts(ATTEMPTS, async |tx| {
            let mut locks = Locks::open::<M>(tx).await?;
            locks.roots::<M>(tx).await?;
            for scope in &scopes {
                locks.tree(tx, scope).await?;
            }
            let trees = trees::<M>(Some(&locks)).await?;
            let mut fixed = 0;
            for tree in &trees {
                let parents: Vec<Option<M::Key>> = tree.iter().map(|node| node.parent_key().cloned()).collect();
                fixed += write_rebuilt(tree, &parents).await?;
            }
            if fixed > 0 {
                changed::<M>(TreeChange::Fixed, None).await?;
            }
            locks.release_after_commit(tx).await?;
            Ok(fixed)
        })
        .await
}

/// Writes the bounds, parent, and depth [`rebuild`] works out for one tree to the rows that
/// differ, and returns how many it changed. `parents[i]` is the parent `nodes[i]` should have;
/// siblings keep the order of `nodes`.
pub(crate) async fn write_rebuilt<M: NestedSet>(nodes: &[M], parents: &[Option<M::Key>]) -> laravel::Result<u64>
where
    Option<M::Key>: IntoExpr,
{
    let changed: Vec<(&M, Rebuilt<M::Key>)> = rebuild(nodes, parents)
        .into_iter()
        .filter(|(node, rebuilt)| {
            (rebuilt.lft, rebuilt.rgt, rebuilt.parent.as_ref()) != (node.lft(), node.rgt(), node.parent_key())
                || M::depth_column().is_some_and(|column| *column.get(*node) != rebuilt.depth)
        })
        .collect();
    let keys: Option<Vec<i64>> = changed.iter().map(|(node, _)| integer_key(*node)).collect();
    match keys {
        Some(keys) => write_in_batches(&changed, &keys).await?,
        None => write_one_by_one(&changed).await?,
    }
    Ok(changed.len() as u64)
}

/// The nodes that get each new parent.
type ByParent<K> = Vec<(Option<K>, Vec<K>)>;

/// Rows per batched `UPDATE`.
const BATCH: usize = 1_000;

/// Writes integer-keyed rows a thousand at a time: one `UPDATE` with a `CASE` per column for the
/// bounds and depth, whose SQL holds only integers, and one bound `UPDATE` per new parent.
async fn write_in_batches<M: NestedSet>(changed: &[(&M, Rebuilt<M::Key>)], keys: &[i64]) -> laravel::Result<()>
where
    Option<M::Key>: IntoExpr,
{
    let driver = connection::<M>()?.driver();
    let key = quote(driver, M::META.key.name());
    for (rows, keys) in changed.chunks(BATCH).zip(keys.chunks(BATCH)) {
        let case = |value: &dyn Fn(&Rebuilt<M::Key>) -> i64, column: &str| {
            let mut arms = String::new();
            for ((_, rebuilt), key) in rows.iter().zip(keys) {
                let _ = write!(arms, " WHEN {key} THEN {}", value(rebuilt));
            }
            let column = quote(driver, column);
            db::raw!(AssertSqlSafe(format!("CASE {key}{arms} ELSE {column} END")))
        };
        let mut values = Values::new()
            .set(
                M::lft_column().name(),
                case(&|rebuilt| rebuilt.lft, M::lft_column().name()),
            )
            .set(
                M::rgt_column().name(),
                case(&|rebuilt| rebuilt.rgt, M::rgt_column().name()),
            );
        if let Some(column) = M::depth_column() {
            values = values.set(column.name(), case(&|rebuilt| rebuilt.depth, column.name()));
        }
        __query::<M>()
            .filter(M::META.key.is_in(rows.iter().map(|(node, _)| node.node_key().clone())))
            .update_values(untouched::<M>(values))
            .await?;
    }

    let mut by_parent: ByParent<M::Key> = Vec::new();
    for (node, rebuilt) in changed
        .iter()
        .filter(|(node, rebuilt)| rebuilt.parent.as_ref() != node.parent_key())
    {
        match by_parent.iter_mut().find(|(parent, _)| *parent == rebuilt.parent) {
            Some((_, nodes)) => nodes.push(node.node_key().clone()),
            None => by_parent.push((rebuilt.parent.clone(), vec![node.node_key().clone()])),
        }
    }
    for (parent, nodes) in by_parent {
        for chunk in nodes.chunks(BATCH) {
            let values = Values::new().set(M::parent_column().name(), parent.clone());
            __query::<M>()
                .filter(M::META.key.is_in(chunk.iter().cloned()))
                .update_values(untouched::<M>(values))
                .await?;
        }
    }
    Ok(())
}

/// Writes each row with its own `UPDATE`, for keys that aren't integers.
async fn write_one_by_one<M: NestedSet>(changed: &[(&M, Rebuilt<M::Key>)]) -> laravel::Result<()>
where
    Option<M::Key>: IntoExpr,
{
    for (node, rebuilt) in changed {
        let mut values = Values::new()
            .set(M::lft_column().name(), rebuilt.lft)
            .set(M::rgt_column().name(), rebuilt.rgt)
            .set(M::parent_column().name(), rebuilt.parent.clone());
        if let Some(column) = M::depth_column() {
            values = values.set(column.name(), rebuilt.depth);
        }
        __query::<M>()
            .filter(M::META.key.eq(node.node_key().clone()))
            .update_values(untouched::<M>(values))
            .await?;
    }
    Ok(())
}

/// Where a node belongs, as [`rebuild`] works it out.
struct Rebuilt<K> {
    lft: i64,
    rgt: i64,
    depth: i64,
    parent: Option<K>,
}

/// The bounds and parent each node of one tree should have, from `parent_id`. Siblings keep their
/// current order. A node whose parent is missing, or that sits in a `parent_id` cycle, becomes a
/// root.
fn rebuild<'a, M: NestedSet>(nodes: &'a [M], parents: &[Option<M::Key>]) -> Vec<(&'a M, Rebuilt<M::Key>)> {
    let positions: HashMap<&M::Key, usize> = nodes
        .iter()
        .enumerate()
        .map(|(index, node)| (node.node_key(), index))
        .collect();
    let mut children: HashMap<usize, Vec<usize>> = HashMap::new();
    let mut tops = Vec::new();
    for (index, parent) in parents.iter().enumerate() {
        match parent.as_ref().and_then(|parent| positions.get(parent)) {
            Some(&parent) if parent != index => children.entry(parent).or_default().push(index),
            _ => tops.push(index),
        }
    }

    let mut result = Vec::with_capacity(nodes.len());
    let mut visited = vec![false; nodes.len()];
    let mut bound = 0;
    // Nodes no top reaches sit in a cycle: each one left over starts a tree of its own.
    let starts: Vec<usize> = tops.into_iter().chain(0..nodes.len()).collect();
    for start in starts {
        if visited[start] {
            continue;
        }
        // Depth-first: (node, parent, whether its children are done).
        let mut stack = vec![(start, None::<usize>, false)];
        let mut lfts: HashMap<usize, (i64, i64)> = HashMap::new();
        while let Some((index, parent, done)) = stack.pop() {
            if done {
                bound += 1;
                let parent_key = parent.map(|parent| nodes[parent].node_key().clone());
                let (lft, depth) = lfts[&index];
                result.push((
                    &nodes[index],
                    Rebuilt {
                        lft,
                        rgt: bound,
                        depth,
                        parent: parent_key,
                    },
                ));
                continue;
            }
            if visited[index] {
                continue;
            }
            visited[index] = true;
            bound += 1;
            let depth = parent.map_or(0, |parent| lfts[&parent].1 + 1);
            lfts.insert(index, (bound, depth));
            stack.push((index, parent, true));
            if let Some(below) = children.get(&index) {
                for &child in below.iter().rev() {
                    if !visited[child] {
                        stack.push((child, Some(index), false));
                    }
                }
            }
        }
    }
    result
}