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::sync::{Arc, Mutex, PoisonError};

use async_trait::async_trait;
use laravel::http::client;
use laravel::time::ToSpan;
use serde_json::{Map, Value, json};

use crate::keys::KeyRepository;
use crate::result::{RetryableSubmission, SubmissionResult};

/// The transport: sends one batch of URLs of one host.
#[async_trait]
pub trait Submitter: Send + Sync {
    /// Send `urls`, which all belong to `host`.
    async fn submit(&self, host: &str, urls: &[String]) -> Result<SubmissionResult, RetryableSubmission>;
}

/// Talks to the IndexNow endpoint.
pub struct HttpSubmitter {
    keys: KeyRepository,
    endpoint: String,
    timeout: u64,
}

impl HttpSubmitter {
    /// A submitter for `endpoint`.
    pub fn new(keys: KeyRepository, endpoint: impl Into<String>, timeout: u64) -> Self {
        Self {
            keys,
            endpoint: endpoint.into(),
            timeout,
        }
    }

    fn payload(&self, host: &str, urls: &[String], key: &str) -> Value {
        let mut body = Map::new();

        body.insert("host".into(), json!(host));
        body.insert("key".into(), json!(key));

        if let Some(location) = self.keys.explicit_location() {
            body.insert("keyLocation".into(), json!(location));
        }

        body.insert("urlList".into(), json!(urls));

        Value::Object(body)
    }

    fn interpret(
        &self,
        host: &str,
        urls: &[String],
        status: u16,
        retry_after: Option<u64>,
        key: &str,
    ) -> Result<SubmissionResult, RetryableSubmission> {
        Ok(match status {
            200 => SubmissionResult::success(host, urls, status, "Submitted."),
            202 => SubmissionResult::success(
                host,
                urls,
                status,
                "Accepted. The key is still being verified, which is normal the first time.",
            ),
            400 => SubmissionResult::failure(
                host,
                urls,
                Some(status),
                "Bad request: a URL is malformed or the payload was rejected.",
            ),
            403 => SubmissionResult::failure(
                host,
                urls,
                Some(status),
                format!(
                    "Key rejected. It must be readable at {} and contain exactly [{key}]. Run `indexnow:verify` to check.",
                    self.keys
                        .location_for(host, None)
                        .unwrap_or_else(|| "the configured key location".to_owned()),
                ),
            ),
            422 => SubmissionResult::failure(
                host,
                urls,
                Some(status),
                format!("The submitted URLs do not all belong to [{host}], or the key does not match that host."),
            ),
            429 => {
                return Err(RetryableSubmission::new(
                    "Rate limited by the IndexNow endpoint.",
                    host,
                    urls,
                    retry_after,
                ));
            }
            500.. => {
                return Err(RetryableSubmission::new(
                    format!("The IndexNow endpoint answered {status}."),
                    host,
                    urls,
                    None,
                ));
            }
            _ => SubmissionResult::failure(host, urls, Some(status), format!("Unexpected response: {status}.")),
        })
    }
}

#[async_trait]
impl Submitter for HttpSubmitter {
    async fn submit(&self, host: &str, urls: &[String]) -> Result<SubmissionResult, RetryableSubmission> {
        if urls.is_empty() {
            return Ok(SubmissionResult::skipped(host, urls, "Nothing to submit."));
        }

        let Some(key) = self.keys.for_host(host) else {
            return Ok(SubmissionResult::skipped(
                host,
                urls,
                format!("No IndexNow key is configured for host [{host}]."),
            ));
        };

        let response = client::post(&self.endpoint)
            .timeout((self.timeout as i64).seconds())
            .accept_json()
            .json(self.payload(host, urls, &key))
            .await
            .map_err(|error| {
                RetryableSubmission::new(
                    format!("Could not reach the IndexNow endpoint: {error}"),
                    host,
                    urls,
                    None,
                )
            })?;

        let retry_after = response
            .header("retry-after")
            .and_then(|value| value.trim().parse::<u64>().ok())
            .map(|seconds| seconds.max(1));

        self.interpret(host, urls, response.status().as_u16(), retry_after, &key)
    }
}

/// Goes through the whole pipeline and drops the request at the last step.
pub struct NullSubmitter;

#[async_trait]
impl Submitter for NullSubmitter {
    async fn submit(&self, host: &str, urls: &[String]) -> Result<SubmissionResult, RetryableSubmission> {
        Ok(SubmissionResult::success(
            host,
            urls,
            200,
            "Dropped by the null driver. Nothing left the application.",
        ))
    }
}

/// Records what would have been submitted, for tests. Get one with [`crate::fake`].
#[derive(Clone, Default)]
pub struct Fake {
    submissions: Arc<Mutex<Vec<SubmissionResult>>>,
}

impl Fake {
    /// Every request recorded, in order.
    pub fn submissions(&self) -> Vec<SubmissionResult> {
        self.submissions.lock().unwrap_or_else(PoisonError::into_inner).clone()
    }

    /// Every distinct URL recorded, in the order it was first seen.
    pub fn submitted(&self) -> Vec<String> {
        let mut urls: Vec<String> = Vec::new();

        for submission in self.submissions() {
            for url in submission.urls {
                if !urls.contains(&url) {
                    urls.push(url);
                }
            }
        }

        urls
    }

    /// Forget everything recorded so far.
    pub fn reset(&self) {
        self.submissions.lock().unwrap_or_else(PoisonError::into_inner).clear();
    }

    /// Fail unless `url` was submitted.
    #[track_caller]
    pub fn assert_submitted(&self, url: &str) {
        let submitted = self.submitted();

        assert!(
            submitted.iter().any(|candidate| candidate == url),
            "Expected URL was not submitted to IndexNow.\nSubmitted:\n  {}",
            if submitted.is_empty() {
                "(nothing)".to_owned()
            } else {
                submitted.join("\n  ")
            },
        );
    }

    /// Fail unless some submitted URL satisfies `predicate`.
    #[track_caller]
    pub fn assert_submitted_where(&self, predicate: impl Fn(&str) -> bool) {
        let submitted = self.submitted();

        assert!(
            submitted.iter().any(|url| predicate(url)),
            "No submitted URL matched.\nSubmitted:\n  {}",
            submitted.join("\n  "),
        );
    }

    /// Fail if `url` was submitted.
    #[track_caller]
    pub fn assert_not_submitted(&self, url: &str) {
        assert!(
            !self.submitted().iter().any(|candidate| candidate == url),
            "URL [{url}] should not have been submitted to IndexNow.",
        );
    }

    /// Fail if anything was submitted.
    #[track_caller]
    pub fn assert_nothing_submitted(&self) {
        let submitted = self.submitted();

        assert!(
            submitted.is_empty(),
            "Expected no IndexNow submissions.\nSubmitted:\n  {}",
            submitted.join("\n  "),
        );
    }

    /// Fail unless exactly `count` distinct URLs were submitted.
    #[track_caller]
    pub fn assert_submitted_count(&self, count: usize) {
        assert_eq!(
            self.submitted().len(),
            count,
            "Expected {count} URLs submitted to IndexNow."
        );
    }
}

#[async_trait]
impl Submitter for Fake {
    async fn submit(&self, host: &str, urls: &[String]) -> Result<SubmissionResult, RetryableSubmission> {
        let result = SubmissionResult::success(host, urls, 200, "Faked.");

        self.submissions
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .push(result.clone());

        Ok(result)
    }
}