use std::time::Duration;
use laravel::Application;
use laravel::config::database::ConnectionConfig;
use laravel::config::{Config, Env};
use laravel::container::Inject;
use laravel::db;
use laravel::event::Event;
use laravel::queue::Queueable;
use laravel::queue::events::{JobFailed, JobProcessed};
use laravel::queue::{Attempt, JobId, QueueSizes, job};
use laravel::rate_limit::{self, Limit};
use laravel::testing::{MakesConsoleRequests, TestCommandResult};
use laravel::time::{Timestamp, ToSpan};
use serde_json::json;
use crate::queue::Records;
use crate::queue::database::{create_failed_table, create_table};
#[derive(Queueable)]
struct Flaky {
id: u32,
failures: u32,
}
#[job(tries = 3, backoff = [10.seconds(), 1.minutes()])]
impl Flaky {
async fn handle(self, records: Inject<Records>, attempt: &Attempt) -> laravel::Result<()> {
records.push(format!("flaky {} ran as attempt {}", self.id, attempt.number()));
if attempt.number() <= self.failures {
return Err(laravel::abort_with(500, format!("flaky {} broke", self.id)));
}
Ok(())
}
async fn failed(self, error: &laravel::Error, records: Inject<Records>) {
records.push(format!("failed hook for flaky {}: {error}", self.id));
}
}
#[derive(Queueable)]
struct Reject;
#[job]
impl Reject {
async fn handle(self) -> laravel::Result<()> {
Err(std::io::Error::other("payload \x1b]0;pwned\x07 rejected").into())
}
}
#[derive(Queueable)]
struct Transcode;
#[job(tries = 2)]
impl Transcode {
async fn handle(self) -> laravel::Result<()> {
laravel::context::add("step", "transcoding");
Err(laravel::abort_with(500, "the codec is missing"))
}
}
#[derive(Queueable)]
struct Poll;
#[job(queue = "polls")]
impl Poll {
async fn handle(self, records: Inject<Records>, attempt: &Attempt) {
records.push(format!("poll ran as attempt {}", attempt.number()));
attempt.release(30.seconds());
}
}
#[derive(Queueable)]
struct PollForAnHour;
#[job(queue = "polls", retry_for = 1.hours())]
impl PollForAnHour {
async fn handle(self, attempt: &Attempt) {
attempt.release(30.seconds());
}
}
#[derive(Queueable)]
struct SendNewsletter;
#[job(queue = "newsletters", retry_for = 1.hours())]
impl SendNewsletter {
async fn handle(self, records: Inject<Records>) -> laravel::Result<()> {
rate_limit::attempt("newsletter", Limit::per_minute(1)).await??;
records.push("newsletter sent");
Ok(())
}
}
#[derive(Queueable)]
struct SendNewsletterSoon;
#[job(queue = "newsletters", retry_for = 30.seconds())]
impl SendNewsletterSoon {
async fn handle(self) -> laravel::Result<()> {
rate_limit::attempt("newsletter", Limit::per_minute(1)).await??;
Ok(())
}
}
#[derive(Queueable)]
struct ChargeCard;
#[job(retry_for = 1.minutes(), backoff = 45.seconds())]
impl ChargeCard {
async fn handle(self) -> laravel::Result<()> {
Err(laravel::abort_with(503, "the payment gateway is down"))
}
}
#[derive(Queueable)]
struct Unsteady(u32);
#[job(tries = 10, max_errors = 2)]
impl Unsteady {
async fn handle(self, records: Inject<Records>, attempt: &Attempt) -> laravel::Result<()> {
records.push(format!("unsteady {} ran as attempt {}", self.0, attempt.number()));
if attempt.number() == 1 {
attempt.release(30.seconds());
return Ok(());
}
Err(laravel::abort_with(500, format!("unsteady {} broke", self.0)))
}
}
#[derive(Queueable)]
struct Note(String);
#[job]
impl Note {
async fn handle(self, records: Inject<Records>) {
records.push(self.0);
}
}
#[derive(Queueable)]
struct Slow;
#[job(timeout = 100.milliseconds())]
impl Slow {
async fn handle(self) {
tokio::time::sleep(Duration::from_secs(30)).await;
}
}
#[derive(Queueable)]
struct Meet(u32);
#[derive(Default)]
struct Meeting(tokio::sync::watch::Sender<(usize, bool)>);
struct Present<'a>(&'a Meeting);
impl Drop for Present<'_> {
fn drop(&mut self) {
self.0.0.send_modify(|(present, _)| *present -= 1);
}
}
#[job(timeout = 1.seconds())]
impl Meet {
async fn handle(self, meeting: Inject<Meeting>, records: Inject<Records>) {
meeting.0.send_modify(|(present, met)| {
*present += 1;
*met |= *present >= 2;
});
let _present = Present(&meeting);
let _ = meeting.0.subscribe().wait_for(|(_, met)| *met).await;
records.push(format!("met {}", self.0));
}
}
#[derive(Queueable)]
struct Hold;
#[derive(Default)]
struct Gate(tokio::sync::watch::Sender<bool>);
#[job(timeout = 30.seconds())]
impl Hold {
async fn handle(self, gate: Inject<Gate>) {
let _ = gate.0.subscribe().wait_for(|open| *open).await;
}
}
#[derive(Default)]
struct Seen(Records);
#[derive(Clone, Default)]
struct Reported(std::sync::Arc<Records>);
const NOW: i64 = 1_800_000_000;
fn at(seconds: i64) -> Timestamp {
Timestamp::from_second(seconds).unwrap()
}
fn sql_at(seconds: i64) -> String {
format!("'{}'", at(seconds).strftime("%Y-%m-%dT%H:%M:%S+00:00"))
}
async fn application(url: impl Into<String>) -> Application {
application_with(url, |_| {}).await
}
async fn application_with(url: impl Into<String>, configure: impl FnOnce(&mut Config) + 'static) -> Application {
let url = url.into();
let reported = Reported::default();
let app = Application::configure()
.replace_env(Env::default())
.with_config(move |config, _| {
configure(config);
config.queue.default = "database".into();
config.database.default = "primary".into();
config
.database
.connections
.insert("primary".into(), ConnectionConfig::new(url));
})
.with_services({
let reported = reported.clone();
move |services| {
services.instance(Records::default());
services.instance(Seen::default());
services.instance(Meeting::default());
services.instance(Gate::default());
services.instance(reported);
}
})
.with_errors(move |errors, _| {
errors.report_all(move |error| {
let step = laravel::context::get::<String>("step");
reported.0.push(format!("{error} with step {step:?}"));
});
})
.with_events(|events, _| {
events.listen(|event: Event<JobProcessed>, seen: Inject<Seen>| async move {
seen.0.push(format!("{} {}", event.job.name, event.outcome));
});
events.listen(|event: Event<JobFailed>, seen: Inject<Seen>| async move {
seen.0
.push(format!("{} failed for good: {}", event.job.name, event.error));
});
})
.create();
app.scope(async || {
let connection = db::default_connection()?;
for table in ["jobs", "failed_jobs"] {
connection
.query(db::sqlx::AssertSqlSafe(format!("DROP TABLE IF EXISTS {table}")))
.statement()
.await?;
}
connection.query(create_table(connection.driver())).statement().await?;
connection
.query(create_failed_table(connection.driver()))
.statement()
.await
})
.await
.unwrap();
app.travel_to(Timestamp::from_second(NOW).unwrap());
app
}
#[cfg(feature = "database-sqlite")]
fn sqlite(name: &str) -> (crate::support::TempDir, String) {
let directory = crate::support::TempDir::new(name);
let url = format!("sqlite://{}?mode=rwc", directory.join("queue.sqlite").display());
(directory, url)
}
async fn work(app: &Application, options: &str) -> TestCommandResult {
tokio::time::timeout(
Duration::from_secs(30),
app.command(&format!("queue:work --stop-when-empty {options}")),
)
.await
.expect("the worker should stop once no job is available")
}
async fn dispatch<J: laravel::queue::Job>(app: &Application, job: J) -> JobId {
app.scope(async || laravel::queue::dispatch(job).await).await.unwrap()
}
async fn statement(app: &Application, sql: &str) {
app.scope(async || {
db::default_connection()?
.query(db::sqlx::AssertSqlSafe(sql.to_owned()))
.statement()
.await
})
.await
.unwrap();
}
#[derive(Debug, PartialEq, Eq, db::FromRow)]
struct Row {
queue: String,
attempts: i64,
reserved_at: Option<Timestamp>,
available_at: Timestamp,
}
async fn rows(app: &Application) -> Vec<Row> {
app.scope(async || {
db::default_connection()?
.query("SELECT queue, attempts, reserved_at, available_at FROM jobs ORDER BY id")
.select_as()
.await
})
.await
.unwrap()
}
#[derive(Debug, db::FromRow)]
struct FailedRow {
job_id: String,
connection: String,
queue: String,
error: String,
}
async fn failed(app: &Application) -> Vec<FailedRow> {
app.scope(async || {
db::default_connection()?
.query("SELECT job_id, connection, queue, error FROM failed_jobs ORDER BY id")
.select_as()
.await
})
.await
.unwrap()
}
async fn records(app: &Application) -> Vec<String> {
app.resolve::<Records>().await.all()
}
async fn reported(app: &Application) -> Vec<String> {
app.resolve::<Reported>().await.0.all()
}
async fn seen(app: &Application) -> Vec<String> {
app.resolve::<Seen>().await.0.all()
}
fn row(queue: &str, attempts: i64, available_in: i64) -> Row {
Row {
queue: queue.into(),
attempts,
reserved_at: None,
available_at: at(NOW + available_in),
}
}
async fn worker_contract(app: &Application) {
let flaky = "integration::queue_worker::Flaky";
let first = dispatch(app, Flaky { id: 1, failures: 2 }).await;
let second = dispatch(app, Flaky { id: 2, failures: 5 }).await;
let result = work(app, "").await;
result.assert_successful();
assert_eq!(
result.error_output().matches(" retrying ").count(),
2,
"{}",
result.error_output()
);
assert_eq!(
rows(app).await,
[row("default", 1, 10), row("default", 1, 10)],
"a failure waits out the first backoff"
);
app.travel(10.seconds());
work(app, "").await.assert_successful();
assert_eq!(
rows(app).await,
[row("default", 2, 10 + 60), row("default", 2, 10 + 60)],
"the second failure waits out the second backoff"
);
app.travel(1.minutes());
let result = work(app, "").await;
assert!(
crate::support::outcomes(result.error_output()).contains(&"done"),
"{}",
result.error_output()
);
assert!(result.error_output().contains(" failed "), "{}", result.error_output());
assert!(rows(app).await.is_empty());
assert_eq!(
records(app).await,
[
"flaky 1 ran as attempt 1",
"flaky 2 ran as attempt 1",
"flaky 1 ran as attempt 2",
"flaky 2 ran as attempt 2",
"flaky 1 ran as attempt 3",
"flaky 2 ran as attempt 3",
"failed hook for flaky 2: flaky 2 broke",
]
);
assert_eq!(
seen(app).await,
[
format!("{flaky} retrying"),
format!("{flaky} retrying"),
format!("{flaky} retrying"),
format!("{flaky} retrying"),
format!("{flaky} succeeded"),
format!("{flaky} failed for good: flaky 2 broke"),
format!("{flaky} failed"),
]
);
let failures = failed(app).await;
assert_eq!(failures.len(), 1);
assert_eq!(
(
failures[0].job_id.as_str(),
failures[0].connection.as_str(),
failures[0].queue.as_str()
),
(second.to_string().as_str(), "database", "default")
);
assert_eq!(failures[0].error, "flaky 2 broke");
assert_ne!(first, second);
app.command("queue:failed")
.await
.assert_successful()
.assert_output_contains(&second.to_string())
.assert_output_contains(flaky);
app.command(&format!("queue:retry {second}"))
.await
.assert_successful()
.assert_error_output_contains("` retried.");
assert!(failed(app).await.is_empty());
assert_eq!(rows(app).await, [row("default", 0, 70)], "a retried job starts over");
app.command("queue:clear").await.assert_successful();
dispatch(app, Flaky { id: 3, failures: 0 }).await;
dispatch(app, Poll).await;
statement(
app,
&format!("UPDATE jobs SET attempts = 1, reserved_at = {}", sql_at(NOW - 120)),
)
.await;
let result = work(app, "--queue=default,polls").await;
result.assert_successful();
let records = records(app).await;
assert_eq!(records.last().unwrap(), "flaky 3 ran as attempt 2", "{records:?}");
assert!(
!records.iter().any(|record| record.starts_with("poll")),
"a job without tries left doesn't run again"
);
let failures = failed(app).await;
assert_eq!(failures.len(), 1);
assert!(
failures[0]
.error
.contains("has been attempted more than its 1 `tries` allow"),
"{}",
failures[0].error
);
dispatch(app, Hold).await;
let held = async {
let reserved_at = wait_for_reservation(app, |_| true).await;
app.travel(45.seconds());
wait_for_reservation(app, |renewed| renewed == reserved_at + 45).await;
app.travel(30.seconds());
work(app, "").await.assert_successful();
assert_eq!(rows(app).await[0].attempts, 1, "another worker took the running job");
app.resolve::<Gate>().await.0.send_replace(true);
};
let (holding, ()) = tokio::join!(work(app, ""), held);
holding.assert_successful().assert_error_output_contains("Hold ");
for note in 0..40 {
dispatch(app, Note(format!("note {note:02}"))).await;
}
let (first, second) = tokio::join!(work(app, "--concurrency=4"), work(app, "--concurrency=4"));
first.assert_successful();
second.assert_successful();
let mut notes: Vec<_> = records_after(app, "note").await;
notes.sort();
assert_eq!(notes, (0..40).map(|note| format!("note {note:02}")).collect::<Vec<_>>());
assert!(rows(app).await.is_empty());
}
async fn wait_for_reservation(app: &Application, expected: impl Fn(i64) -> bool) -> i64 {
let reserved_at = async {
loop {
if let Some(reserved_at) = rows(app)
.await
.first()
.and_then(|row| row.reserved_at)
.map(Timestamp::as_second)
&& expected(reserved_at)
{
return reserved_at;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
};
tokio::time::timeout(Duration::from_secs(20), reserved_at)
.await
.expect("the worker should renew the job's reservation")
}
async fn records_after(app: &Application, prefix: &str) -> Vec<String> {
records(app)
.await
.into_iter()
.filter(|record| record.starts_with(prefix))
.collect()
}
async fn sizes(app: &Application) -> QueueSizes {
app.scope(async || {
let manager = laravel::queue::manager();
manager.sizes("database", "default").await
})
.await
.unwrap()
.expect("the database driver counts its jobs")
}
async fn sizes_contract(app: &Application) {
dispatch(app, Note("now".into())).await;
app.scope(async || Note("later".into()).dispatch().delay(30.seconds()).await)
.await
.unwrap();
dispatch(app, Note("running".into())).await;
dispatch(app, Note("abandoned".into())).await;
statement(
app,
&format!(
"UPDATE jobs SET attempts = 1, reserved_at = {} WHERE payload LIKE '%running%'",
sql_at(NOW)
),
)
.await;
statement(
app,
&format!(
"UPDATE jobs SET attempts = 1, reserved_at = {} WHERE payload LIKE '%abandoned%'",
sql_at(NOW - 120)
),
)
.await;
assert_eq!(
sizes(app).await,
QueueSizes {
pending: 2,
delayed: 1,
reserved: 1,
oldest_pending: Some(Timestamp::from_second(NOW).unwrap()),
approximate: false,
}
);
app.travel(30.seconds());
let due = sizes(app).await;
assert_eq!((due.pending, due.delayed, due.reserved), (3, 0, 1));
app.travel(1.minutes());
assert_eq!(sizes(app).await.pending, 4);
statement(app, "DELETE FROM jobs").await;
app.travel_to(Timestamp::from_second(NOW).unwrap());
assert_eq!(sizes(app).await, QueueSizes::default());
}
#[cfg(feature = "database-sqlite")]
#[tokio::test]
async fn sqlite_workers_retry_fail_and_recover_jobs() {
let (_directory, url) = sqlite("queue-worker");
let app = application(url).await;
sizes_contract(&app).await;
worker_contract(&app).await;
}
#[cfg(feature = "database-postgres")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"]
async fn postgres_queues_push_and_work_jobs() {
let url = std::env::var("LARAVEL_TEST_POSTGRES_URL").unwrap();
database_contracts(url).await;
}
#[cfg(feature = "database-mysql")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_MYSQL_URL pointing to a disposable database"]
async fn mysql_queues_push_and_work_jobs() {
let url = std::env::var("LARAVEL_TEST_MYSQL_URL").unwrap();
database_contracts(url).await;
}
#[cfg(any(feature = "database-postgres", feature = "database-mysql"))]
async fn database_contracts(url: String) {
let app = crate::queue::database::application(url.clone()).await;
crate::queue::database::push_contract(&app).await;
crate::queue::database::transaction_contract(&app).await;
crate::queue::database::bulk_contract(&app).await;
let app = application(url.clone()).await;
sizes_contract(&app).await;
worker_contract(&app).await;
#[cfg(feature = "database-sqlite")]
crate::queue_batches::concurrent_completion_contract(&crate::queue_batches::application(url, "database").await)
.await;
}
#[cfg(feature = "database-sqlite")]
mod sqlite {
use super::*;
#[tokio::test]
async fn workers_take_queues_in_priority_order_and_stop_after_max_jobs() {
let (_directory, url) = sqlite("queue-priority");
let app = application(url).await;
for (name, queue) in [
("low 1", "low"),
("high 1", "high"),
("low 2", "low"),
("high 2", "high"),
] {
app.scope(async || Note(name.into()).dispatch().on_queue(queue).await)
.await
.unwrap();
}
let result = work(&app, "--queue=high,low --max-jobs=3").await;
result.assert_successful().assert_error_output_contains(
"Processing jobs from `database:high`, `database:low`. Press Ctrl+C to stop.",
);
assert_eq!(records(&app).await, ["high 1", "high 2", "low 1"]);
assert_eq!(
result
.error_output()
.matches("integration::queue_worker::Note ")
.count(),
3
);
assert_eq!(rows(&app).await, [row("low", 0, 0)]);
}
#[tokio::test]
async fn a_job_running_past_its_timeout_fails() {
let (_directory, url) = sqlite("queue-timeout");
let app = application(url).await;
dispatch(&app, Slow).await;
work(&app, "")
.await
.assert_successful()
.assert_error_output_contains(" failed ");
let failures = failed(&app).await;
assert_eq!(failures.len(), 1);
assert_eq!(failures[0].error, "the job ran longer than its timeout of 100ms");
}
#[tokio::test]
async fn a_job_warns_on_each_retry_and_reports_only_its_last_failure() {
let (_directory, url) = sqlite("queue-reported-context");
let app = application(url).await;
dispatch(&app, Transcode).await;
let (lines, _guard) = crate::logging::Lines::capture();
work(&app, "").await.assert_successful();
assert_eq!(
reported(&app).await,
["the codec is missing with step Some(\"transcoding\")"]
);
let retries: Vec<_> = lines
.json()
.into_iter()
.filter(|line| line["target"] == "laravel::queue" && line["level"] == "WARN")
.map(|line| {
(
line["fields"]["message"].clone(),
line["fields"]["job"].clone(),
line["fields"]["attempt"].clone(),
line["fields"]["retry_in_ms"].clone(),
)
})
.collect();
assert_eq!(
retries,
[(
json!("The job failed and will be retried: the codec is missing"),
json!("integration::queue_worker::Transcode"),
json!(1),
json!(0),
)]
);
}
#[tokio::test]
async fn job_failures_remove_terminal_escapes_from_the_error() {
let (_directory, url) = sqlite("queue-escapes");
let app = application(url).await;
dispatch(&app, Reject).await;
let result = work(&app, "").await;
let output = result.error_output();
let (before, after) = output.split_once(" failed ").expect(output);
let (_duration, error) = after.split_once('\n').expect(output);
assert_eq!(
before,
"Processing jobs from `database:default`. Press Ctrl+C to stop.\nintegration::queue_worker::Reject"
);
assert_eq!(error, "payload rejected\n");
}
#[tokio::test]
async fn concurrent_workers_run_jobs_at_the_same_time() {
let (_directory, url) = sqlite("queue-concurrency");
let app = application(url).await;
dispatch(&app, Meet(1)).await;
dispatch(&app, Meet(2)).await;
work(&app, "--concurrency=2").await.assert_successful();
let mut met = records(&app).await;
met.sort();
assert_eq!(met, ["met 1", "met 2"]);
assert!(failed(&app).await.is_empty());
}
#[tokio::test]
async fn a_single_worker_runs_one_job_at_a_time() {
let (_directory, url) = sqlite("queue-sequential");
let app = application(url).await;
dispatch(&app, Meet(1)).await;
dispatch(&app, Meet(2)).await;
work(&app, "").await.assert_successful();
assert!(records(&app).await.is_empty(), "neither job met the other");
assert_eq!(failed(&app).await.len(), 2);
}
#[tokio::test]
async fn releases_use_tries_unless_the_job_retries_for_a_while() {
let (_directory, url) = sqlite("queue-releases");
let app = application(url).await;
dispatch(&app, Poll).await;
work(&app, "--queue=polls")
.await
.assert_error_output_contains(" released ");
assert_eq!(rows(&app).await, [row("polls", 1, 30)], "the job keeps its row");
app.travel(30.seconds());
work(&app, "--queue=polls")
.await
.assert_error_output_contains(" failed ");
assert_eq!(
records(&app).await,
["poll ran as attempt 1"],
"its one try was the release"
);
let failures = failed(&app).await;
assert_eq!(failures.len(), 1);
assert!(
failures[0].error.contains("attempted more than its 1 `tries` allow"),
"{}",
failures[0].error
);
dispatch(&app, PollForAnHour).await;
statement(&app, "UPDATE jobs SET attempts = 500").await;
work(&app, "--queue=polls")
.await
.assert_error_output_contains(" released ");
app.travel(2.hours());
work(&app, "--queue=polls")
.await
.assert_error_output_contains(" failed ");
let failures = failed(&app).await;
assert_eq!(failures.len(), 2);
assert!(
failures[1].error.contains("has run past its `retry_for`"),
"{}",
failures[1].error
);
}
#[tokio::test]
async fn a_job_that_would_retry_past_its_retry_for_fails_with_its_error() {
let (_directory, url) = sqlite("queue-retry-for-cause");
let app = application(url).await;
dispatch(&app, ChargeCard).await;
work(&app, "").await.assert_error_output_contains(" retrying ");
app.travel(45.seconds());
work(&app, "").await.assert_error_output_contains(" failed ");
let failures = failed(&app).await;
assert_eq!(failures.len(), 1);
let error = "`integration::queue_worker::ChargeCard` has run out of its `retry_for`, so it won't be retried: \
the payment gateway is down";
assert_eq!(failures[0].error, error);
assert_eq!(reported(&app).await, [format!("{error} with step None")]);
}
#[tokio::test]
async fn jobs_over_a_rate_limit_are_released_until_the_limit_allows_them() {
let (_directory, url) = sqlite("queue-rate-limited");
let app = application(url).await;
app.scope(async || rate_limit::hit("newsletter", Limit::per_minute(1)).await)
.await
.unwrap();
dispatch(&app, SendNewsletter).await;
work(&app, "--queue=newsletters")
.await
.assert_error_output_contains(" released ");
assert_eq!(rows(&app).await, [row("newsletters", 1, 60)]);
assert!(reported(&app).await.is_empty(), "a release isn't an error");
app.travel(1.minutes());
work(&app, "--queue=newsletters").await.assert_successful();
assert_eq!(records(&app).await, ["newsletter sent"]);
assert!(rows(&app).await.is_empty());
assert!(failed(&app).await.is_empty());
}
#[tokio::test]
async fn jobs_that_would_wait_past_their_retry_for_fail_over_the_rate_limit() {
let (_directory, url) = sqlite("queue-rate-limited-expiring");
let app = application(url).await;
app.scope(async || rate_limit::hit("newsletter", Limit::per_minute(1)).await)
.await
.unwrap();
dispatch(&app, SendNewsletterSoon).await;
work(&app, "--queue=newsletters")
.await
.assert_error_output_contains(" failed ");
assert!(rows(&app).await.is_empty());
let failures = failed(&app).await;
assert_eq!(failures.len(), 1);
assert!(failures[0].error.contains("Too Many Attempts"), "{}", failures[0].error);
}
#[tokio::test]
async fn quiet_workers_print_no_job_lines_even_for_failures() {
use crate::queue_middleware::{Decision, Guarded};
let (_directory, url) = sqlite("queue-quiet");
let app = application(url).await;
for decision in [Decision::Run, Decision::Error, Decision::Fail] {
dispatch(&app, Guarded::new(decision)).await;
}
work(&app, "-q").await.assert_successful().assert_no_output();
assert_eq!(rows(&app).await, [row("default", 1, 10)], "the error still retries");
assert_eq!(failed(&app).await.len(), 1, "the failure is still kept");
}
#[tokio::test]
async fn the_worker_runs_jobs_through_their_middleware() {
use crate::queue_middleware::{Decision, Guarded, WRAPPED};
let (_directory, url) = sqlite("queue-middleware");
let app = application(url).await;
for decision in [
Decision::Run,
Decision::Skip,
Decision::Release,
Decision::Error,
Decision::Fail,
] {
dispatch(&app, Guarded::new(decision)).await;
}
let result = work(&app, "").await;
result.assert_successful();
assert_eq!(
crate::support::outcomes(result.error_output()),
["done", "done", "released", "retrying", "failed"],
"{}",
result.error_output()
);
assert_eq!(
rows(&app).await,
[row("default", 1, 30), row("default", 1, 10)],
"the release waits its delay, and the error its backoff"
);
let failures = failed(&app).await;
assert_eq!(failures.len(), 1);
assert_eq!(failures[0].error, "the middleware refused");
let skipped = ["outer before", "outer after"];
assert_eq!(
records(&app).await,
[
&WRAPPED[..],
&skipped,
&skipped,
&["outer before", "outer after: the middleware refused"],
&skipped,
&["failed hook: the middleware refused"],
]
.concat()
);
}
#[tokio::test]
async fn max_errors_fails_a_job_after_its_errors_not_its_releases() {
let (_directory, url) = sqlite("queue-max-errors");
let app = application(url).await;
let id = dispatch(&app, Unsteady(1)).await;
work(&app, "").await.assert_error_output_contains(" released ");
app.travel(30.seconds());
work(&app, "")
.await
.assert_error_output_contains(" retrying ")
.assert_error_output_contains(" failed ");
assert_eq!(
records(&app).await,
[
"unsteady 1 ran as attempt 1",
"unsteady 1 ran as attempt 2",
"unsteady 1 ran as attempt 3",
]
);
let failures = failed(&app).await;
assert_eq!(
(failures.len(), failures[0].job_id.as_str()),
(1, id.to_string().as_str())
);
assert_eq!(failures[0].error, "unsteady 1 broke");
app.command(&format!("queue:retry {id}")).await.assert_successful();
work(&app, "").await.assert_successful();
assert_eq!(
rows(&app).await,
[row("default", 1, 60)],
"its first run released it again"
);
app.scope(async || {
laravel::cache::put(&format!("laravel:job-running:{id}"), true, 1.hours()).await?;
laravel::cache::put(&format!("laravel:job-errors:{id}"), 1, 1.hours()).await
})
.await
.unwrap();
app.travel(30.seconds());
work(&app, "").await.assert_error_output_contains(" failed ");
assert_eq!(records(&app).await.len(), 4, "the job didn't run again");
let failures = failed(&app).await;
assert!(
failures[0].error.contains("stopped its worker"),
"{}",
failures[0].error
);
}
#[tokio::test]
async fn unreadable_jobs_fail_for_good() {
let (_directory, url) = sqlite("queue-unreadable");
let app = application(url).await;
let id = "0199f3c2-0000-7000-8000-000000000000";
statement(
&app,
&format!(
"INSERT INTO jobs (queue, payload, attempts, available_at, created_at) VALUES \
('default', 'not json', 0, {epoch}, {epoch}), \
('default', '{{\"version\":1,\"id\":\"{id}\",\"job\":\"removed.job\",\"data\":null,\"dispatched_at\":0}}', 0, {epoch}, {epoch})",
epoch = sql_at(0)
),
)
.await;
let result = work(&app, "").await;
result
.assert_successful()
.assert_error_output_contains("removed.job failed ")
.assert_error_output_contains("an unreadable job failed ");
assert!(rows(&app).await.is_empty());
let failures = failed(&app).await;
assert_eq!(failures.len(), 2);
assert!(failures[0].error.contains("couldn't be read"), "{}", failures[0].error);
assert_eq!(failures[1].job_id, id);
assert!(
failures[1].error.contains("no job named `removed.job`"),
"{}",
failures[1].error
);
app.command("queue:retry all")
.await
.assert_exit_code(1)
.assert_error_output_contains(&format!("failed job `{}` couldn't be retried", failures[0].job_id))
.assert_error_output_contains(&format!("Failed job `{id}` retried."));
assert_eq!(rows(&app).await.len(), 1);
assert_eq!(failed(&app).await.len(), 1);
}
#[tokio::test]
async fn failed_jobs_can_be_listed_retried_forgotten_and_flushed() {
let (_directory, url) = sqlite("queue-failed");
let app = application(url).await;
app.command("queue:failed")
.await
.assert_successful()
.assert_error_output_contains("No failed jobs found.");
let ids = [
dispatch(&app, Flaky { id: 1, failures: 9 }).await,
dispatch(&app, Flaky { id: 2, failures: 9 }).await,
dispatch(&app, Flaky { id: 3, failures: 9 }).await,
];
statement(&app, "UPDATE jobs SET attempts = 2").await;
work(&app, "").await.assert_successful();
statement(
&app,
&format!("UPDATE failed_jobs SET failed_at = {}", sql_at(NOW - 7200)),
)
.await;
statement(
&app,
&format!(
"UPDATE failed_jobs SET failed_at = {} WHERE job_id = '{}'",
sql_at(NOW),
ids[2]
),
)
.await;
assert_eq!(failed(&app).await.len(), 3);
app.command(&format!("queue:forget {}", ids[0]))
.await
.assert_successful()
.assert_error_output_contains(format!("Failed job `{}` deleted.", ids[0]).as_str());
app.command(&format!("queue:forget {}", ids[0]))
.await
.assert_exit_code(1)
.assert_error_output_contains("no failed job has the ID");
app.command("queue:flush --hours=1")
.await
.assert_successful()
.assert_error_output_contains("1 failed job deleted.");
assert_eq!(failed(&app).await[0].job_id, ids[2].to_string());
app.command("queue:retry nonsense all")
.await
.assert_successful()
.assert_error_output_contains(format!("Failed job `{}` retried.", ids[2]).as_str());
assert!(failed(&app).await.is_empty());
assert_eq!(rows(&app).await.len(), 1);
app.command("queue:retry nonsense")
.await
.assert_exit_code(1)
.assert_error_output_contains("no failed job has the ID `nonsense`");
app.command("queue:clear")
.await
.assert_successful()
.assert_error_output_contains("1 job cleared from `database:default`.");
assert!(rows(&app).await.is_empty());
app.command("queue:flush").await.assert_successful();
}
#[tokio::test]
async fn without_a_failed_jobs_table_failures_are_discarded() {
let (_directory, url) = sqlite("queue-discard");
drop(application(url.clone()).await);
let app = Application::configure()
.replace_env(Env::default())
.with_config(move |config, _| {
config.queue.failed = laravel::config::queue::FailedJobs::Discard;
config.database.default = "primary".into();
config
.database
.connections
.insert("primary".into(), ConnectionConfig::new(url));
})
.with_services(|services| {
services.instance(Records::default());
})
.create();
dispatch(&app, Flaky { id: 1, failures: 9 }).await;
statement(&app, "UPDATE jobs SET attempts = 2").await;
work(&app, "")
.await
.assert_successful()
.assert_error_output_contains(" failed ");
assert!(rows(&app).await.is_empty());
app.command("queue:failed")
.await
.assert_successful()
.assert_error_output_contains("Failed jobs aren't kept");
app.command("queue:forget 1")
.await
.assert_exit_code(1)
.assert_error_output_contains("failed jobs aren't kept; `config.queue.failed` is `FailedJobs::Discard`");
}
#[tokio::test]
async fn only_database_connections_can_be_worked() {
let (_directory, url) = sqlite("queue-sync");
let app = application(url).await;
app.command("queue:work sync --stop-when-empty")
.await
.assert_exit_code(1)
.assert_error_output_contains(
"queue connection `sync` uses the `sync` driver, which keeps no jobs to work",
);
}
#[tokio::test]
async fn a_missing_table_stops_a_worker_that_stops_when_empty() {
let (_directory, url) = sqlite("queue-missing");
let app = application(url).await;
statement(&app, "DROP TABLE jobs").await;
work(&app, "").await.assert_exit_code(1);
}
#[tokio::test]
async fn workers_skip_paused_queues_until_they_are_resumed() {
let (_directory, url) = sqlite("queue-pause");
let app = application(url).await;
for (name, queue) in [("high", "high"), ("low", "low")] {
app.scope(async || Note(name.into()).dispatch().on_queue(queue).await)
.await
.unwrap();
}
app.command("queue:pause database:high")
.await
.assert_successful()
.assert_error_output_contains("Queue `database:high` paused.")
.assert_error_output_contains("Cache store `memory` only reaches this process.");
work(&app, "--queue=high,low")
.await
.assert_successful()
.assert_error_output_contains("Queue `high` paused.");
assert_eq!(records(&app).await, ["low"]);
app.command("queue:continue high")
.await
.assert_successful()
.assert_error_output_contains("Queue `database:high` resumed.");
work(&app, "--queue=high,low").await.assert_successful();
assert_eq!(records(&app).await, ["low", "high"]);
dispatch(&app, Note("default".into())).await;
app.command("queue:pause --all")
.await
.assert_successful()
.assert_error_output_contains("All queues paused.");
work(&app, "").await.assert_successful();
assert_eq!(records(&app).await, ["low", "high"]);
app.command("queue:continue database:default")
.await
.assert_successful()
.assert_error_output_contains("Queue `database:default` isn't paused.")
.assert_error_output_contains("All queues are still paused. Continue them with `queue:continue --all`.");
app.command("queue:continue --all")
.await
.assert_successful()
.assert_error_output_contains("All queues resumed.");
work(&app, "").await.assert_successful();
assert_eq!(records(&app).await, ["low", "high", "default"]);
app.command("queue:pause reports:high")
.await
.assert_exit_code(1)
.assert_error_output_contains("queue connection `reports` isn't defined");
app.command("queue:pause").await.assert_exit_code(2);
}
#[tokio::test]
async fn a_waiting_worker_notices_pauses_and_restarts() {
let (_directory, url) = sqlite("queue-idle-signals");
let app = application(url).await;
let worker = serve(&app, "--sleep=1");
let signals = async {
app.command("queue:pause default").await.assert_successful();
tokio::time::sleep(Duration::from_millis(200)).await;
dispatch(&app, Note("while paused".into())).await;
tokio::time::sleep(Duration::from_millis(1500)).await;
assert!(
records(&app).await.is_empty(),
"the worker took a job from a paused queue"
);
app.command("queue:continue default").await.assert_successful();
tokio::time::timeout(Duration::from_secs(10), async {
while records(&app).await.is_empty() {
tokio::time::sleep(Duration::from_millis(50)).await;
}
})
.await
.expect("the worker should take jobs once the queue is resumed");
app.command("queue:restart")
.await
.assert_successful()
.assert_error_output_contains("Restart signal sent.");
};
let (worker, ()) = tokio::join!(worker, signals);
worker
.assert_successful()
.assert_error_output_contains("Queue `default` paused.")
.assert_error_output_contains("Queue `default` resumed.")
.assert_error_output_contains("Restart signal received.");
assert_eq!(records(&app).await, ["while paused"]);
}
#[tokio::test]
async fn a_restarting_worker_finishes_its_running_job_and_takes_no_more() {
let (_directory, url) = sqlite("queue-restart");
let app = application(url).await;
dispatch(&app, Hold).await;
let worker = serve(&app, "");
let restart = async {
wait_for_reservation(&app, |_| true).await;
app.command("queue:restart").await.assert_successful();
dispatch(&app, Note("after the restart".into())).await;
app.resolve::<Gate>().await.0.send_replace(true);
};
let (worker, ()) = tokio::join!(worker, restart);
worker
.assert_successful()
.assert_error_output_contains("Hold ")
.assert_error_output_contains("Restart signal received.");
assert!(!worker.error_output().contains("Note"), "{}", worker.error_output());
assert_eq!(rows(&app).await, [row("default", 0, 0)]);
work(&app, "").await.assert_successful();
assert_eq!(records(&app).await, ["after the restart"]);
}
#[tokio::test]
async fn workers_keep_working_while_the_cache_is_unavailable() {
let (_directory, url) = sqlite("queue-signals-unavailable");
let app = application_with(url, |config| config.cache.default = "database".into()).await;
dispatch(&app, Note("cache unavailable".into())).await;
app.command("queue:pause default").await.assert_exit_code(1);
work(&app, "").await.assert_successful();
assert_eq!(records(&app).await, ["cache unavailable"]);
}
#[tokio::test]
async fn signals_need_a_cache_store_that_keeps_them() {
let (_directory, url) = sqlite("queue-signals-discard");
let app = application_with(url, |config| config.cache.default = "discard".into()).await;
for command in ["queue:restart", "queue:pause default", "queue:continue default"] {
app.command(command)
.await
.assert_exit_code(1)
.assert_error_output_contains("the default cache store `discard` keeps nothing");
}
}
}
async fn serve(app: &Application, options: &str) -> TestCommandResult {
tokio::time::timeout(Duration::from_secs(30), app.command(&format!("queue:work {options}")))
.await
.expect("the worker should restart")
}