laraindexnow 0.1.2

IndexNow for Laravel Rust: tell Bing, Yandex and other search engines a URL changed, the moment it changes.
Documentation
use laravel::container::{Inject, Registrar};
use laravel::event::Event;
use laravel::model::{Created, Deleted, Model, Updated};

use crate::manager::IndexNow;
use crate::record::{Change, ChangeKind, Record};
use crate::registration::Registration;
use crate::support::config;

/// Observe the three model events Laravel Rust dispatches for a model: created, updated and
/// deleted. They already wait for the surrounding transaction to commit, so a rolled back write
/// never reaches a search engine.
pub(crate) fn listen<M: Model>(app: &mut Registrar) {
    app.events()
        .listen(created::<M>)
        .listen(updated::<M>)
        .listen(deleted::<M>);
}

async fn created<M: Model>(event: Event<Created<M>>, manager: Inject<IndexNow>) -> laravel::Result<()> {
    process(&manager, &event.model, ChangeKind::Created, None, &[]).await;

    Ok(())
}

async fn updated<M: Model>(event: Event<Updated<M>>, manager: Inject<IndexNow>) -> laravel::Result<()> {
    let before = Record::before(&event.model, &event.changes);
    let changed: Vec<&'static str> = event.changes.columns().collect();

    process(&manager, &event.model, ChangeKind::Updated, Some(before), &changed).await;

    Ok(())
}

async fn deleted<M: Model>(event: Event<Deleted<M>>, manager: Inject<IndexNow>) -> laravel::Result<()> {
    process(
        &manager,
        &event.model,
        ChangeKind::Deleted,
        Some(Record::of(&event.model)),
        &[],
    )
    .await;

    Ok(())
}

/// Decide what a write announces and submit it.
///
/// A failure is reported and never returned: announcing a URL is never worth losing the write it
/// was announcing, so an error here must not reach the code that saved the record.
async fn process<M: Model>(
    manager: &IndexNow,
    model: &M,
    kind: ChangeKind,
    before: Option<Record>,
    changed: &[&'static str],
) {
    if !manager.enabled() || manager.paused() {
        return;
    }

    if let Err(error) = announce(manager, model, kind, before, changed).await {
        laravel::report(error);
    }
}

async fn announce<M: Model>(
    manager: &IndexNow,
    model: &M,
    kind: ChangeKind,
    before: Option<Record>,
    changed: &[&'static str],
) -> laravel::Result<()> {
    let registrations = manager.registry().for_model::<M>();

    if registrations.is_empty() {
        return Ok(());
    }

    let after = Record::of(model);
    let change = Change {
        kind,
        after: &after,
        before: before.as_ref(),
    };

    // Registrations are an OR: each one is asked on its own, and the first that wants this write
    // is enough. A record that can become worth indexing through more than one route is declared
    // as one registration per route, which keeps every route's conditions an AND of its own.
    let mut urls: Vec<String> = Vec::new();
    let mut setting: Vec<&Registration<M>> = Vec::new();

    for registration in registrations {
        if !wants(registration, &change, changed) {
            continue;
        }

        let current = registration.url_of(model, &after)?;

        if let Some(url) = &current {
            urls.push(url.clone());
        }

        if kind == ChangeKind::Updated
            && let Some(previous) = before.as_ref().and_then(|before| registration.previous_url_of(before))
            && current.as_ref() != Some(&previous)
        {
            urls.push(previous);
        }

        urls.extend(registration.affected_urls(model));
        setting.push(registration);
    }

    if urls.is_empty() {
        return Ok(());
    }

    let mut unique: Vec<String> = Vec::with_capacity(urls.len());

    for url in urls {
        if !unique.contains(&url) {
            unique.push(url);
        }
    }

    manager.submit(unique).await?;

    for registration in setting {
        registration.apply_set(model).await?;
    }

    Ok(())
}

fn wants<M: Model>(registration: &Registration<M>, change: &Change<'_>, changed: &[&'static str]) -> bool {
    // A transition rule, when there is one, decides on its own: it can see both states, so it
    // knows things the indexable predicate cannot.
    if let Some(decision) = registration.decide(change) {
        return decision;
    }

    // Resolved per registration, never cached across them: each one has its own conditions, so
    // each one has its own idea of what indexable means.
    let was = match change.kind {
        ChangeKind::Created => false,
        _ => change.before.is_some_and(|before| registration.passes(before)),
    };

    let is = match change.kind {
        ChangeKind::Deleted => false,
        _ => registration.passes(change.after),
    };

    if !was && !is {
        return false;
    }

    !(was && is && !content_changed::<M>(registration, changed))
}

fn content_changed<M: Model>(registration: &Registration<M>, changed: &[&'static str]) -> bool {
    let mut ignored = config().ignored_attributes;

    ignored.extend(registration.ignored_attributes());
    ignored.extend(M::META.created_at.map(|stamp| stamp.name.to_owned()));
    ignored.extend(M::META.updated_at.map(|stamp| stamp.name.to_owned()));

    changed.iter().any(|column| !ignored.iter().any(|name| name == column))
}