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 super::JobId;
use super::job::__Registration;
use super::payload::{Payload, unix_now};
use crate::Error;
use crate::cache::Repository;

const MIN_TTL: Duration = Duration::from_secs(5 * 60);

struct Keys {
    latest: String,
    waiting_since: String,
}

impl Keys {
    fn new(job: &str, id: &str) -> Self {
        Self {
            latest: format!("laravel:debounce:{job}:{id}"),
            waiting_since: format!("laravel:debounce-wait:{job}:{id}"),
        }
    }

    fn of(payload: &Payload) -> Option<Self> {
        payload.debounce_id.as_deref().map(|id| Self::new(&payload.job, id))
    }
}

pub(super) struct Claim {
    latest: String,
    id: JobId,
}

impl Claim {
    pub(super) async fn release(self) {
        let released = async {
            if crate::cache::get::<JobId>(&self.latest).await? == Some(self.id) {
                crate::cache::forget(&self.latest).await?;
            }
            Ok::<_, Error>(())
        };

        if let Err(error) = released.await {
            cache_failed(&error);
        }
    }
}

pub(super) async fn claim(payload: &mut Payload, delay: Option<Duration>) -> crate::Result<(Duration, Option<Claim>)> {
    let options = __Registration::find(&payload.job)
        .map(|registered| registered.options())
        .unwrap_or_default();
    let (Some(keys), Some(debounce_for)) = (Keys::of(payload), options.debounce_for.map(Duration::from)) else {
        return Ok((delay.unwrap_or_default(), None));
    };
    let ttl = debounce_for.saturating_mul(10).max(MIN_TTL);
    let store = crate::cache::manager().default_store()?;

    store.put(&keys.latest, payload.id, ttl).await?;
    let waited = match options.max_wait {
        Some(max_wait) => waited(&store, &keys, *max_wait, ttl.max(max_wait.saturating_add(debounce_for))).await?,
        None => false,
    };
    if waited {
        payload.debounce_id = None;
    }
    let claim = Claim {
        latest: keys.latest,
        id: payload.id,
    };

    Ok((
        delay.unwrap_or(if waited { Duration::ZERO } else { debounce_for }),
        Some(claim),
    ))
}

async fn waited(store: &Repository, keys: &Keys, max_wait: Duration, ttl: Duration) -> crate::Result<bool> {
    let now = unix_now();
    if store.add(&keys.waiting_since, now, ttl).await? {
        return Ok(false);
    }
    let Some(since) = store.get::<i64>(&keys.waiting_since).await? else {
        return Ok(false);
    };
    if now.saturating_sub(since) < i64::try_from(max_wait.as_secs()).unwrap_or(i64::MAX) {
        return Ok(false);
    }

    store.forget(&keys.waiting_since).await?;
    Ok(true)
}

pub(super) async fn superseded(payload: &Payload) -> bool {
    let Some(keys) = Keys::of(payload) else {
        return false;
    };
    match crate::cache::get::<JobId>(&keys.latest).await {
        Ok(latest) => latest.is_some_and(|latest| latest != payload.id),
        Err(error) => {
            cache_failed(&error);
            false
        }
    }
}

pub(super) async fn running(job: &str, id: &str) {
    if let Err(error) = crate::cache::forget(&Keys::new(job, id).waiting_since).await {
        cache_failed(&error);
    }
}

fn cache_failed(error: &Error) {
    crate::foundation::telemetry::logging(
        error,
        || tracing::warn!(target: "laravel::queue", %error, "A debounced job couldn't be checked in the cache"),
    );
}