use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use laravel::Application;
use laravel::config::Env;
use laravel::config::database::ConnectionConfig as DatabaseConnection;
use laravel::container::Inject;
use laravel::db::{self, Driver};
use laravel::queue::Queueable;
use laravel::queue::{self, Attempt, Batch, BatchId, Callback, Job, callback, job};
use laravel::testing::{MakesConsoleRequests, RunsJobs, TestCommandResult};
use laravel::time::ToSpan;
use crate::queue::Records;
use crate::queue::database::{create_failed_table, create_table};
#[derive(Debug, Queueable)]
struct Item {
name: String,
then: Option<String>,
}
fn item(name: &str) -> Item {
Item {
name: name.into(),
then: None,
}
}
fn item_then(name: &str, then: &str) -> Item {
Item {
name: name.into(),
then: Some(then.into()),
}
}
#[derive(Default)]
struct Repaired(AtomicBool);
struct Gate(tokio::sync::watch::Sender<bool>);
impl Default for Gate {
fn default() -> Self {
Self(tokio::sync::watch::channel(false).0)
}
}
#[job]
impl Item {
async fn handle(
self,
records: Inject<Records>,
repaired: Inject<Repaired>,
attempt: &Attempt,
) -> laravel::Result<()> {
records.push(self.name.clone());
let then = self.then.as_deref().unwrap_or_default();
let then = match then.strip_prefix("fail") {
Some(_) if !repaired.0.load(Ordering::SeqCst) => {
return Err(laravel::abort_with(500, format!("{} broke", self.name)));
}
Some(rest) => rest.trim_start_matches(','),
None => then,
};
match then {
"cancel" => attempt.cancel_batch(),
"tenant" => records.push(format!("tenant {:?}", laravel::context::get::<String>("tenant"))),
then => {
if let Some(names) = then.strip_prefix("add:") {
attempt.add_to_batch(names.split(',').map(item));
}
if let Some(names) = then.strip_prefix("append:") {
attempt.append_to_chain(names.split(',').map(item));
}
}
}
Ok(())
}
async fn failed(self, records: Inject<Records>) {
records.push(format!("failed {}", self.name));
}
}
#[derive(Queueable)]
struct Hold(String);
#[job(tries = 2)]
impl Hold {
async fn handle(self, records: Inject<Records>, gate: Inject<Gate>, attempt: &Attempt) {
records.push(self.0);
if attempt.number() == 1 {
let mut open = gate.0.subscribe();
let _ = tokio::time::timeout(Duration::from_secs(20), open.wait_for(|open| *open)).await;
}
}
}
#[derive(Queueable)]
struct Note(String);
#[callback]
impl Note {
async fn then(self, batch: &Batch, records: Inject<Records>, notes: Inject<Notes>) {
records.push(self.0);
notes.batches.lock().unwrap().push(batch.id());
}
async fn catch(self, error: &laravel::Error, records: Inject<Records>, notes: Inject<Notes>) {
records.push(self.0);
notes.errors.lock().unwrap().push(error.to_string());
}
async fn finally(self, batch: &Batch, records: Inject<Records>, notes: Inject<Notes>) {
records.push(self.0);
notes.batches.lock().unwrap().push(batch.id());
}
}
#[derive(Default)]
struct Notes {
batches: std::sync::Mutex<Vec<BatchId>>,
errors: std::sync::Mutex<Vec<String>>,
}
pub(crate) fn create_batch_tables(driver: Driver) -> [&'static str; 2] {
match driver {
Driver::MySql | Driver::MariaDb => [
"CREATE TABLE job_batches (
id VARCHAR(36) PRIMARY KEY,
name VARCHAR(255) NULL,
total_jobs INT NOT NULL,
pending_jobs INT NOT NULL,
failed_jobs INT NOT NULL,
options LONGTEXT NOT NULL,
created_at DATETIME(6) NOT NULL,
cancelled_at DATETIME(6) NULL,
finished_at DATETIME(6) NULL
)",
"CREATE TABLE job_batch_jobs (
batch_id VARCHAR(36) NOT NULL,
job_id VARCHAR(36) NOT NULL,
status VARCHAR(16) NOT NULL,
PRIMARY KEY (batch_id, job_id)
)",
],
_ => [
"CREATE TABLE job_batches (
id VARCHAR(36) PRIMARY KEY,
name VARCHAR(255),
total_jobs INTEGER NOT NULL,
pending_jobs INTEGER NOT NULL,
failed_jobs INTEGER NOT NULL,
options TEXT NOT NULL,
created_at TIMESTAMP(6) NOT NULL,
cancelled_at TIMESTAMP(6),
finished_at TIMESTAMP(6)
)",
"CREATE TABLE job_batch_jobs (
batch_id VARCHAR(36) NOT NULL,
job_id VARCHAR(36) NOT NULL,
status VARCHAR(16) NOT NULL,
PRIMARY KEY (batch_id, job_id)
)",
],
}
}
pub(crate) async fn application(url: String, default: &'static str) -> Application {
let app = Application::configure()
.replace_env(Env::default())
.with_config(move |config, _| {
config.queue.default = default.into();
config.database.default = "primary".into();
config
.database
.connections
.insert("primary".into(), DatabaseConnection::new(url));
})
.with_services(|services| {
services.instance(Records::default());
services.instance(Repaired::default());
services.instance(Gate::default());
services.instance(Notes::default());
})
.create();
app.scope(async || {
let connection = db::default_connection()?;
for table in ["job_batch_jobs", "job_batches", "failed_jobs", "jobs"] {
connection
.query(db::sqlx::AssertSqlSafe(format!("DROP TABLE IF EXISTS {table}")))
.statement()
.await?;
}
let driver = connection.driver();
for sql in [create_table(driver), create_failed_table(driver)]
.into_iter()
.chain(create_batch_tables(driver))
{
connection.query(sql).statement().await?;
}
Ok::<_, laravel::Error>(())
})
.await
.unwrap();
app
}
async fn sqlite(directory: &crate::support::TempDir, default: &'static str) -> Application {
let url = format!("sqlite://{}?mode=rwc", directory.join("batches.sqlite").display());
application(url, default).await
}
async fn records(app: &Application) -> Vec<String> {
app.resolve::<Records>().await.all()
}
async fn clear(app: &Application) {
app.resolve::<Records>().await.clear();
}
async fn work(app: &Application, options: &str) -> TestCommandResult {
tokio::time::timeout(
Duration::from_secs(60),
app.command(&format!("queue:work database --stop-when-empty {options}")),
)
.await
.expect("the worker should stop once no job is available")
}
async fn dispatch(app: &Application, batch: queue::PendingBatch) -> BatchId {
app.scope(async || batch.await).await.unwrap()
}
async fn find(app: &Application, id: BatchId) -> queue::Batch {
app.scope(async || queue::find_batch(id).await)
.await
.unwrap()
.expect("the batch is stored")
}
async fn counts(app: &Application, id: BatchId) -> (i64, i64, i64) {
app.scope(async || {
let row = db::default_connection()?
.query(db::sqlx::AssertSqlSafe(format!(
"SELECT total_jobs, pending_jobs, failed_jobs FROM job_batches WHERE id = '{id}'"
)))
.select_one()
.await?
.unwrap();
Ok::<_, laravel::Error>((row.try_get(0_usize)?, row.try_get(1_usize)?, row.try_get(2_usize)?))
})
.await
.unwrap()
}
#[tokio::test]
async fn sync_batches_run_their_jobs_then_call_their_callbacks() {
let directory = crate::support::TempDir::new("queue-batches-sync");
let app = sqlite(&directory, "sync").await;
let id = dispatch(
&app,
queue::batch([item("a"), item("b")])
.name("letters")
.then(Note("then".into()))
.catch(Note("catch".into()))
.finally(Note("finally".into())),
)
.await;
assert_eq!(records(&app).await, ["a", "b", "then", "finally"]);
let batch = find(&app, id).await;
assert_eq!(batch.name(), Some("letters"));
assert_eq!(
(
batch.total_jobs(),
batch.pending_jobs(),
batch.processed_jobs(),
batch.progress()
),
(2, 0, 2, 100)
);
assert!(batch.is_finished() && !batch.is_cancelled());
assert_eq!(
*app.resolve::<Notes>().await.batches.lock().unwrap(),
[id, id],
"callbacks receive their batch"
);
clear(&app).await;
let id = dispatch(
&app,
queue::batch([item("a"), item_then("b", "fail"), item("c")])
.then(Note("then".into()))
.catch(Note("catch".into()))
.finally(Note("finally".into())),
)
.await;
assert_eq!(records(&app).await, ["a", "b", "catch", "failed b", "finally"]);
assert_eq!(*app.resolve::<Notes>().await.errors.lock().unwrap(), ["b broke"]);
let batch = find(&app, id).await;
assert_eq!(
(batch.total_jobs(), batch.pending_jobs(), batch.failed_jobs()),
(3, 1, 1)
);
assert!(batch.is_cancelled() && batch.is_finished() && batch.has_failures());
clear(&app).await;
let id = dispatch(
&app,
queue::batch([item("a"), item_then("b", "fail"), item("c")])
.allow_failures()
.then(Note("then".into()))
.catch(Note("catch".into()))
.finally(Note("finally".into())),
)
.await;
assert_eq!(records(&app).await, ["a", "b", "catch", "failed b", "c", "finally"]);
assert!(!find(&app, id).await.is_cancelled());
clear(&app).await;
let id = dispatch(
&app,
queue::batch(Vec::<Item>::new())
.then(Note("then".into()))
.finally(Note("finally".into())),
)
.await;
assert_eq!(records(&app).await, ["then", "finally"]);
assert!(find(&app, id).await.is_finished());
}
#[tokio::test]
async fn chains_in_batches_and_batches_in_chains_run_in_order_and_count_as_their_jobs() {
let directory = crate::support::TempDir::new("queue-batches-nested");
let app = sqlite(&directory, "database").await;
let inner = queue::batch([item("bb1"), item("bb2")]).then(Note("inner then".into()));
let outer = queue::batch((item("b1"), queue::chain(item("bc1")).then(inner).then(item("bc2"))))
.then(Note("outer then".into()));
app.scope(async || queue::chain(item("c1")).then(outer).then(item("c2")).await)
.await
.unwrap();
work(&app, "").await.assert_successful();
assert_eq!(
records(&app).await,
["c1", "b1", "bc1", "bb1", "bb2", "inner then", "bc2", "outer then", "c2"],
"each batch waits for its chains, and each chain waits for its batches",
);
let totals: Vec<(i64, i64, i64)> = app
.scope(async || {
db::default_connection()?
.query("SELECT total_jobs, pending_jobs, failed_jobs FROM job_batches ORDER BY total_jobs DESC")
.select()
.await?
.iter()
.map(|row| Ok((row.try_get(0_usize)?, row.try_get(1_usize)?, row.try_get(2_usize)?)))
.collect::<laravel::Result<_>>()
})
.await
.unwrap();
assert_eq!(
totals,
[(4, 0, 0), (2, 0, 0)],
"the inner batch counts as one job of the outer one"
);
}
#[tokio::test]
async fn a_chain_can_start_with_a_batch_and_waits_for_it_to_finish() {
let directory = crate::support::TempDir::new("queue-batches-chain-start");
let app = sqlite(&directory, "database").await;
let start = app
.scope(async || {
queue::chain(queue::batch(["first", "second"].into_iter().map(item)))
.then(item("after"))
.await
})
.await
.unwrap();
let queue::ChainDispatched::Batch(id) = start else {
panic!("the chain should return its first batch's ID");
};
assert!(records(&app).await.is_empty());
assert_eq!(find(&app, id).await.total_jobs(), 2);
work(&app, "--max-jobs=1").await.assert_successful();
assert_eq!(records(&app).await, ["first"]);
work(&app, "").await.assert_successful();
assert_eq!(records(&app).await, ["first", "second", "after"]);
assert!(find(&app, id).await.is_finished());
}
#[tokio::test]
async fn an_empty_leading_batch_continues_but_a_delayed_leading_batch_is_rejected() {
let directory = crate::support::TempDir::new("queue-batches-chain-empty");
let app = sqlite(&directory, "sync").await;
app.scope(async || {
queue::chain(queue::batch(std::iter::empty::<Item>()))
.then(item("after empty"))
.await
})
.await
.unwrap();
assert_eq!(records(&app).await, ["after empty"]);
app.scope(async || {
let fake = queue::fake();
let error = queue::chain(queue::batch([item("never")]))
.delay(0.seconds())
.await
.unwrap_err();
assert_eq!(error.to_string(), "a chain starting with a batch can't have a delay");
fake.assert_nothing_pushed().assert_nothing_batched();
})
.await;
}
#[tokio::test]
async fn a_failing_batch_in_a_chain_stops_the_chain_unless_it_allows_failures() {
let directory = crate::support::TempDir::new("queue-batches-chain-failure");
let app = sqlite(&directory, "database").await;
let chain = |batch: queue::PendingBatch| {
queue::chain(item("c1"))
.then(batch.catch(Note("batch catch".into())))
.then(item("c2"))
.catch(Note("chain catch".into()))
};
let failing = || queue::batch([item("b1"), item_then("b2", "fail"), item("b3")]);
app.scope(async || chain(failing()).await).await.unwrap();
work(&app, "").await.assert_successful();
assert_eq!(
records(&app).await,
["c1", "b1", "b2", "batch catch", "chain catch", "failed b2"],
"the failing worker calls both catch callbacks, and the cancelled batch skips b3 and stops the chain",
);
clear(&app).await;
app.scope(async || chain(failing().allow_failures()).await)
.await
.unwrap();
work(&app, "").await.assert_successful();
assert_eq!(
records(&app).await,
["c1", "b1", "b2", "batch catch", "failed b2", "b3", "c2"],
);
clear(&app).await;
app.scope(async || {
queue::chain(failing().catch(Note("batch catch".into())))
.then(item("never"))
.catch(Note("chain catch".into()))
.await
})
.await
.unwrap();
work(&app, "").await.assert_successful();
assert_eq!(
records(&app).await,
["b1", "b2", "batch catch", "chain catch", "failed b2"]
);
clear(&app).await;
app.scope(async || queue::chain(failing().allow_failures()).then(item("after")).await)
.await
.unwrap();
work(&app, "").await.assert_successful();
assert_eq!(records(&app).await, ["b1", "b2", "failed b2", "b3", "after"]);
}
#[tokio::test]
async fn a_batch_that_cant_dispatch_a_job_is_cancelled_and_stops_its_chain_once() {
let directory = crate::support::TempDir::new("queue-batches-undispatchable");
let app = sqlite(&directory, "database").await;
let error = app
.scope(async || {
queue::batch((item("a"), queue::chain(item("b")).on_connection("missing")))
.finally(Note("finally".into()))
.await
})
.await
.unwrap_err();
assert!(error.to_string().contains("`missing`"), "{error}");
work(&app, "").await.assert_successful();
assert_eq!(
records(&app).await,
["finally"],
"the batch is cancelled, and its jobs are skipped"
);
clear(&app).await;
app.scope(async || {
queue::chain(item("x"))
.then(queue::batch([item("a")]).on_connection("missing"))
.catch(Note("catch".into()))
.await
})
.await
.unwrap();
work(&app, "").await.assert_successful();
assert_eq!(
records(&app).await,
["x", "catch"],
"the cancelled batch stops the chain, and x succeeded"
);
}
#[tokio::test]
async fn a_chain_that_cant_go_on_after_its_batch_fails_and_finishes_its_own_batch() {
let directory = crate::support::TempDir::new("queue-batches-stuck-continuation");
let app = sqlite(&directory, "database").await;
let id = dispatch(
&app,
queue::batch(
queue::chain(queue::batch([item("inner")]))
.then(item("never"))
.on_connection("missing")
.catch(Note("catch".into())),
)
.finally(Note("finally".into())),
)
.await;
work(&app, "").await.assert_successful();
assert_eq!(records(&app).await, ["inner", "catch", "finally"]);
let (_, pending, failed) = counts(&app, id).await;
assert_eq!((pending, failed), (1, 1), "the chain's steps settle as one failure");
}
#[tokio::test]
async fn jobs_add_to_and_cancel_their_batch_and_a_retry_clears_a_failure() {
let directory = crate::support::TempDir::new("queue-batches-running");
let app = sqlite(&directory, "database").await;
let id = dispatch(
&app,
queue::batch([item_then("loader", "add:x,y")]).then(Note("then".into())),
)
.await;
work(&app, "").await.assert_successful();
assert_eq!(records(&app).await, ["loader", "x", "y", "then"]);
assert_eq!(counts(&app, id).await, (3, 0, 0));
clear(&app).await;
let id = dispatch(
&app,
queue::batch([item_then("a", "cancel"), item("b")])
.then(Note("then".into()))
.finally(Note("finally".into())),
)
.await;
work(&app, "")
.await
.assert_successful()
.assert_error_output_contains(" deleted ");
assert_eq!(
records(&app).await,
["a", "finally"],
"b is skipped, and `then` never runs"
);
assert!(find(&app, id).await.is_cancelled());
clear(&app).await;
let id = dispatch(
&app,
queue::batch([item("a"), item_then("b", "fail")])
.allow_failures()
.then(Note("then".into()))
.finally(Note("finally".into())),
)
.await;
work(&app, "").await.assert_successful();
assert_eq!(records(&app).await, ["a", "b", "finally", "failed b"]);
assert_eq!(counts(&app, id).await, (2, 1, 1));
clear(&app).await;
app.resolve::<Repaired>().await.0.store(true, Ordering::SeqCst);
app.command("queue:retry all").await.assert_successful();
work(&app, "").await.assert_successful();
assert_eq!(
records(&app).await,
["b", "then"],
"the retry succeeds, so every job has"
);
assert_eq!(counts(&app, id).await, (2, 0, 0));
}
#[tokio::test]
async fn jobs_a_batch_job_adds_to_its_chain_and_a_retried_chain_count_as_the_batchs_jobs() {
let directory = crate::support::TempDir::new("queue-batches-chain-grows");
let app = sqlite(&directory, "database").await;
let id = dispatch(
&app,
queue::batch([item_then("a", "append:b,c")]).then(Note("then".into())),
)
.await;
work(&app, "").await.assert_successful();
assert_eq!(records(&app).await, ["a", "b", "c", "then"]);
assert_eq!(counts(&app, id).await, (3, 0, 0));
clear(&app).await;
let id = dispatch(
&app,
queue::batch([queue::chain(item_then("x", "fail")).then(item("y"))])
.allow_failures()
.then(Note("then".into()))
.finally(Note("finally".into())),
)
.await;
work(&app, "").await.assert_successful();
assert_eq!(records(&app).await, ["x", "finally", "failed x"]);
assert_eq!(counts(&app, id).await, (2, 1, 1));
clear(&app).await;
app.resolve::<Repaired>().await.0.store(true, Ordering::SeqCst);
app.command(&format!("queue:retry-batch {id}"))
.await
.assert_successful();
work(&app, "--max-jobs=1").await.assert_successful();
assert_eq!(records(&app).await, ["x"]);
assert_eq!(counts(&app, id).await, (2, 1, 0));
assert!(
!find(&app, id).await.is_finished(),
"the retry revived y, so the batch has work left"
);
work(&app, "").await.assert_successful();
assert!(find(&app, id).await.is_finished());
assert_eq!(
records(&app).await,
["x", "y", "then", "finally"],
"the retried job's chain runs before `then`, and `finally` runs again as the batch finishes again"
);
assert_eq!(counts(&app, id).await, (2, 0, 0));
}
#[tokio::test]
async fn a_retried_job_that_adds_jobs_reopens_its_finished_batch() {
let directory = crate::support::TempDir::new("queue-batches-retry-adds");
let app = sqlite(&directory, "database").await;
let id = dispatch(
&app,
queue::batch([item_then("a", "fail,add:b")])
.allow_failures()
.then(Note("then".into()))
.finally(Note("finally".into())),
)
.await;
work(&app, "").await.assert_successful();
assert_eq!(records(&app).await, ["a", "finally", "failed a"]);
assert!(find(&app, id).await.is_finished());
clear(&app).await;
app.resolve::<Repaired>().await.0.store(true, Ordering::SeqCst);
app.command(&format!("queue:retry-batch {id}"))
.await
.assert_successful();
work(&app, "--max-jobs=1").await.assert_successful();
assert_eq!(records(&app).await, ["a"]);
assert_eq!(counts(&app, id).await, (2, 1, 0));
assert!(
!find(&app, id).await.is_finished(),
"a added b, so the batch has work left"
);
work(&app, "").await.assert_successful();
assert_eq!(records(&app).await, ["a", "b", "then", "finally"]);
assert!(find(&app, id).await.is_finished());
}
#[tokio::test]
async fn a_job_that_runs_twice_is_counted_once() {
let directory = crate::support::TempDir::new("queue-batches-twice");
let app = sqlite(&directory, "database").await;
let id = dispatch(&app, queue::batch([Hold("twice".into())]).then(Note("then".into()))).await;
let second = async {
while !records(&app).await.contains(&"twice".to_owned()) {
tokio::time::sleep(Duration::from_millis(10)).await;
}
app.travel(2.minutes());
work(&app, "").await.assert_successful();
app.resolve::<Gate>().await.0.send_replace(true);
};
let (first, ()) = tokio::join!(work(&app, ""), second);
first.assert_successful();
assert_eq!(records(&app).await, ["twice", "twice", "then"]);
assert_eq!(
counts(&app, id).await,
(1, 0, 0),
"the second success of the same job isn't counted"
);
}
pub(crate) async fn concurrent_completion_contract(app: &Application) {
let id = dispatch(
app,
queue::batch((0..30).map(|n| item(&format!("job {n:02}"))).collect::<Vec<_>>())
.then(Note("then".into()))
.finally(Note("finally".into())),
)
.await;
let (first, second) = tokio::join!(work(app, "--concurrency=8"), work(app, "--concurrency=8"));
first.assert_successful();
second.assert_successful();
let records = records(app).await;
assert_eq!(records.iter().filter(|record| record.starts_with("job")).count(), 30);
assert_eq!(
records.iter().filter(|record| *record == "then").count(),
1,
"{records:?}"
);
assert_eq!(
records.iter().filter(|record| *record == "finally").count(),
1,
"{records:?}"
);
assert_eq!(counts(app, id).await, (30, 0, 0));
}
#[tokio::test]
async fn sqlite_batches_finish_once_when_jobs_finish_concurrently() {
let directory = crate::support::TempDir::new("queue-batches-concurrent");
concurrent_completion_contract(&sqlite(&directory, "database").await).await;
}
#[tokio::test]
async fn a_batch_dispatched_in_a_transaction_waits_for_the_commit() {
let directory = crate::support::TempDir::new("queue-batches-transaction");
let app = sqlite(&directory, "database").await;
let (during, committed) = app
.scope(async || {
let connection = db::default_connection().unwrap();
let rolled_back = connection
.transaction(async |_| {
queue::batch([item("never")]).await?;
Err::<(), _>(laravel::abort_with(500, "rolled back"))
})
.await;
assert!(rolled_back.is_err());
let mut id = None;
let during = connection
.transaction(async |tx| {
laravel::context::add("tenant", "acme");
id = Some(queue::batch([item_then("a", "tenant")]).await?);
laravel::context::add("tenant", "added after the dispatch");
tx.query("SELECT COUNT(*) FROM job_batches").scalar::<i64>().await
})
.await
.unwrap();
(during, id.unwrap())
})
.await;
assert_eq!(during, Some(0));
work(&app, "").await.assert_successful();
assert_eq!(records(&app).await, ["a", "tenant Some(\"acme\")"]);
assert!(find(&app, committed).await.is_finished());
}
#[tokio::test]
async fn a_leading_batch_and_its_continuation_wait_for_commit_and_are_discarded_on_rollback() {
let directory = crate::support::TempDir::new("queue-batches-leading-transaction");
let app = sqlite(&directory, "sync").await;
app.scope(async || {
let connection = db::default_connection().unwrap();
let rollback = connection
.transaction(async |_| {
queue::chain(queue::batch([item("never")]))
.then(item("also never"))
.await?;
Err::<(), _>(laravel::abort_with(500, "rolled back"))
})
.await;
assert!(rollback.is_err());
connection
.transaction(async |tx| {
queue::chain(queue::batch(std::iter::empty::<Item>()).then(Note("then".into())))
.then(item("after"))
.await?;
assert_eq!(
tx.query("SELECT COUNT(*) FROM job_batches").scalar::<i64>().await?,
Some(0)
);
assert!(laravel::resolve::<Records>().await?.all().is_empty());
Ok(())
})
.await
.unwrap();
let fake = queue::fake();
connection
.transaction(async |_| {
let start = queue::chain(queue::batch([item("faked")]))
.then(item("not run"))
.await?;
assert!(matches!(start, queue::ChainDispatched::Batch(_)));
fake.assert_nothing_batched();
Ok(())
})
.await
.unwrap();
fake.assert_batch_count(1).assert_nothing_pushed();
})
.await;
assert_eq!(records(&app).await, ["then", "after"]);
}
fn fake_application() -> Application {
Application::configure()
.replace_env(Env::default())
.with_services(|services| {
services.instance(Records::default());
services.instance(Repaired::default());
services.instance(Notes::default());
})
.create()
}
#[tokio::test]
async fn the_fake_records_batches_without_running_them() {
let app = fake_application();
app.scope(async || {
let queue = queue::fake();
queue.assert_nothing_batched();
let id = queue::batch((item("a"), queue::chain(item("b")).then(item("c"))))
.name("letters")
.on_queue("letters")
.allow_failures()
.then(Note("then".into()))
.await
.unwrap();
queue::chain(item("first"))
.then(queue::batch([item("x"), item("y")]))
.await
.unwrap();
queue.assert_batch_count(1).assert_batched(|batch| {
batch.id() == id
&& batch.name() == Some("letters")
&& batch.jobs().names() == [Item::NAME, Item::NAME]
&& batch.jobs().get::<Item>(1).is_some_and(|job| job.name == "b")
&& batch.chain(1).get::<Item>(0).is_some_and(|job| job.name == "c")
&& batch.chain(0).is_empty()
&& batch.then().names() == [Note::NAME]
&& batch.allows_failures()
&& batch.queue() == Some("letters")
});
queue.assert_pushed_where::<Item>(|job| {
job.name == "first"
&& job.chain().names() == ["batch"]
&& job.chain().batch(0).is_some_and(|batch| batch.jobs().len() == 2)
});
queue.assert_not_pushed_where::<Item>(|job| job.name == "a");
let batch = queue::find_batch(id).await.unwrap().unwrap();
assert_eq!((batch.total_jobs(), batch.pending_jobs(), batch.progress()), (3, 3, 0));
assert_eq!(
serde_json::to_value(&batch).unwrap()["total_jobs"],
serde_json::json!(3),
"a batch serializes for a route to return"
);
queue::cancel_batch(id).await.unwrap();
assert!(
queue::find_batch(id).await.unwrap().unwrap().is_cancelled(),
"the fake cancels a batch it recorded"
);
})
.await;
}
#[tokio::test]
async fn test_callbacks_run_against_a_batch_shaped_for_their_point() {
let app = fake_application();
app.callback(Note("then".into())).then().await.unwrap();
app.callback(Note("catch".into()))
.catch(laravel::abort_with(500, "row 812 is invalid"))
.await
.unwrap();
app.callback(Note("finally".into()))
.total_jobs(3)
.failed_jobs(1)
.cancelled()
.finally()
.await
.unwrap();
assert_eq!(app.resolve::<Records>().await.all(), ["then", "catch", "finally"]);
let notes = app.resolve::<Notes>().await;
assert_eq!(*notes.errors.lock().unwrap(), ["row 812 is invalid"]);
assert_eq!(notes.batches.lock().unwrap().len(), 2);
app.callback(Picky).then().await.unwrap();
let error = app
.callback(Picky)
.total_jobs(4)
.pending_jobs(1)
.then()
.await
.unwrap_err();
assert_eq!(error.to_string(), "3 of 4 jobs processed, unfinished");
assert!(app.callback(Picky).cancelled().then().await.is_err());
}
#[derive(Queueable)]
struct Picky;
#[callback]
impl Picky {
async fn then(self, batch: &Batch) -> laravel::Result<()> {
assert!(!batch.is_cancelled(), "a cancelled batch never calls then");
if !batch.is_finished() {
return Err(laravel::abort_with(
500,
format!(
"{} of {} jobs processed, unfinished",
batch.processed_jobs(),
batch.total_jobs()
),
));
}
Ok(())
}
}
#[tokio::test]
async fn test_attempts_in_a_batch_report_what_the_job_asked_of_it() {
let app = fake_application();
let result = app.job(item_then("loader", "add:x,y")).in_batch().await;
result.assert_succeeded();
assert_eq!(result.added_to_batch().names(), [Item::NAME, Item::NAME]);
assert_eq!(result.added_to_batch().get::<Item>(1).unwrap().name, "y");
app.job(item_then("a", "cancel"))
.in_batch()
.await
.assert_batch_cancelled();
let outside = app.job(item_then("loader", "add:x")).await;
outside.assert_failed();
assert!(
outside
.error()
.unwrap()
.to_string()
.contains("isn't one of a batch's jobs")
);
}
#[tokio::test]
async fn retry_batch_pushes_back_the_failed_jobs_of_batches_that_were_not_cancelled() {
let directory = crate::support::TempDir::new("queue-batches-retry");
let app = sqlite(&directory, "database").await;
let cancelled = dispatch(&app, queue::batch([item_then("x", "fail")])).await;
let id = dispatch(
&app,
queue::batch([item("a"), item_then("b", "fail"), item_then("c", "fail")])
.allow_failures()
.then(Note("then".into())),
)
.await;
work(&app, "").await.assert_successful();
assert_eq!(counts(&app, id).await, (3, 2, 2));
clear(&app).await;
app.resolve::<Repaired>().await.0.store(true, Ordering::SeqCst);
let result = app
.command(&format!("queue:retry-batch {id} {cancelled} missing"))
.await;
result
.assert_exit_code(1)
.assert_error_output_contains(&format!(
"batch `{cancelled}` was cancelled, so its failed jobs can't be retried"
))
.assert_error_output_contains("no batch has the ID `missing`");
assert_eq!(result.error_output().matches("` retried.").count(), 2);
work(&app, "").await.assert_successful();
let mut retried = records(&app).await;
retried[..2].sort();
assert_eq!(retried, ["b", "c", "then"]);
assert_eq!(counts(&app, id).await, (3, 0, 0));
app.command(&format!("queue:retry-batch {id}"))
.await
.assert_successful()
.assert_error_output_contains(&format!("Batch `{id}` has no failed jobs."));
let failed: Option<i64> = app
.scope(async || {
db::default_connection()?
.query("SELECT COUNT(*) FROM failed_jobs")
.scalar()
.await
})
.await
.unwrap();
assert_eq!(failed, Some(1), "the cancelled batch's failed job is kept");
}
#[tokio::test]
async fn prune_batches_deletes_old_batches_with_their_jobs() {
let directory = crate::support::TempDir::new("queue-batches-prune");
let app = sqlite(&directory, "database").await;
let now = jiff::Timestamp::now();
let literal = |hours: u64| {
format!(
"'{}'",
(now - Duration::from_secs(hours * 3600)).strftime("%Y-%m-%dT%H:%M:%S+00:00")
)
};
let (old, recent) = (literal(48), literal(1));
let mut ids = Vec::new();
for name in ["old finished", "recent finished", "old unfinished", "old cancelled"] {
ids.push(dispatch(&app, queue::batch([item(name), item(name)])).await);
}
for (id, set) in ids.iter().zip([
format!("created_at = {old}, finished_at = {old}"),
format!("created_at = {old}, finished_at = {recent}"),
format!("created_at = {old}"),
format!("created_at = {old}, finished_at = {recent}, cancelled_at = {recent}"),
]) {
statement(&app, &format!("UPDATE job_batches SET {set} WHERE id = '{id}'")).await;
}
app.command("queue:prune-batches")
.await
.assert_successful()
.assert_error_output_contains("1 finished batch deleted.");
assert_eq!(
stored_batches(&app).await,
[(ids[1], 2), (ids[2], 2), (ids[3], 2)].map(|(id, jobs)| (id.to_string(), jobs))
);
let result = app.command("queue:prune-batches --unfinished=24 --cancelled=24").await;
result.assert_successful();
assert_eq!(
result.error_output().lines().collect::<Vec<_>>(),
[
"No finished batches found.",
"1 unfinished batch deleted.",
"1 cancelled batch deleted."
]
);
assert_eq!(stored_batches(&app).await, [(ids[1].to_string(), 2)]);
}
async fn statement(app: &Application, sql: &str) {
app.scope(async || {
db::default_connection()?
.query(db::sqlx::AssertSqlSafe(sql.to_owned()))
.statement()
.await
})
.await
.unwrap();
}
async fn stored_batches(app: &Application) -> Vec<(String, i64)> {
app.scope(async || {
let rows = db::default_connection()?
.query(
"SELECT job_batches.id, (SELECT COUNT(*) FROM job_batch_jobs WHERE batch_id = job_batches.id) \
FROM job_batches ORDER BY job_batches.id",
)
.select()
.await?;
let orphans: Option<i64> = db::default_connection()?
.query("SELECT COUNT(*) FROM job_batch_jobs WHERE batch_id NOT IN (SELECT id FROM job_batches)")
.scalar()
.await?;
assert_eq!(orphans, Some(0), "no job rows outlive their batch");
rows.iter()
.map(|row| Ok((row.try_get(0_usize)?, row.try_get(1_usize)?)))
.collect::<laravel::Result<Vec<_>>>()
})
.await
.unwrap()
}