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
#[cfg(feature = "database")]
mod batches;
mod control;
#[cfg(feature = "database")]
mod failed;

use super::QueueManagerInternals as _;
use crate::console::ConsoleInternals as _;
use std::sync::Arc;
use std::time::Duration;

use futures_util::stream::{FuturesUnordered, StreamExt};
use tokio::task::JoinHandle;
use tokio::time::Instant;
use tracing::Instrument;

use self::control::{Next, Signals};
use super::QueueManager;
use super::events::JobOutcome;
use super::worker::{Processed, Worker};
use crate::console::markup::clean;
use crate::console::theme::{elapsed, type_label};
use crate::console::{Commands, Console, clap, trap_stop};
use crate::container::Inject;
use crate::context::{Context, Internals};
use crate::foundation::telemetry::untraced;
use crate::{Error, Result};

pub fn register(commands: &mut Commands) {
    commands.add::<Work>().add::<Clear>();
    control::register(commands);
    #[cfg(feature = "database")]
    failed::register(commands);
    #[cfg(feature = "database")]
    batches::register(commands);
}

const MAX_ERROR_WAIT: Duration = Duration::from_secs(60);

/// Process jobs on the queue.
#[derive(clap::Parser)]
#[command(name = "queue:work")]
struct Work {
    /// The queue connection to work.
    connection: Option<String>,
    /// The queues to work, in priority order, as `high,default`, instead of the connection's.
    #[arg(long, value_delimiter = ',', value_name = "QUEUES")]
    queue: Vec<String>,
    /// How many jobs to run at the same time.
    #[arg(long, default_value_t = 1, value_name = "COUNT", value_parser = clap::value_parser!(u16).range(1..))]
    concurrency: u16,
    /// How many seconds to wait before checking again when no job is available.
    #[arg(long, default_value_t = 3, value_name = "SECONDS")]
    sleep: u64,
    /// Stop after taking this many jobs, once they finish.
    #[arg(long, value_name = "COUNT")]
    max_jobs: Option<u64>,
    /// Stop after this many seconds, once running jobs finish.
    #[arg(long, value_name = "SECONDS")]
    max_time: Option<u64>,
    /// Stop once no job is available.
    #[arg(long)]
    stop_when_empty: bool,
}

#[crate::console::command(long_running)]
impl Work {
    async fn handle(self, manager: Inject<QueueManager>, console: &mut Console) -> Result<()> {
        let mut stop = trap_stop(console)?;
        let (connection, queue) = manager.route(self.connection.as_deref(), None)?;
        let worker = Arc::new(Worker::new(&manager, &connection).await?);
        let queues = if self.queue.is_empty() {
            vec![queue]
        } else {
            self.queue.clone()
        };
        announce(&connection, &queues, console);

        let deadline = self
            .max_time
            .map(|seconds| Instant::now() + Duration::from_secs(seconds));
        let sleep = Duration::from_secs(self.sleep);
        let mut running = FuturesUnordered::new();
        let mut taken = 0_u64;
        let mut error_wait = None;
        let mut signals = Signals::new(&connection, &queues).instrument(untraced()).await;
        let mut lost = None;
        loop {
            if *stop.borrow()
                || lost.is_some()
                || self.max_jobs.is_some_and(|max| taken >= max)
                || deadline.is_some_and(|deadline| Instant::now() >= deadline)
            {
                break;
            }
            if running.len() >= usize::from(self.concurrency) {
                tokio::select! {
                    biased;
                    Ok(()) = stop.changed() => {}
                    Some(finished) = running.next() => lost = lost.or(write(finished, console)),
                }
                continue;
            }

            let unpaused = match signals.check(console).instrument(untraced()).await {
                Next::Restart => {
                    console.info("Restart signal received.");
                    break;
                }
                Next::Reserve(unpaused) => unpaused,
            };
            let reserved = if unpaused.is_empty() {
                Ok(None)
            } else {
                tokio::select! {
                    biased;
                    Ok(()) = stop.changed() => continue,
                    reserved = worker.reserve(&unpaused).instrument(untraced()) => reserved,
                }
            };
            let wait = match reserved {
                Ok(Some(job)) => {
                    taken += 1;
                    error_wait = None;
                    let worker = Arc::clone(&worker);
                    running.push(crate::task::spawn(async move { worker.process(job).await }));
                    continue;
                }
                Ok(None) if self.stop_when_empty && running.is_empty() => break,
                Ok(None) => {
                    error_wait = None;
                    (!self.stop_when_empty).then_some(sleep)
                }
                Err(error) if self.stop_when_empty || stops_worker(&error) => {
                    drain(&mut running, console).await;
                    return Err(error);
                }
                Err(error) => {
                    let wait = error_wait.map_or(sleep.max(Duration::from_secs(1)), |wait: Duration| {
                        (wait * 2).min(MAX_ERROR_WAIT)
                    });
                    error_wait = Some(wait);
                    console.error(format!(
                        "couldn't reserve a job, trying again in {}: {}",
                        elapsed(wait),
                        clean(&error.to_string())
                    ));
                    Context::expect("queue:work").report_rendered(&error);
                    Some(wait)
                }
            };

            tokio::select! {
                biased;
                Ok(()) = stop.changed() => {}
                Some(finished) = running.next(), if !running.is_empty() => lost = lost.or(write(finished, console)),
                () = tokio::time::sleep(wait.unwrap_or_default()), if wait.is_some() => {}
            }
        }

        match running.len() {
            0 => {}
            1 => console.info("Waiting for 1 running job to finish."),
            running => console.info(format!("Waiting for {running} running jobs to finish.")),
        }
        lost.or(drain(&mut running, console).await).map_or(Ok(()), Err)
    }
}

/// Start the worker's ticks and say which queues it works.
fn announce(connection: &str, queues: &[String], console: &mut Console) {
    // Tests run the worker with a captured console, and run ticks themselves...
    if !console.is_captured() {
        let context = Context::expect("queue:work");
        crate::task::ticks::start(
            &context,
            crate::foundation::Host::Worker {
                connection: connection.to_owned(),
                queues: queues.to_vec(),
            },
        );
    }
    let queues: Vec<_> = queues.iter().map(|queue| format!("`{connection}:{queue}`")).collect();

    console.info(format!(
        "Processing jobs from {}. Press Ctrl+C to stop.",
        queues.join(", ")
    ));
}

/// Wait for every running job, and return the first error that stops the worker.
async fn drain(running: &mut FuturesUnordered<JoinHandle<Result<Processed>>>, console: &mut Console) -> Option<Error> {
    let mut lost = None;
    while let Some(finished) = running.next().await {
        lost = lost.or(write(finished, console));
    }

    lost
}

fn stops_worker(error: &Error) -> bool {
    #[cfg(feature = "sqs")]
    return error.is::<super::cloud::AgentUnreachable>();
    #[cfg(not(feature = "sqs"))]
    {
        let _ = error;
        false
    }
}

#[must_use]
fn write(
    finished: std::result::Result<Result<Processed>, tokio::task::JoinError>,
    console: &mut Console,
) -> Option<Error> {
    match finished.map_err(Error::from).and_then(|processed| processed) {
        Ok(processed) => report(&processed, console),
        Err(error) if stops_worker(&error) => return Some(error),
        Err(error) => {
            console.error(format!("a job couldn't be settled: {}", clean(&error.to_string())));
            Context::expect("queue:work").report_rendered(&error);
        }
    }

    None
}

/// One line per attempt: the job's name, how it ended, and how long it ran, with the error below.
fn report(processed: &Processed, console: &mut Console) {
    // Failures are reported to the logs, so `--quiet` hides every job line.
    if console.is_quiet() {
        return;
    }
    let duration = console.muted(&elapsed(processed.duration));
    let name = type_label(&processed.name);
    let mut line = match processed.outcome {
        JobOutcome::Succeeded => format!("{name}  {duration}"),
        outcome => format!("{name} {outcome}  {duration}"),
    };
    if let Some(error) = &processed.error {
        line.push('\n');
        line.push_str(&clean(error));
    }
    match processed.outcome {
        JobOutcome::Succeeded => console.success(line),
        JobOutcome::Released | JobOutcome::Deleted | JobOutcome::Debounced | JobOutcome::MissingModels => {
            console.info(line);
        }
        JobOutcome::Retrying => console.warn(line),
        JobOutcome::Failed => console.error(line),
    }
}

/// The time `hours` ago, which `queue:flush` and `queue:prune-batches` delete records from before.
#[cfg(feature = "database")]
fn hours_ago(hours: u32) -> jiff::Timestamp {
    crate::clock::system_timestamp()
        .checked_sub(Duration::from_secs(u64::from(hours) * 3600))
        .unwrap_or(jiff::Timestamp::MIN)
}

/// Delete all jobs on a queue.
#[derive(clap::Parser)]
#[command(name = "queue:clear")]
struct Clear {
    /// The queue connection to clear.
    connection: Option<String>,
    /// The queue to clear, instead of the connection's.
    #[arg(long, value_name = "QUEUE")]
    queue: Option<String>,
}

#[crate::console::command]
impl Clear {
    async fn handle(self, manager: Inject<QueueManager>, console: &mut Console) -> Result<()> {
        let (connection, queue) = manager.route(self.connection.as_deref(), self.queue.as_deref())?;
        let deleted = manager.driver(&connection).await?.clear(&queue).await?;

        match deleted {
            0 => console.info(format!("No jobs found on `{connection}:{queue}`.")),
            1 => console.success(format!("1 job cleared from `{connection}:{queue}`.")),
            deleted => console.success(format!("{deleted} jobs cleared from `{connection}:{queue}`.")),
        }
        Ok(())
    }
}