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::cache::{self, Repository};
use laravel::time::ToSpan;
use sha1::{Digest, Sha1};

use crate::config::IndexNowConfig;

/// The package's configuration, as the running application has it.
pub fn config() -> IndexNowConfig {
    laravel::config().section::<IndexNowConfig>().clone()
}

/// A cache store by name, or the default one.
pub fn store(name: Option<&str>) -> laravel::Result<Repository> {
    match name {
        Some(name) => cache::store(name),
        None => cache::manager().default_store(),
    }
}

/// The same URL is not submitted twice within the deduplication window.
///
/// The window is an anti-bounce measure, not a record of what is already indexed, so keep it
/// short.
pub struct Dedupe {
    cache: Repository,
    enabled: bool,
    ttl: u64,
    prefix: String,
}

impl Dedupe {
    /// Build it from the configuration.
    pub fn from_config(config: &IndexNowConfig) -> laravel::Result<Self> {
        Ok(Self {
            cache: store(config.buffer.store.as_deref())?,
            enabled: config.dedupe.enabled,
            ttl: config.dedupe.ttl,
            prefix: config.dedupe.prefix.clone(),
        })
    }

    /// Drop the URLs already submitted within the window.
    pub async fn filter(&self, urls: Vec<String>) -> laravel::Result<Vec<String>> {
        if !self.enabled {
            return Ok(urls);
        }

        let mut kept = Vec::with_capacity(urls.len());

        for url in urls {
            if !self.cache.has(&self.key(&url)).await? {
                kept.push(url);
            }
        }

        Ok(kept)
    }

    /// Remember that these URLs were submitted.
    pub async fn mark(&self, urls: &[String]) -> laravel::Result<()> {
        if !self.enabled || self.ttl == 0 {
            return Ok(());
        }

        for url in urls {
            self.cache
                .put(&self.key(url), true, (self.ttl as i64).seconds())
                .await?;
        }

        Ok(())
    }

    /// Forget that these URLs were submitted.
    pub async fn forget(&self, urls: &[String]) -> laravel::Result<()> {
        for url in urls {
            self.cache.forget(&self.key(url)).await?;
        }

        Ok(())
    }

    fn key(&self, url: &str) -> String {
        format!("{}{}", self.prefix, hex(&Sha1::digest(url.as_bytes())))
    }
}

fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}

/// The cache backed buffer that model events push URLs into.
pub struct UrlBuffer {
    cache: Repository,
    key: String,
    max: usize,
}

/// How long an unflushed buffer survives. A flush job normally empties it within a minute.
const BUFFER_LIFETIME_DAYS: i64 = 7;

impl UrlBuffer {
    /// Build it from the configuration.
    pub fn from_config(config: &IndexNowConfig) -> laravel::Result<Self> {
        Ok(Self {
            cache: store(config.buffer.store.as_deref())?,
            key: config.buffer.key.clone(),
            max: config.buffer.max_urls.max(1),
        })
    }

    /// Add URLs, dropping duplicates and anything past `max_urls`. Returns how many are buffered.
    pub async fn push(&self, urls: &[String]) -> laravel::Result<usize> {
        if urls.is_empty() {
            return self.count().await;
        }

        let urls = urls.to_vec();
        let cache = self.cache.clone();
        let key = self.key.clone();
        let max = self.max;

        self.locked(move || async move {
            let mut buffered: Vec<String> = cache.get(&key).await?.unwrap_or_default();

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

            buffered.truncate(max);
            cache.put(&key, &buffered, BUFFER_LIFETIME_DAYS.days()).await?;

            Ok(buffered.len())
        })
        .await
    }

    /// Take everything out of the buffer.
    pub async fn pull(&self) -> laravel::Result<Vec<String>> {
        let cache = self.cache.clone();
        let key = self.key.clone();

        self.locked(move || async move {
            let buffered: Vec<String> = cache.get(&key).await?.unwrap_or_default();
            cache.forget(&key).await?;

            Ok(buffered)
        })
        .await
    }

    /// How many URLs wait in the buffer.
    pub async fn count(&self) -> laravel::Result<usize> {
        Ok(self
            .cache
            .get::<Vec<String>>(&self.key)
            .await?
            .unwrap_or_default()
            .len())
    }

    async fn locked<T, F, Fut>(&self, callback: F) -> laravel::Result<T>
    where
        T: Send + 'static,
        F: FnOnce() -> Fut + Send,
        Fut: Future<Output = laravel::Result<T>> + Send,
    {
        self.cache
            .lock(&format!("{}:lock", self.key), 10.seconds())
            .block(5.seconds())
            .get(callback)
            .await
    }
}