laravel-nestedset 0.2.3

Nested set trees for Laravel Rust models: fast subtree and ancestor queries, safe under concurrent writes.
Documentation
//! The service provider and the `nestedset:check` and `nestedset:fix` console commands.

use std::future::Future;
use std::pin::Pin;

use laravel::console::{Console, clap};
use laravel::container::{Inject, Registrar};
use laravel::db::IntoExpr;
use laravel::foundation::ServiceProvider;

use crate::node::NestedSet;

type Boxed<T> = Pin<Box<dyn Future<Output = laravel::Result<T>> + Send>>;

/// The broken nodes of one table, by kind, as text keys.
type Findings = Vec<(&'static str, Vec<String>)>;

/// A registered model: its table and type-erased `check_tree` and `fix_tree`.
#[derive(Clone, Copy)]
struct Entry {
    table: &'static str,
    check: fn() -> Boxed<Findings>,
    fix: fn() -> Boxed<u64>,
}

fn check<M: NestedSet>() -> Boxed<Findings> {
    Box::pin(async {
        let report = M::check_tree().await?;
        let keys = |keys: Vec<M::Key>| keys.iter().map(ToString::to_string).collect::<Vec<_>>();
        Ok(vec![
            ("bad bounds", keys(report.oddness)),
            ("shared bounds", keys(report.duplicates)),
            ("parent_id doesn't match the bounds", keys(report.wrong_parent)),
            ("parent_id points to no node", keys(report.missing_parent)),
        ])
    })
}

fn fix<M: NestedSet>() -> Boxed<u64>
where
    Option<M::Key>: IntoExpr,
{
    Box::pin(M::fix_tree())
}

/// The models the console commands work on.
struct NestedSetModels(Vec<Entry>);

impl NestedSetModels {
    /// The models named by `table`, or all of them when `table` is `None`.
    fn select(&self, table: Option<&str>) -> Vec<Entry> {
        self.0
            .iter()
            .filter(|entry| table.is_none_or(|table| entry.table == table))
            .copied()
            .collect()
    }
}

/// Registers the `nestedset:check` and `nestedset:fix` commands for the models you list.
///
/// ```no_run
/// # use laravel::model::{Column, model};
/// # use laravel_nestedset::NestedSet;
/// # #[model]
/// # pub struct Category {
/// #     pub id: i64,
/// #     #[default]
/// #     pub lft: i64,
/// #     #[default]
/// #     pub rgt: i64,
/// #     pub parent_id: Option<i64>,
/// # }
/// # impl NestedSet for Category {
/// #     fn lft_column() -> Column<Self, i64> { Category::lft }
/// #     fn rgt_column() -> Column<Self, i64> { Category::rgt }
/// #     fn parent_column() -> Column<Self, Option<i64>> { Category::parent_id }
/// # }
/// use laravel::Application;
/// use laravel_nestedset::NestedSetServiceProvider;
///
/// Application::configure().with_providers(|providers| {
///     providers.add(NestedSetServiceProvider::new().model::<Category>());
/// });
/// ```
///
/// ```shell
/// laravel nestedset:check             # every registered table; exits with 1 when one is broken
/// laravel nestedset:check categories  # one table
/// laravel nestedset:fix categories    # rebuild the bounds from parent_id
/// ```
#[derive(Clone, Default)]
pub struct NestedSetServiceProvider {
    models: Vec<Entry>,
}

impl NestedSetServiceProvider {
    /// A provider without models yet.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds the model `M`: the commands name it by its table.
    #[must_use]
    pub fn model<M: NestedSet>(mut self) -> Self
    where
        Option<M::Key>: IntoExpr,
    {
        self.models.push(Entry {
            table: M::META.table,
            check: check::<M>,
            fix: fix::<M>,
        });
        self
    }
}

impl ServiceProvider for NestedSetServiceProvider {
    fn register(&self, app: &mut Registrar) {
        app.instance(NestedSetModels(self.models.clone()));
        let commands = app.commands();
        commands.add::<CheckCommand>();
        commands.add::<FixCommand>();
    }
}

/// Check nested set trees for broken nodes.
#[derive(clap::Parser)]
#[command(name = "nestedset:check")]
struct CheckCommand {
    /// The table to check, such as `categories`. Every registered table when left out.
    table: Option<String>,
}

#[laravel::console::command]
impl CheckCommand {
    async fn handle(self, console: &mut Console, models: Inject<NestedSetModels>) -> laravel::Result<u8> {
        let Some(entries) = selected(&models, self.table.as_deref(), console) else {
            return Ok(2);
        };
        let mut broken = false;
        for entry in entries {
            let findings = (entry.check)().await?;
            if findings.iter().all(|(_, keys)| keys.is_empty()) {
                console.success(format!("`{}` is valid.", entry.table));
                continue;
            }
            broken = true;
            console.error(format!("`{}` is broken.", entry.table));
            for (kind, keys) in findings.into_iter().filter(|(_, keys)| !keys.is_empty()) {
                console.line(format!("  {kind}: {}", shorten(&keys)));
            }
        }
        if broken {
            console.info("Run `nestedset:fix` to rebuild the bounds from parent_id.");
        }
        Ok(u8::from(broken))
    }
}

/// Rebuild the bounds of nested set trees from `parent_id`.
#[derive(clap::Parser)]
#[command(name = "nestedset:fix")]
struct FixCommand {
    /// The table to fix, such as `categories`. Every registered table when left out.
    table: Option<String>,
}

#[laravel::console::command]
impl FixCommand {
    async fn handle(self, console: &mut Console, models: Inject<NestedSetModels>) -> laravel::Result<u8> {
        let Some(entries) = selected(&models, self.table.as_deref(), console) else {
            return Ok(2);
        };
        for entry in entries {
            match (entry.fix)().await? {
                0 => console.success(format!("`{}` needed no changes.", entry.table)),
                changed => console.success(format!("`{}`: fixed {changed} rows.", entry.table)),
            }
        }
        Ok(0)
    }
}

/// The models a command runs on, or `None` after telling the user that nothing matches.
fn selected(models: &NestedSetModels, table: Option<&str>, console: &mut Console) -> Option<Vec<Entry>> {
    let entries = models.select(table);
    if !entries.is_empty() {
        return Some(entries);
    }
    match table {
        Some(table) => console.error(format!(
            "No nested set model uses the table `{table}`. Add it with `NestedSetServiceProvider::model`."
        )),
        None => console.error("No nested set models are registered. Add them with `NestedSetServiceProvider::model`."),
    }
    None
}

/// The first keys of a list, with a count of the rest.
fn shorten(keys: &[String]) -> String {
    const SHOWN: usize = 20;
    let shown = keys.iter().take(SHOWN).cloned().collect::<Vec<_>>().join(", ");
    match keys.len().saturating_sub(SHOWN) {
        0 => shown,
        more => format!("{shown} and {more} more"),
    }
}