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

use laravel::config::{Config, Env};
use laravel::container::{Container, Inject, Registrar};
use laravel::foundation::ServiceProvider;
use laravel::model::Model;
use laravel::prelude::Request;

use crate::config::IndexNowConfig;
use crate::keys::KeyRepository;
use crate::manager::IndexNow;
use crate::observer;
use crate::registration::Registration;
use crate::source::Source;
use crate::tracked::Registry;

/// Wires IndexNow into the application: configuration, the service, the key file route, the
/// commands, the queue jobs and the model observers.
///
/// ```ignore
/// Application::configure().with_providers(|providers| {
///     providers.add(
///         IndexNowServiceProvider::new()
///             .track(
///                 indexnow::track::<Post>()
///                     .url_template("https://example.com/blog/{slug}")
///                     .when_holds("status", "published"),
///             )
///             .sitemap("https://example.com/sitemap.xml"),
///     );
/// })
/// ```
#[derive(Clone, Default)]
pub struct IndexNowServiceProvider {
    registry: Registry,
    sources: Vec<Arc<dyn Source>>,
    observed: Vec<TypeId>,
    observers: Vec<fn(&mut Registrar)>,
}

impl IndexNowServiceProvider {
    /// A provider that tracks nothing yet.
    pub fn new() -> Self {
        Self::default()
    }

    /// Track a model. Tracking the same model again adds a second registration, and registrations
    /// combine with OR. The model is observed once however many it has.
    #[must_use]
    pub fn track<M: Model>(mut self, registration: Registration<M>) -> Self {
        if !self.observed.contains(&TypeId::of::<M>()) {
            self.observed.push(TypeId::of::<M>());
            self.observers.push(observer::listen::<M>);
        }

        self.registry.add(registration);

        self
    }

    /// Add a source for `indexnow:due`.
    #[must_use]
    pub fn source(mut self, source: impl Source + 'static) -> Self {
        self.sources.push(Arc::new(source));

        self
    }

    /// Add a sitemap, or a sitemap index, as a source for `indexnow:due`.
    #[must_use]
    pub fn sitemap(self, url: impl Into<String>) -> Self {
        self.source(crate::sources::SitemapSource::new(url))
    }
}

impl ServiceProvider for IndexNowServiceProvider {
    fn config(&self, config: &mut Config, env: &Env) {
        config.discover(env!("CARGO_CRATE_NAME"), env);
    }

    fn register(&self, app: &mut Registrar) {
        IndexNow::register(app, Arc::new(self.registry.clone()), self.sources.clone());

        for observe in &self.observers {
            observe(app);
        }

        app.discover(env!("CARGO_CRATE_NAME"));

        // Laravel Rust 0.1 does not allow text after a route parameter, so `/{key}.txt` cannot be one
        // route. The keys are known when the application registers its routes, so each gets its own.
        let section = app.config().section::<IndexNowConfig>().clone();
        let mut keys: Vec<String> = section.key.iter().chain(section.keys.values()).cloned().collect();

        keys.sort();
        keys.dedup();

        if section.serve_key_file && !keys.is_empty() {
            app.routing().web(move |route| {
                for key in keys.iter().filter(|key| KeyRepository::is_valid(key)) {
                    route.get(&format!("/{key}.txt"), key_file);
                }
            });
        }
    }

    async fn boot(&self, _app: &Container) -> laravel::Result<()> {
        self.registry.validate()
    }
}

/// `GET /{key}.txt`: the key file, answered with the key of whichever host was requested.
pub async fn key_file(manager: Inject<IndexNow>, request: Request) -> laravel::Result<String> {
    let host = request.host();
    let keys = manager.keys();
    let requested = request
        .path()
        .trim_start_matches('/')
        .trim_end_matches(".txt")
        .to_owned();

    match keys.for_host(&host) {
        Some(configured) if configured == requested && keys.allows(&host) => Ok(configured),
        _ => Err(laravel::abort(404)),
    }
}