laraindexnow 0.1.0

IndexNow for Laravel Rust: tell Bing, Yandex and other search engines a URL changed, the moment it changes.
Documentation
use std::any::{Any, TypeId};
use std::marker::PhantomData;
use std::sync::Arc;

use async_trait::async_trait;
use laravel::db::col;
use laravel::model::Model;
use laravel::stream::StreamExt;
use laravel::time::{Timestamp, civil};

use crate::record::Record;
use crate::registration::Registration;
use crate::source::Page;
use crate::value::Attr;

/// One registration, with the model it tracks erased. `indexnow:models` and the model source read
/// registrations through it.
#[async_trait]
pub trait Tracked: Send + Sync {
    /// The model's struct name, such as `Post`.
    fn model_name(&self) -> &'static str;

    /// The model's type.
    fn model_type(&self) -> TypeId;

    /// How the registration is configured, for `indexnow:models`.
    fn describe(&self) -> String;

    /// The registration itself, to get its typed form back.
    fn as_any(&self) -> &dyn Any;

    /// Whether the registration can resolve a URL: it has a resolver or a policy.
    fn has_url(&self) -> bool;

    /// The column named by `publishes_at`.
    fn publish_column(&self) -> Option<String>;

    /// The column named by `changes_at`.
    fn change_column(&self) -> Option<String>;

    /// The pages whose publish or change date falls between `since` and `until`.
    async fn changed_since(&self, since: Timestamp, until: Timestamp) -> laravel::Result<Vec<Page>>;
}

/// Receives the URLs `indexnow:sync` collects, a batch at a time.
#[async_trait]
pub trait UrlSink: Send {
    /// Handle a batch. Returns how many URLs were accepted.
    async fn send(&mut self, urls: Vec<String>) -> laravel::Result<usize>;
}

/// How `indexnow:sync` walks a table.
#[derive(Debug, Clone)]
pub struct ScanOptions {
    /// Rows read per query.
    pub chunk: u64,
    /// URLs collected before each batch goes to the sink.
    pub batch: usize,
    /// Stop after this many rows.
    pub limit: Option<u64>,
    /// Never write `sets` attributes.
    pub dry_run: bool,
}

/// What a scan found.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Scan {
    /// Rows read.
    pub seen: u64,
    /// Rows that belong in the index.
    pub matched: u64,
    /// URLs the sink accepted.
    pub submitted: u64,
}

/// Walks every row of one model, whatever the number of registrations it has.
#[async_trait]
pub trait ModelDriver: Send + Sync {
    /// The model's struct name, such as `Post`.
    fn model_name(&self) -> &'static str;

    /// The model's full type name.
    fn type_name(&self) -> &'static str;

    /// How many rows a scan would read.
    async fn count(&self, limit: Option<u64>) -> laravel::Result<u64>;

    /// Read the table, evaluate every registration of the model against each row and hand the
    /// URLs of the rows that belong in the index to `sink`.
    async fn scan(&self, registry: &Registry, options: &ScanOptions, sink: &mut dyn UrlSink) -> laravel::Result<Scan>;
}

/// Every registration of the application, and one driver per tracked model.
#[derive(Default, Clone)]
pub struct Registry {
    tracked: Vec<Arc<dyn Tracked>>,
    drivers: Vec<(TypeId, Arc<dyn ModelDriver>)>,
}

impl Registry {
    /// Add a registration. Registrations of the same model combine with OR.
    pub fn add<M: Model>(&mut self, registration: Registration<M>) {
        let id = TypeId::of::<M>();

        if !self.drivers.iter().any(|(existing, _)| *existing == id) {
            self.drivers.push((id, Arc::new(Driver::<M>(PhantomData))));
        }

        self.tracked.push(Arc::new(registration));
    }

    /// Whether this model has a registration.
    pub fn tracks<M: Model>(&self) -> bool {
        self.tracked
            .iter()
            .any(|tracked| tracked.model_type() == TypeId::of::<M>())
    }

    /// The registrations of a model, in the order they were added.
    pub fn for_model<M: Model>(&self) -> Vec<&Registration<M>> {
        self.tracked
            .iter()
            .filter_map(|tracked| tracked.as_any().downcast_ref::<Registration<M>>())
            .collect()
    }

    /// Every registration, in the order they were added.
    pub fn tracked(&self) -> &[Arc<dyn Tracked>] {
        &self.tracked
    }

    /// The driver of a model, by struct name (`Post`, case insensitive) or full type name.
    pub fn driver(&self, name: &str) -> Option<Arc<dyn ModelDriver>> {
        self.drivers
            .iter()
            .map(|(_, driver)| driver)
            .find(|driver| driver.type_name() == name || driver.model_name().eq_ignore_ascii_case(name))
            .cloned()
    }

    /// Whether anything is tracked.
    pub fn is_empty(&self) -> bool {
        self.tracked.is_empty()
    }

    /// Catch the registrations that can never work, so the application refuses to start instead
    /// of missing submissions in production.
    ///
    /// # Errors
    ///
    /// Fails when a registration has neither a URL resolver nor a policy, or when `changes_at` is
    /// used without `publishes_at`.
    pub fn validate(&self) -> laravel::Result<()> {
        for tracked in &self.tracked {
            if !tracked.has_url() {
                return Err(laravel::Error::msg(format!(
                    "No IndexNow URL resolver defined for [{}]. Call url() or url_template() on the registration, or give it a policy.",
                    tracked.model_name()
                )));
            }

            if tracked.change_column().is_some() && tracked.publish_column().is_none() {
                return Err(laravel::Error::msg(format!(
                    "changes_at() on [{}] needs publishes_at(): without it the registration is not a source.",
                    tracked.model_name()
                )));
            }
        }

        Ok(())
    }
}

#[async_trait]
impl<M: Model> Tracked for Registration<M> {
    fn model_name(&self) -> &'static str {
        M::META.name
    }

    fn model_type(&self) -> TypeId {
        TypeId::of::<M>()
    }

    fn describe(&self) -> String {
        Registration::describe(self)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn has_url(&self) -> bool {
        Registration::has_url(self)
    }

    fn publish_column(&self) -> Option<String> {
        Registration::publish_column(self).map(str::to_owned)
    }

    fn change_column(&self) -> Option<String> {
        Registration::change_column(self).map(str::to_owned)
    }

    async fn changed_since(&self, since: Timestamp, until: Timestamp) -> laravel::Result<Vec<Page>> {
        let columns: Vec<String> = [self.publish_column(), self.change_column()]
            .into_iter()
            .flatten()
            .map(str::to_owned)
            .collect();

        let mut window = None;

        for column in &columns {
            let within = col(column).ge(since) & col(column).le(until);

            window = Some(match window {
                Some(existing) => existing | within,
                None => within,
            });
        }

        let Some(window) = window else {
            return Ok(Vec::new());
        };

        let mut rows = laravel::model::__query::<M>().filter(window).lazy_by_id(500);
        let mut pages = Vec::new();

        while let Some(row) = rows.next().await {
            let row = row?;
            let record = Record::of(&row);

            let Some(changed_at) = columns
                .iter()
                .filter_map(|column| instant(record.get(column)))
                .filter(|date| *date >= since && *date <= until)
                .max()
            else {
                continue;
            };

            if !self.passes(&record) {
                continue;
            }

            let mut urls: Vec<String> = self.url_of(&row, &record)?.into_iter().collect();
            urls.extend(self.affected_urls(&row));
            urls.dedup();

            for url in urls {
                pages.push(Page::new(url, changed_at));
            }
        }

        Ok(pages)
    }
}

struct Driver<M>(PhantomData<fn() -> M>);

#[async_trait]
impl<M: Model> ModelDriver for Driver<M> {
    fn model_name(&self) -> &'static str {
        M::META.name
    }

    fn type_name(&self) -> &'static str {
        std::any::type_name::<M>()
    }

    async fn count(&self, limit: Option<u64>) -> laravel::Result<u64> {
        let count = laravel::model::__query::<M>().count().await?;

        Ok(limit.map_or(count, |limit| count.min(limit)))
    }

    async fn scan(&self, registry: &Registry, options: &ScanOptions, sink: &mut dyn UrlSink) -> laravel::Result<Scan> {
        let registrations = registry.for_model::<M>();
        let mut scan = Scan::default();
        let mut urls: Vec<String> = Vec::new();
        let mut marks: Vec<(usize, M)> = Vec::new();
        let mut chunks = laravel::model::__query::<M>().chunk_by_id(options.chunk.max(1));

        'rows: while let Some(chunk) = chunks.next().await {
            for row in chunk? {
                scan.seen += 1;

                let record = Record::of(&row);
                let mut row_urls: Vec<String> = Vec::new();

                for (index, registration) in registrations.iter().enumerate() {
                    if !registration.passes(&record) {
                        continue;
                    }

                    if let Some(url) = registration.url_of(&row, &record)?
                        && !row_urls.contains(&url)
                    {
                        row_urls.push(url);
                    }

                    if registration.has_sets() && !options.dry_run {
                        marks.push((index, row.clone()));
                    }
                }

                if !row_urls.is_empty() {
                    scan.matched += 1;
                    urls.extend(row_urls);
                }

                if urls.len() >= options.batch.max(1) {
                    scan.submitted += flush(registrations.as_slice(), sink, &mut urls, &mut marks).await?;
                }

                if options.limit.is_some_and(|limit| scan.seen >= limit) {
                    break 'rows;
                }
            }
        }

        if !urls.is_empty() {
            scan.submitted += flush(registrations.as_slice(), sink, &mut urls, &mut marks).await?;
        }

        Ok(scan)
    }
}

async fn flush<M: Model>(
    registrations: &[&Registration<M>],
    sink: &mut dyn UrlSink,
    urls: &mut Vec<String>,
    marks: &mut Vec<(usize, M)>,
) -> laravel::Result<u64> {
    let sent = sink.send(std::mem::take(urls)).await?;

    for (index, row) in std::mem::take(marks) {
        registrations[index].apply_set(&row).await?;
    }

    Ok(sent as u64)
}

/// A column value read as a point in time.
pub fn instant(value: &Attr) -> Option<Timestamp> {
    match value {
        Attr::Time(timestamp) => Some(*timestamp),
        Attr::Int(seconds) => Timestamp::from_second(*seconds).ok(),
        Attr::Text(text) => text
            .parse::<Timestamp>()
            .ok()
            .or_else(|| {
                text.parse::<civil::DateTime>()
                    .ok()
                    .and_then(|date| date.in_tz("UTC").ok())
                    .map(|zoned| zoned.timestamp())
            })
            .or_else(|| {
                text.parse::<civil::Date>()
                    .ok()
                    .and_then(|date| date.in_tz("UTC").ok())
                    .map(|zoned| zoned.timestamp())
            }),
        _ => None,
    }
}