laravel-rust-queue 0.1.0

Internal crate of Laravel for Rust: jobs, the queue drivers, the worker, batches, and chains. Depend on `laravel-rust` instead
Documentation
//! The job tail that email, text messages, and notification channel messages share when queued:
//! where the job goes, how often it retries, and which errors end it.

use super::QueueManagerInternals as _;
use std::fmt;
use std::time::Duration;

use super::{Attempt, Job, JobOptions};
use crate::time::Moment;
use crate::{Error, Result};

/// Where a delivery job goes and how long it waits, as `on_connection`, `on_queue`, and `delay`
/// set them. A sender's own defaults, such as `MAIL_QUEUE`, fill in what they leave out.
#[derive(Debug, Default)]
pub struct Placement {
    pub connection: Option<String>,
    pub queue: Option<String>,
    pub delay: Option<Moment>,
}

impl Placement {
    /// The connection and queue: these, then the given defaults, then the queue's own defaults.
    pub fn resolve(
        &self,
        services: &crate::container::Services,
        connection: Option<&str>,
        queue: Option<&str>,
    ) -> Result<(String, String)> {
        super::QueueManager::of(services).route(
            self.connection.as_deref().or(connection),
            self.queue.as_deref().or(queue),
        )
    }
}

/// A delivery job's options: three tries, 10 seconds and then a minute apart.
pub fn options() -> JobOptions {
    JobOptions::new()
        .tries(3)
        .backoff([Duration::from_secs(10), Duration::from_secs(60)])
}

/// End a delivery attempt. An error that [`refused`] picks out fails the job for good, and any
/// other error retries it.
pub fn settle<T>(attempt: &Attempt, delivered: Result<T>) -> Result<()> {
    match delivered {
        Ok(_) => Ok(()),
        Err(error) if refused(&error) => {
            attempt.fail(error);
            Ok(())
        }
        Err(error) => Err(error),
    }
}

/// Whether a provider refused the message in a way that retrying can't change: a [`Refused`], or
/// a 4xx response other than a timeout, a conflict, or a rate limit.
pub fn refused(error: &Error) -> bool {
    error.chain().any(|source| {
        source.is::<Refused>()
            || source
                .downcast_ref::<Rejection>()
                .is_some_and(|rejection| rejection.refused)
            || source
                .downcast_ref::<crate::http::client::Error>()
                .is_some_and(crate::http::client::Error::is_permanent)
    })
}

/// A message that sending again can't deliver, without an HTTP error that says so, such as an
/// email over the size limit or Slack's `channel_not_found`. A queued delivery fails without
/// another attempt.
#[derive(Debug)]
pub struct Refused(#[doc(hidden)] pub String);

impl fmt::Display for Refused {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for Refused {}

/// A provider's error response to a message, such as Resend's to an email. Its message quotes the
/// provider's, which can repeat an address or a number, so a span exports only its
/// [summary](crate::foundation::telemetry::Summary): the provider and the status.
#[derive(Debug)]
pub struct Rejection {
    provider: &'static str,
    message_kind: &'static str,
    message: String,
    response: crate::http::client::Error,
    refused: bool,
}

impl Rejection {
    /// The rejection of a `message_kind`, such as `email`, in `response`, with the provider's
    /// `message`.
    pub fn new(
        provider: &'static str,
        message_kind: &'static str,
        response: crate::http::client::Response,
        message: String,
    ) -> Self {
        Self {
            provider,
            message_kind,
            message,
            response: crate::http::client::Error::Status(Box::new(response)),
            refused: false,
        }
    }

    /// Marks the rejection as one that sending again can't change, whatever its status.
    #[must_use]
    pub fn refused(mut self) -> Self {
        self.refused = true;
        self
    }

    fn status(&self) -> u16 {
        self.response
            .response()
            .map_or(0, |response| response.status().as_u16())
    }

    fn summary(&self) -> String {
        format!(
            "{} rejected the {} with HTTP {}",
            self.provider,
            self.message_kind,
            self.status()
        )
    }
}

impl fmt::Display for Rejection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.summary(), self.message)
    }
}

impl std::error::Error for Rejection {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.response)
    }
}

inventory::submit! {
    crate::foundation::telemetry::Summarizer(|error| {
        use crate::foundation::telemetry::Summary;

        if let Some(rejection) = error.downcast_ref::<Rejection>() {
            return Some(Summary::new(rejection.status().to_string(), rejection.summary()));
        }
        // A refusal's reason can quote the provider, so its span says only that it was refused...
        error
            .is::<Refused>()
            .then(|| Summary::new("refused", "the provider refused the message"))
    })
}

/// Push a delivery job to `connection` and `queue`, after `delay`, shown as what it delivers.
pub async fn dispatch<J: Job>(
    job: J,
    display_name: Option<&str>,
    connection: String,
    queue: String,
    delay: Option<Moment>,
) -> Result<()> {
    let mut dispatch = super::dispatch(job).on_connection(connection).on_queue(queue);
    if let Some(name) = display_name {
        dispatch = dispatch.display_name(name);
    }
    if let Some(delay) = delay {
        dispatch = dispatch.delay(delay);
    }

    dispatch.await.map(drop)
}