use std::collections::BTreeMap;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use laravel::Application;
use laravel::config::Env;
use laravel::config::queue::ConnectionConfig;
use laravel::container::Inject;
use laravel::queue::Queueable;
use laravel::queue::{self, Attempt, Callback, Job, callback, job};
use laravel::testing::RunsJobs;
use laravel::time::ToSpan;
use serde::{Deserialize, Serialize};
use crate::queue::Records;
#[derive(Debug, Serialize, Deserialize, Queueable)]
struct Step {
name: String,
then: Option<String>,
}
fn step(name: &str) -> Step {
Step {
name: name.into(),
then: None,
}
}
fn step_then(name: &str, then: &str) -> Step {
Step {
name: name.into(),
then: Some(then.into()),
}
}
#[derive(Default)]
struct Repaired(AtomicBool);
#[derive(Debug, thiserror::Error)]
#[error("{0} broke")]
struct Broke(String);
#[job]
impl Step {
async fn handle(
self,
records: Inject<Records>,
repaired: Inject<Repaired>,
attempt: &Attempt,
) -> laravel::Result<()> {
records.push(format!("{} on {}/{}", self.name, attempt.connection(), attempt.queue()));
match self.then.as_deref().unwrap_or_default().split_once(':') {
Some(("prepend", names)) => attempt.prepend_to_chain(names.split(',').map(step)),
Some(("append", name)) => attempt.append_to_chain(step(name)),
_ => {}
}
match self.then.as_deref() {
Some("fail") if !repaired.0.load(Ordering::SeqCst) => {
return Err(Broke(self.name).into());
}
Some("release") => attempt.release(30.seconds()),
Some("delete") => attempt.delete(),
_ => {}
}
Ok(())
}
async fn failed(self, error: &laravel::Error, records: Inject<Records>) {
records.push(format!("failed hook for {}: {error}", self.name));
}
}
#[derive(Queueable)]
struct Publish(String);
#[job(queue = "podcasts")]
impl Publish {
async fn handle(self, records: Inject<Records>, attempt: &Attempt) {
records.push(format!(
"publish {} on {}/{}",
self.0,
attempt.connection(),
attempt.queue()
));
}
}
#[derive(Queueable)]
struct Alert(String);
#[callback]
impl Alert {
async fn catch(self, error: &laravel::Error, records: Inject<Records>) {
let kind = if error.is::<Broke>() { "Broke" } else { "another error" };
records.push(format!("alert {}: {kind}: {error}", self.0));
}
}
#[derive(Queueable)]
struct Trail(String);
fn trail() -> String {
laravel::context::get::<Vec<String>>("trail")
.unwrap_or_default()
.join(">")
}
#[job]
impl Trail {
async fn handle(self, records: Inject<Records>) -> laravel::Result<()> {
let mut trail = laravel::context::get::<Vec<String>>("trail").unwrap_or_default();
trail.push(self.0.clone());
laravel::context::add("trail", &trail);
records.push(trail.join(">"));
if self.0.ends_with('!') {
return Err(Broke(self.0).into());
}
Ok(())
}
async fn failed(self, records: Inject<Records>) {
records.push(format!("failed hook sees {}", trail()));
}
}
#[derive(Queueable)]
struct SeeTrail;
#[callback]
impl SeeTrail {
async fn catch(self, records: Inject<Records>) {
records.push(format!("catch sees {}", trail()));
}
}
fn trail_chain(last: &str) -> queue::PendingChain {
queue::chain((Trail("a".into()), Trail("b".into()), Trail(last.into()))).catch(SeeTrail)
}
const TRAIL_RECORDS: [&str; 5] = ["a", "a>b", "a>b>c!", "catch sees a>b>c!", "failed hook sees a>b>c!"];
#[derive(Queueable)]
struct Unencodable(BTreeMap<(u8, u8), u8>);
#[job]
impl Unencodable {
async fn handle(self) {}
}
fn unencodable() -> Unencodable {
Unencodable(BTreeMap::from([((1, 2), 3)]))
}
fn configure(default: &'static str) -> laravel::foundation::ApplicationBuilder {
Application::configure()
.replace_env(Env::default())
.with_config(move |config, _| {
config.queue.default = default.into();
config.queue.add_connection("other", ConnectionConfig::Sync);
})
.with_services(|services| {
services.instance(Records::default());
services.instance(Repaired::default());
})
}
async fn records(app: &Application) -> Vec<String> {
app.resolve::<Records>().await.all()
}
async fn clear(app: &Application) {
app.resolve::<Records>().await.clear();
}
#[tokio::test]
async fn sync_chains_continue_after_success_or_delete_and_stop_at_a_release_or_failure() {
let app = configure("sync").create();
let start = app
.scope(async || {
queue::chain(["a"].into_iter().map(step))
.then(["skip", "b"].into_iter().filter(|name| *name != "skip").map(step))
.then(Publish("c".into()))
.await
})
.await
.unwrap();
assert!(matches!(start, queue::ChainDispatched::Job(_)));
assert_eq!(
records(&app).await,
["a on sync/default", "b on sync/default", "publish c on sync/podcasts"]
);
clear(&app).await;
app.scope(async || queue::chain(step_then("a", "delete")).then(step("b")).await)
.await
.unwrap();
assert_eq!(records(&app).await, ["a on sync/default", "b on sync/default"]);
clear(&app).await;
app.scope(async || queue::chain(step_then("a", "release")).then(step("b")).await)
.await
.unwrap();
assert_eq!(
records(&app).await,
["a on sync/default"],
"a release ends the job and the chain"
);
clear(&app).await;
let error = app
.scope(async || {
queue::chain(step("a"))
.then(step_then("b", "fail"))
.then(step("c"))
.catch(Alert("x".into()))
.catch(Alert("y".into()))
.await
})
.await
.unwrap_err();
assert_eq!(
error.to_string(),
"b broke",
"the failed job's error returns, not a wrapped one"
);
assert_eq!(
records(&app).await,
[
"a on sync/default",
"b on sync/default",
"alert x: Broke: b broke",
"alert y: Broke: b broke",
"failed hook for b: b broke",
],
"the failed job runs its hook once and the rest of the chain doesn't run"
);
}
#[tokio::test]
async fn each_job_in_a_chain_sees_the_context_values_the_jobs_before_it_added() {
let app = configure("sync").create();
let error = app.scope(async || trail_chain("c!").await).await.unwrap_err();
assert!(error.is::<Broke>(), "{error}");
assert_eq!(records(&app).await, TRAIL_RECORDS);
}
#[tokio::test]
async fn chains_take_tuples_of_mixed_jobs_and_lists_of_one_type() {
let app = configure("sync").create();
app.scope(async || {
queue::chain((step("a"), Publish("b".into())))
.then([step("c"), step("d")])
.then(vec![Publish("e".into())])
.await
})
.await
.unwrap();
assert_eq!(
records(&app).await,
[
"a on sync/default",
"publish b on sync/podcasts",
"c on sync/default",
"d on sync/default",
"publish e on sync/podcasts",
]
);
let error = app
.scope(async || queue::chain(Vec::<Step>::new()).then(Vec::<Publish>::new()).await)
.await
.unwrap_err();
assert_eq!(error.to_string(), "the chain has no jobs to dispatch");
app.scope(async || {
let fake = queue::fake();
queue::chain((step("a"), Publish("b".into()), step("c")))
.catch(Alert("x".into()))
.catch(Alert("y".into()))
.await
.unwrap();
fake.assert_chained::<(Step, Publish, Step)>()
.assert_pushed_where::<Step>(|job| job.chain_catch().names() == [Alert::NAME, Alert::NAME]);
})
.await;
}
#[tokio::test]
async fn a_chain_goes_to_its_connection_and_queue_and_otherwise_each_jobs_own() {
let app = configure("sync").create();
let error = app
.scope(async || {
queue::chain(step("a"))
.then(Publish("b".into()))
.on_connection("other")
.on_queue("shows")
.catch(Alert("x".into()))
.then(step_then("c", "fail"))
.await
})
.await
.unwrap_err();
assert_eq!(error.to_string(), "c broke");
assert_eq!(
records(&app).await,
[
"a on other/shows",
"publish b on other/shows",
"c on other/shows",
"alert x: Broke: c broke",
"failed hook for c: c broke",
]
);
clear(&app).await;
app.scope(async || {
queue::chain(step("a"))
.then(Publish("b".into()))
.on_connection("other")
.await
})
.await
.unwrap();
assert_eq!(
records(&app).await,
["a on other/default", "publish b on other/podcasts"]
);
}
#[tokio::test]
async fn running_jobs_add_to_their_chain_and_dispatch_sync_continues_it() {
let app = configure("sync").create();
app.scope(async || queue::chain(step_then("a", "prepend:x,w")).then(step("b")).await)
.await
.unwrap();
app.scope(async || queue::chain(step_then("c", "append:y")).then(step("d")).await)
.await
.unwrap();
assert_eq!(
records(&app).await,
[
"a on sync/default",
"x on sync/default",
"w on sync/default",
"b on sync/default",
"c on sync/default",
"d on sync/default",
"y on sync/default",
]
);
clear(&app).await;
app.scope(async || step_then("a", "append:b").dispatch_sync().await)
.await
.unwrap();
assert_eq!(records(&app).await, ["a on sync/default", "b on sync/default"]);
clear(&app).await;
app.scope(async || ReleaseAfter(step_then("a", "append:b")).dispatch_sync().await)
.await
.unwrap();
assert_eq!(
records(&app).await,
["a on sync/default"],
"jobs added by a released attempt don't run"
);
}
#[derive(Queueable)]
struct ReleaseAfter(Step);
#[job]
impl ReleaseAfter {
async fn handle(self, records: Inject<Records>, attempt: &Attempt) -> laravel::Result<()> {
records.push(format!(
"{} on {}/{}",
self.0.name,
attempt.connection(),
attempt.queue()
));
if let Some(("append", name)) = self.0.then.as_deref().and_then(|then| then.split_once(':')) {
attempt.append_to_chain(step(name));
}
attempt.release(1.seconds());
Ok(())
}
}
#[tokio::test]
async fn the_fake_records_the_first_job_with_the_rest_of_its_chain() {
let app = configure("sync").create();
app.scope(async || {
let fake = queue::fake();
let start = queue::chain(step("a"))
.then(step("b"))
.then(Publish("c".into()))
.on_queue("shows")
.delay(10.seconds())
.catch(Alert("x".into()))
.await
.unwrap();
assert_eq!(start, queue::ChainDispatched::Job(fake.pushed::<Step>()[0].id()));
step("lonely").dispatch().await.unwrap();
fake.assert_pushed_times::<Step>(2)
.assert_not_pushed::<Publish>()
.assert_chained::<(Step, Step, Publish)>()
.assert_pushed_without_chain::<Step>()
.assert_pushed_where::<Step>(|job| {
job.name == "a"
&& job.queue() == "shows"
&& job.delay() == Duration::from_secs(10)
&& job.chain().len() == 2
&& job.chain().get::<Step>(0).is_some_and(|b| b.name == "b")
&& job.chain().get::<Publish>(0).is_none()
&& job.chain().get::<Publish>(1).is_some_and(|c| c.0 == "c")
&& job.chain_catch().names() == [Alert::NAME]
});
for (wrong, message) in [
(
catch_unwind(AssertUnwindSafe(|| {
fake.assert_chained::<(Step, Publish)>();
})),
"expected job `integration::queue_chains::Step` to be pushed with the chain \
[\"integration::queue_chains::Publish\"]",
),
(
catch_unwind(AssertUnwindSafe(|| {
fake.assert_pushed_without_chain::<Publish>();
})),
"expected job `integration::queue_chains::Publish` to be pushed without a chain",
),
] {
let panic = wrong.unwrap_err();
let panic = panic.downcast_ref::<String>().unwrap();
assert!(panic.starts_with(message), "{panic}");
}
})
.await;
assert!(records(&app).await.is_empty());
let error = app
.scope(async || {
let fake = queue::fake();
let error = queue::chain(step("a"))
.then(std::iter::once(unencodable()))
.await
.unwrap_err();
fake.assert_nothing_pushed();
error
})
.await;
assert!(
error
.to_string()
.starts_with("the job `integration::queue_chains::Unencodable` couldn't be encoded"),
"{error}"
);
}
#[tokio::test]
async fn a_test_attempt_lists_the_jobs_it_added_without_running_them() {
let app = configure("sync").create();
let result = app.job(step_then("a", "prepend:x")).await;
result.assert_succeeded().assert_chained::<Step>();
assert_eq!(result.chain().names(), [Step::NAME]);
assert_eq!(result.chain().get::<Step>(0).unwrap().name, "x");
assert_eq!(records(&app).await, ["a on sync/default"]);
app.job(step_then("a", "prepend:x,y"))
.await
.assert_succeeded()
.assert_chained::<(Step, Step)>();
let wrong = catch_unwind(AssertUnwindSafe(|| {
result.assert_chained::<Publish>();
}));
let message = wrong
.unwrap_err()
.downcast::<String>()
.map_or_else(|_| String::new(), |message| *message);
assert!(
message.contains("expected job `integration::queue_chains::Step` to chain")
&& message.contains("integration::queue_chains::Publish"),
"{message}"
);
app.job(step("b")).await.assert_succeeded();
assert!(app.job(step("b")).await.chain().is_empty());
let result = app.job(AddsUnencodable).await;
result.assert_failed();
assert!(result.error().unwrap().to_string().contains("couldn't be encoded"));
}
#[derive(Queueable)]
struct AddsUnencodable;
#[job]
impl AddsUnencodable {
async fn handle(self, attempt: &Attempt) {
attempt.append_to_chain(unencodable());
}
}
#[cfg(feature = "database-sqlite")]
mod database {
use laravel::config::database::ConnectionConfig as DatabaseConnection;
use laravel::config::queue::DatabaseQueue;
use laravel::db;
use laravel::testing::{MakesConsoleRequests, TestCommandResult};
use super::*;
use crate::queue::database::{create_failed_table, create_table};
async fn application(directory: &crate::support::TempDir, default: &'static str) -> Application {
let url = format!("sqlite://{}?mode=rwc", directory.join("queue.sqlite").display());
let app = configure(default)
.with_config(move |config, _| {
config.database.default = "primary".into();
config
.database
.connections
.insert("primary".into(), DatabaseConnection::new(url));
config
.queue
.add_connection("broken", DatabaseQueue::new().table("missing_jobs"));
})
.create();
app.scope(async || {
let connection = db::default_connection()?;
connection.query(create_table(connection.driver())).statement().await?;
connection
.query(create_failed_table(connection.driver()))
.statement()
.await
})
.await
.unwrap();
app
}
async fn work(app: &Application, connection: &str) -> TestCommandResult {
tokio::time::timeout(
Duration::from_secs(30),
app.command(&format!(
"queue:work {connection} --stop-when-empty --queue=default,podcasts"
)),
)
.await
.expect("the worker should stop once no job is available")
}
async fn count(app: &Application, table: &str) -> i64 {
app.scope(async || {
db::default_connection()?
.query(db::sqlx::AssertSqlSafe(format!("SELECT COUNT(*) FROM {table}")))
.scalar::<i64>()
.await
})
.await
.unwrap()
.unwrap()
}
#[tokio::test]
async fn the_worker_runs_a_chain_in_order_and_retrying_a_failed_job_resumes_it() {
let directory = crate::support::TempDir::new("queue-chains-worker");
let app = application(&directory, "database").await;
app.scope(async || {
queue::chain(step_then("a", "append:z"))
.then(Publish("b".into()))
.then(step("c"))
.await
})
.await
.unwrap();
assert_eq!(count(&app, "jobs").await, 1, "only the first job is queued");
let output = work(&app, "database").await;
output.assert_successful();
assert!(
!output.error_output().contains(" failed "),
"{}",
output.error_output()
);
assert_eq!(
records(&app).await,
[
"a on database/default",
"publish b on database/podcasts",
"c on database/default",
"z on database/default",
]
);
clear(&app).await;
app.scope(async || {
queue::chain(step("a"))
.then(step_then("b", "fail"))
.then(step("c"))
.catch(Alert("x".into()))
.await
})
.await
.unwrap();
work(&app, "database")
.await
.assert_successful()
.assert_error_output_contains(" failed ");
assert_eq!(
records(&app).await,
[
"a on database/default",
"b on database/default",
"alert x: Broke: b broke",
"failed hook for b: b broke",
]
);
assert_eq!(count(&app, "failed_jobs").await, 1);
clear(&app).await;
app.resolve::<Repaired>().await.0.store(true, Ordering::SeqCst);
app.command("queue:retry all").await.assert_successful();
work(&app, "database").await.assert_successful();
assert_eq!(
records(&app).await,
["b on database/default", "c on database/default"],
"the retried job carries the rest of its chain"
);
assert_eq!(count(&app, "jobs").await, 0);
assert_eq!(count(&app, "failed_jobs").await, 0);
}
#[tokio::test]
async fn the_worker_passes_context_values_down_the_chain() {
let directory = crate::support::TempDir::new("queue-chains-context");
let app = application(&directory, "database").await;
app.scope(async || trail_chain("c!").await).await.unwrap();
work(&app, "database").await.assert_successful();
assert_eq!(records(&app).await, TRAIL_RECORDS);
}
#[tokio::test]
async fn a_job_whose_next_job_cant_be_dispatched_fails_for_good() {
let directory = crate::support::TempDir::new("queue-chains-broken");
let app = application(&directory, "broken").await;
let error = app
.scope(async || queue::chain(step("a")).then(step("b")).await)
.await
.unwrap_err();
assert!(error.to_string().contains("missing_jobs"), "{error}");
assert!(records(&app).await.is_empty());
app.scope(async || step_then("a", "append:b").dispatch().on_connection("database").await)
.await
.unwrap();
work(&app, "database")
.await
.assert_successful()
.assert_error_output_contains(" failed ");
let records = records(&app).await;
assert_eq!(records.len(), 2, "{records:?}");
assert_eq!(records[0], "a on database/default");
assert!(records[1].starts_with("failed hook for a: "), "{records:?}");
assert_eq!(count(&app, "failed_jobs").await, 1);
assert_eq!(count(&app, "jobs").await, 0);
}
#[tokio::test]
async fn a_chain_dispatched_in_a_transaction_waits_for_the_commit() {
let directory = crate::support::TempDir::new("queue-chains-transaction");
let app = application(&directory, "database").await;
let during = app
.scope(async || {
let connection = db::default_connection().unwrap();
let rolled_back = connection
.transaction(async |_| {
queue::chain(step("never")).then(step("ever")).await?;
Err::<(), _>(laravel::abort_with(500, "rolled back"))
})
.await;
assert!(rolled_back.is_err());
connection
.transaction(async |tx| {
queue::chain(step("a")).then(step("b")).await?;
tx.query("SELECT COUNT(*) FROM jobs").scalar::<i64>().await
})
.await
.unwrap()
})
.await;
assert_eq!(during, Some(0));
assert_eq!(count(&app, "jobs").await, 1);
work(&app, "database").await.assert_successful();
assert_eq!(records(&app).await, ["a on database/default", "b on database/default"]);
}
}