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::io::Read;
use std::sync::Arc;

use async_trait::async_trait;
use flate2::read::GzDecoder;
use laravel::http::client;
use laravel::time::{Timestamp, ToSpan};
use quick_xml::Reader;
use quick_xml::events::Event;

use crate::source::{Page, Source};
use crate::support::config;
use crate::tracked::{Tracked, instant};
use crate::value::Attr;

/// A tracked model with `publishes_at`, as a source: the rows whose publish date or change date
/// falls inside the window and is not in the future.
pub struct ModelSource {
    tracked: Arc<dyn Tracked>,
}

impl ModelSource {
    /// A source for one registration.
    pub fn new(tracked: Arc<dyn Tracked>) -> Self {
        Self { tracked }
    }
}

#[async_trait]
impl Source for ModelSource {
    fn name(&self) -> String {
        format!("the {} registration", self.tracked.model_name())
    }

    async fn changed_since(&self, since: Timestamp) -> laravel::Result<Vec<Page>> {
        self.tracked.changed_since(since, laravel::now().timestamp()).await
    }
}

/// A sitemap, or a sitemap index, as a source.
///
/// A URL is returned when its `<lastmod>` falls inside the window. URLs without a `<lastmod>` are
/// ignored: the sitemap does not say when they changed, and treating them as changed would
/// announce the whole site on every run. A gzip compressed sitemap is read as it is stored.
pub struct SitemapSource {
    url: String,
}

/// How many sitemap indexes deep the source follows.
const MAX_DEPTH: usize = 3;

impl SitemapSource {
    /// A source for the sitemap at `url`.
    pub fn new(url: impl Into<String>) -> Self {
        Self { url: url.into() }
    }

    async fn fetch(&self, url: &str) -> laravel::Result<String> {
        let response = client::get(url)
            .timeout((config().timeout as i64).seconds())
            .await
            .map_err(|error| laravel::Error::msg(format!("Could not fetch the sitemap [{url}]: {error}")))?;

        if !response.successful() {
            return Err(laravel::Error::msg(format!(
                "Could not fetch the sitemap [{url}]: it answered {}.",
                response.status().as_u16()
            )));
        }

        let bytes = response.bytes();

        if bytes.starts_with(&[0x1f, 0x8b]) {
            let mut body = String::new();

            GzDecoder::new(bytes.as_ref())
                .read_to_string(&mut body)
                .map_err(|error| laravel::Error::msg(format!("The sitemap at [{url}] is not valid gzip: {error}")))?;

            return Ok(body);
        }

        String::from_utf8(bytes.to_vec())
            .map_err(|_| laravel::Error::msg(format!("The sitemap at [{url}] is not valid UTF-8.")))
    }
}

#[async_trait]
impl Source for SitemapSource {
    fn name(&self) -> String {
        format!("the sitemap at {}", self.url)
    }

    async fn changed_since(&self, since: Timestamp) -> laravel::Result<Vec<Page>> {
        let until = laravel::now().timestamp();
        let mut pages = Vec::new();
        let mut visited: Vec<String> = Vec::new();
        let mut pending = vec![(self.url.clone(), 0_usize)];

        while let Some((url, depth)) = pending.pop() {
            if depth >= MAX_DEPTH || visited.contains(&url) {
                continue;
            }

            visited.push(url.clone());

            match parse(&url, &self.fetch(&url).await?)? {
                Sitemap::Index(children) => {
                    for child in children.into_iter().rev() {
                        pending.push((child, depth + 1));
                    }
                }
                Sitemap::Urls(entries) => {
                    for (loc, lastmod) in entries {
                        let Some(changed_at) = lastmod.and_then(|value| instant(&Attr::Text(value))) else {
                            continue;
                        };

                        if changed_at < since || changed_at > until {
                            continue;
                        }

                        if !(loc.starts_with("http://") || loc.starts_with("https://")) {
                            continue;
                        }

                        pages.push(Page::new(loc, changed_at));
                    }
                }
            }
        }

        Ok(pages)
    }
}

enum Sitemap {
    Index(Vec<String>),
    Urls(Vec<(String, Option<String>)>),
}

/// Read a sitemap's entries. Entities are never expanded beyond the five XML predefines, so a
/// hostile document cannot make the parser fetch or inflate anything.
fn parse(url: &str, body: &str) -> laravel::Result<Sitemap> {
    let invalid = || laravel::Error::msg(format!("The sitemap at [{url}] is not valid XML."));
    let mut reader = Reader::from_str(body);
    let mut root: Option<String> = None;
    let mut path: Vec<String> = Vec::new();
    let mut loc: Option<String> = None;
    let mut lastmod: Option<String> = None;
    let mut entries: Vec<(String, Option<String>)> = Vec::new();

    loop {
        match reader.read_event().map_err(|_| invalid())? {
            Event::Start(element) => {
                let name = String::from_utf8_lossy(element.local_name().as_ref()).into_owned();

                if root.is_none() {
                    root = Some(name.clone());
                }

                if name == "url" || name == "sitemap" {
                    loc = None;
                    lastmod = None;
                }

                path.push(name);
            }
            Event::End(_) => {
                if let Some(name) = path.pop()
                    && (name == "url" || name == "sitemap")
                    && let Some(found) = loc.take()
                {
                    entries.push((found, lastmod.take()));
                }
            }
            Event::Text(text) => {
                let text = text.unescape().map_err(|_| invalid())?.trim().to_owned();

                capture(&path, text, &mut loc, &mut lastmod);
            }
            Event::CData(data) => {
                let text = String::from_utf8_lossy(&data).trim().to_owned();

                capture(&path, text, &mut loc, &mut lastmod);
            }
            Event::Eof => break,
            _ => {}
        }
    }

    match root.as_deref() {
        Some("sitemapindex") => Ok(Sitemap::Index(entries.into_iter().map(|(loc, _)| loc).collect())),
        Some("urlset") => Ok(Sitemap::Urls(entries)),
        _ => Err(laravel::Error::msg(format!(
            "The sitemap at [{url}] is neither a <urlset> nor a <sitemapindex>."
        ))),
    }
}

fn capture(path: &[String], text: String, loc: &mut Option<String>, lastmod: &mut Option<String>) {
    if text.is_empty() {
        return;
    }

    let [.., parent, leaf] = path else {
        return;
    };

    if parent != "url" && parent != "sitemap" {
        return;
    }

    match leaf.as_str() {
        "loc" => *loc = Some(text),
        "lastmod" => *lastmod = Some(text),
        _ => {}
    }
}