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 super::QueueManagerInternals as _;
use std::sync::Arc;
use std::time::{Duration, UNIX_EPOCH};

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use tracing::Instrument;

use super::attempt::{Effects, Requested};
use super::batch::{self, BatchChanges, BatchId, Ended};
use super::chain::{Chain, EncodedJob};
use super::fake::Dispatched;
use super::job::__Registration;
use super::queueable::{MissingModels, Undecodable};
use super::{Attempt, JobId};
use crate::context::{Context, Internals, Values};
use crate::errors::panic;
use crate::{Error, Result};

const VERSION: u32 = 1;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Payload {
    pub(crate) version: u32,
    pub(crate) id: JobId,
    pub(crate) job: String,
    /// What `queue:work` and `queue:failed` call the job, when the job's name doesn't say, such
    /// as the workflow a framework job advances.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) display_name: Option<String>,
    pub(crate) data: Value,
    #[serde(default, skip_serializing_if = "Map::is_empty")]
    pub(crate) context: Map<String, Value>,
    #[serde(default, skip_serializing_if = "Map::is_empty")]
    pub(crate) hidden_context: Map<String, Value>,
    pub(crate) dispatched_at: i64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) group: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) deduplication_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub debounce_id: Option<String>,
    #[serde(default, skip_serializing_if = "Chain::is_empty")]
    pub(crate) chain: Chain,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub batch: Option<BatchId>,
    /// The W3C Trace Context fields of the span that pushed the job, which its runs continue.
    #[cfg(feature = "opentelemetry")]
    #[serde(default, skip_serializing_if = "std::collections::HashMap::is_empty")]
    pub(crate) trace: std::collections::HashMap<String, String>,
    /// The job's models as they were dispatched, which a queue fake's assertions read.
    #[serde(skip)]
    pub(crate) dispatched: Dispatched,
}

#[derive(Debug)]
pub struct Ran {
    pub outcome: Outcome,
    pub chain: Chain,
    pub batch: BatchChanges,
    pub(crate) context: Option<ContextValues>,
}

pub(crate) type ContextValues = (Map<String, Value>, Map<String, Value>);

impl Ran {
    fn ended(outcome: Outcome) -> Self {
        Self {
            outcome,
            chain: Chain::default(),
            batch: BatchChanges::default(),
            context: None,
        }
    }

    pub fn failed(error: Error) -> Self {
        Self::ended(Outcome::Failed { error, retry: false })
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Place<'a> {
    pub connection: &'a str,
    pub queue: &'a str,
    pub number: u32,
}

impl Payload {
    pub fn new(job: EncodedJob, values: &Values) -> Self {
        Self {
            version: VERSION,
            id: job.id,
            job: job.job,
            display_name: None,
            data: job.data,
            context: values.logged.clone(),
            hidden_context: values.hidden().clone(),
            dispatched_at: unix_now(),
            group: None,
            deduplication_id: None,
            debounce_id: job.debounce_id,
            chain: Chain::default(),
            batch: None,
            #[cfg(feature = "opentelemetry")]
            trace: crate::foundation::telemetry::job_trace(&tracing::Span::current()),
            dispatched: job.dispatched,
        }
    }

    pub(crate) fn encode(&self) -> Result<String> {
        serde_json::to_string(self).map_err(|error| crate::error::fail(format!("a job couldn't be encoded: {error}")))
    }

    pub(crate) fn decode(payload: &str) -> Result<Self> {
        serde_json::from_str(payload)
            .map_err(|error| crate::error::fail(format!("a queued job couldn't be read: {error}")))
    }

    pub(crate) async fn attempt(&self, place: Place<'_>) -> Ran {
        let cancelled = match self.batch {
            Some(id) => self.in_context(batch::is_cancelled(id)).await,
            None => Ok(false),
        };

        match cancelled {
            Ok(true) => Ran::ended(Outcome::Skipped),
            Ok(false) => self.run(place).await,
            Err(error) => Ran::ended(Outcome::Failed { error, retry: true }),
        }
    }

    pub async fn run(&self, place: Place<'_>) -> Ran {
        if self.version != VERSION {
            return Ran::failed(crate::error::fail(format!(
                "the job `{}` was queued in payload format {}, which this application can't read",
                self.job, self.version
            )));
        }

        self.in_context(async {
            let registered = match __Registration::find(&self.job) {
                Ok(registered) => registered,
                Err(error) => return Ran::failed(error),
            };
            if super::debounce::superseded(self).await {
                return Ran::ended(Outcome::Debounced);
            }
            let attempt = Arc::new(Attempt::new(self, registered.name(), place));
            let handle = match panic::catch(registered.run(self.data.clone(), Arc::clone(&attempt))).await {
                Ok(handle) => handle,
                Err(error) => return Ran::ended(unrestorable(registered, error)),
            };
            let result = panic::catch(handle).await;
            let Effects {
                requested,
                chain: jobs,
                batch,
            } = attempt.take_effects();
            let chain = Chain {
                jobs,
                connection: self.chain.connection.clone(),
                queue: self.chain.queue.clone(),
                catch: self.chain.catch.clone(),
            };

            let outcome = match (requested, result) {
                (Some(Requested::Fail(error)), _) => Outcome::Failed { error, retry: false },
                (_, Err(error)) => Outcome::Failed { error, retry: true },
                (Some(Requested::Settle(error)), Ok(())) => Outcome::Settled(error),
                (Some(Requested::Release(delay)), Ok(())) => Outcome::Released(delay),
                (Some(Requested::Delete), Ok(())) => Outcome::Deleted,
                (None, Ok(())) => Outcome::Succeeded,
            };
            let values = Context::expect("a queued job").values();
            Ran {
                outcome,
                chain,
                batch,
                context: Some((values.logged.clone(), values.hidden().clone())),
            }
        })
        .await
    }

    pub(crate) async fn finish(
        &self,
        outcome: &Outcome,
        chain: Chain,
        mut changes: BatchChanges,
        context: Option<&ContextValues>,
    ) -> Result<()> {
        let ended = match outcome {
            Outcome::Succeeded | Outcome::Deleted => Some(Ended::Succeeded),
            Outcome::Skipped | Outcome::Debounced | Outcome::MissingModels => Some(Ended::Skipped),
            Outcome::Settled(_) => Some(Ended::Failed),
            Outcome::Released(_) | Outcome::Failed { .. } => None,
        };
        let settled = match outcome {
            Outcome::Settled(error) => Some(error),
            _ => None,
        };
        if let Some(id) = self.batch {
            if ended == Some(Ended::Succeeded) {
                changes.chained = chain
                    .member_ids()
                    .filter(|member| !self.chain.member_ids().any(|own| own == *member))
                    .collect();
            }
            self.in_context_with(context, async {
                let context = Context::expect("a batched job");
                batch::settle(id, self.id, ended, settled, &self.chain, changes, &context).await
            })
            .await?;
        }
        if ended != Some(Ended::Succeeded) {
            return Ok(());
        }

        self.in_context_with(context, async {
            let context = Context::expect("a chained job");
            chain.dispatch_next(&context, context.values(), self.batch).await
        })
        .await
    }

    pub(crate) async fn run_once(&self, connection: &str, queue: &str) -> Result<()> {
        let place = Place {
            connection,
            queue,
            number: 1,
        };
        let span = self.span(place);

        async {
            let Ran {
                outcome,
                chain,
                batch,
                context,
            } = self.attempt(place).await;
            let finished = self.finish(&outcome, chain, batch, context.as_ref()).await;

            match outcome {
                Outcome::Failed { error, .. } => {
                    crate::foundation::telemetry::fail(&tracing::Span::current(), &error);
                    if let Err(error) = finished {
                        self.report(error, context.as_ref()).await;
                    }
                    self.run_failed_hook(place, &error, context.as_ref()).await;
                    Err(error)
                }
                Outcome::Settled(error) => {
                    crate::foundation::telemetry::fail(&tracing::Span::current(), &error);
                    finished
                }
                _ => finished,
            }
        }
        .instrument(span)
        .await
    }

    pub fn span(&self, place: Place<'_>) -> tracing::Span {
        let manager = Context::current().map(|context| super::QueueManager::of(context.services()));
        tracing::info_span!(
            target: crate::foundation::telemetry::QUEUE_TARGET,
            "job",
            id = %self.id,
            job = %self.job,
            connection = place.connection,
            queue = place.queue,
            attempt = place.number,
            otel.name = %self.job,
            otel.kind = "consumer",
            otel.status_code = tracing::field::Empty,
            messaging.system = manager.as_ref().and_then(|manager| manager.messaging_system(place.connection)),
            messaging.operation.name = "process",
            messaging.operation.type = "process",
            messaging.destination.name = place.queue,
            messaging.message.id = %self.id,
        )
    }

    pub(crate) async fn run_failed_hook(&self, place: Place<'_>, error: &Error, values: Option<&ContextValues>) {
        self.in_context_with(values, async {
            let context = Context::expect("a failed job's chain");
            if let Some(id) = self.batch {
                let recorded = batch::settle(
                    id,
                    self.id,
                    Some(Ended::Failed),
                    Some(error),
                    &self.chain,
                    BatchChanges::default(),
                    &context,
                );
                if let Err(error) = recorded.await {
                    context.report(error);
                }
            }
            self.chain.call_catch(error, &context).await;
        })
        .await;
        let Ok(registered) = __Registration::find(&self.job) else {
            return;
        };

        self.in_context_with(values, async {
            let attempt = Attempt::new(self, registered.name(), place);
            // A job that couldn't be restored to run has already reported why...
            let failed = match panic::catch(registered.failed(self.data.clone(), error, &attempt)).await {
                Ok(failed) => panic::catch(failed).await,
                Err(_) if is_unrestorable(error) => Ok(()),
                Err(restoring) => Err(restoring),
            };
            if let Err(error) = failed {
                Context::expect("a failed job's hook").report(error);
            }
        })
        .await;
    }

    pub(crate) async fn report(&self, error: Error, values: Option<&ContextValues>) {
        self.in_context_with(values, async { Context::expect("a failed job").report(error) })
            .await;
    }

    pub(crate) async fn in_context<F: Future>(&self, future: F) -> F::Output {
        self.in_context_with(None, future).await
    }

    /// Run `future` in a fresh context with `values`, the values a run of the job ended with, or
    /// without them, the values the job was dispatched with.
    pub(crate) async fn in_context_with<F: Future>(&self, values: Option<&ContextValues>, future: F) -> F::Output {
        let context = Context::expect("a queued job").fresh();
        let (logged, hidden) = values.map_or_else(
            || (self.context.clone(), self.hidden_context.clone()),
            |(logged, hidden)| (logged.clone(), hidden.clone()),
        );
        context.restore_values(logged, hidden);

        context.scope(future).await
    }
}

/// How a job ends when it couldn't be restored from its payload: deleted when a model is gone,
/// unless the job asks to fail, failed for good when a model is gone or the data doesn't decode,
/// and retried when a query failed.
fn unrestorable(registered: &__Registration, error: Error) -> Outcome {
    if error.is::<MissingModels>() && !registered.options().fail_when_missing_models {
        crate::foundation::telemetry::logging(
            &error,
            || tracing::info!(target: "laravel::queue", job = registered.name(), %error, "Deleted a job whose models are gone"),
        );

        return Outcome::MissingModels;
    }
    let retry = !is_unrestorable(&error);

    Outcome::Failed { error, retry }
}

fn is_unrestorable(error: &Error) -> bool {
    error.is::<MissingModels>() || error.is::<Undecodable>()
}

#[derive(Debug)]
pub enum Outcome {
    Succeeded,
    Released(Duration),
    /// The job deleted itself, and its chain continues.
    Deleted,
    Debounced,
    Skipped,
    /// The job was deleted without running because a model is gone, which ends its chain.
    MissingModels,
    Failed {
        error: Error,
        retry: bool,
    },
    /// The job failed for good, and already dealt with the failure, so the queue only deletes it.
    Settled(Error),
}

pub(crate) fn unix_now() -> i64 {
    let elapsed = crate::clock::system_now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();

    i64::try_from(elapsed.as_secs()).unwrap_or(i64::MAX)
}