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
use std::time::Duration;

use serde::Deserialize;
use serde_json::{Value, json};

use super::{Events, timestamp};
use crate::context::{Context, Internals};
use crate::{Error, Result};

impl Events {
    pub(crate) async fn retried(&self, job: &Job) {
        self.emit(json!({
            "_cloud_event": "failed_job",
            "id": job.id,
            "queue": job.queue,
            "retried_at": timestamp(),
        }))
        .await;
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub(crate) struct Job {
    #[serde(deserialize_with = "id")]
    pub(crate) id: String,
    pub(crate) connection: String,
    pub(crate) queue: String,
    pub(crate) payload: String,
}

/// A failed job's ID, which Laravel Cloud may give as a number or a string.
fn id<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<String, D::Error> {
    Ok(match Value::deserialize(deserializer)? {
        Value::String(id) => id,
        other => other.to_string(),
    })
}

#[derive(Deserialize)]
struct Page {
    data: Vec<Job>,
    links: Links,
}

#[derive(Deserialize)]
struct Links {
    next: Option<String>,
}

pub(crate) async fn jobs(url: &str) -> Result<Vec<Job>> {
    let context = Context::expect("queue:retry");
    let cipher = context.config().app.cipher.name().to_ascii_uppercase();
    let client = reqwest::Client::builder()
        .connect_timeout(Duration::from_secs(10))
        .timeout(Duration::from_secs(10))
        .build()
        .map_err(|error| crate::error::fail(format!("Laravel Cloud's client couldn't be built: {error}")))?;

    let mut jobs = Vec::new();
    let mut next = Some(url.to_owned());
    while let Some(url) = next {
        let (version, body) = fetch(&client, &url, &cipher).await?;
        let body = context.encrypter()?.decrypt_string(&body)?;
        let page = read_page(version.as_deref(), &body)?;
        jobs.extend(page.data);
        next = page.links.next;
    }

    Ok(jobs)
}

/// Read a page of failed jobs in the format Laravel Cloud's `Cloud-Payload-Version` names. Without
/// a version, the body is a single job.
fn read_page(version: Option<&str>, body: &str) -> Result<Page> {
    let invalid =
        |error: serde_json::Error| crate::error::fail(format!("Laravel Cloud's failed jobs couldn't be read: {error}"));

    match version.unwrap_or_default() {
        "1" => serde_json::from_str(body).map_err(invalid),
        "" => Ok(Page {
            data: vec![serde_json::from_str(body).map_err(invalid)?],
            links: Links { next: None },
        }),
        version => Err(crate::error::fail(format!("unsupported payload version: {version}"))),
    }
}

async fn fetch(client: &reqwest::Client, url: &str, cipher: &str) -> Result<(Option<String>, String)> {
    let mut attempt = 1;
    loop {
        let response = client
            .get(url)
            .header("Cloud-Payload-Version", "1")
            .header("Cloud-Encryption-Cipher", cipher)
            .send()
            .await
            .and_then(reqwest::Response::error_for_status);
        match response {
            Ok(response) => {
                let version = response
                    .headers()
                    .get("Cloud-Payload-Version")
                    .and_then(|version| version.to_str().ok())
                    .map(str::to_owned);
                let body = response.text().await.map_err(|error| fetch_failed(url, &error))?;
                return Ok((version, body));
            }
            Err(error) if error.status() == Some(reqwest::StatusCode::FORBIDDEN) || attempt == 10 => {
                return Err(fetch_failed(url, &error));
            }
            Err(_) => {
                tokio::time::sleep(Duration::from_millis(500) * 2_u32.pow(attempt - 1)).await;
                attempt += 1;
            }
        }
    }
}

fn fetch_failed(url: &str, error: &reqwest::Error) -> Error {
    crate::error::fail(format!(
        "Laravel Cloud's failed jobs couldn't be fetched from `{url}`: {error}"
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pages_and_single_jobs_are_read_by_version() {
        let page = read_page(
            Some("1"),
            r#"{"data":[{"id":7,"connection":"cloud","queue":"default","payload":"{}"}],
                "links":{"self":"https://cloud.test/a","next":"https://cloud.test/b"}}"#,
        )
        .unwrap();
        assert_eq!(
            page.data,
            [Job {
                id: "7".into(),
                connection: "cloud".into(),
                queue: "default".into(),
                payload: "{}".into(),
            }]
        );
        assert_eq!(page.links.next.as_deref(), Some("https://cloud.test/b"));

        let single = read_page(
            None,
            r#"{"id":"a1","connection":"cloud","queue":"emails","payload":"{}"}"#,
        )
        .unwrap();
        assert_eq!(single.data[0].id, "a1");
        assert_eq!(single.links.next, None);

        let error = read_page(Some("2"), "{}").err().unwrap();
        assert_eq!(error.to_string(), "unsupported payload version: 2");
    }
}