use std::collections::BTreeMap;
use std::time::{Duration, Instant};
use laravel::Application;
use laravel::config::Env;
use laravel::config::queue::{FailedJobs, RedisQueue};
use laravel::config::redis::ConnectionConfig;
use laravel::container::Inject;
use laravel::foundation::ApplicationBuilder;
use laravel::queue::Queueable;
use laravel::queue::{Attempt, QueueSizes, job};
use laravel::redis::{RedisManager, client};
use laravel::testing::{MakesConsoleRequests, TestCommandResult};
use laravel::time::{Timestamp, ToSpan};
use crate::queue::Records;
use crate::redis::{key, server};
#[derive(Queueable)]
struct Flaky {
id: u32,
failures: u32,
}
#[job(name = "redis.flaky", 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 ReleaseOnce;
#[job(name = "redis.release_once", tries = 2)]
impl ReleaseOnce {
async fn handle(self, records: Inject<Records>, attempt: &Attempt) {
records.push(format!("release ran as attempt {}", attempt.number()));
if attempt.number() == 1 {
attempt.release(30.seconds());
}
}
}
#[derive(Queueable)]
struct Note(String);
#[job(name = "redis.note")]
impl Note {
async fn handle(self, records: Inject<Records>, attempt: &Attempt) {
records.push(format!("{} as attempt {}", self.0, attempt.number()));
}
}
#[derive(Queueable)]
struct Hold;
#[derive(Default)]
struct Gate(tokio::sync::watch::Sender<u32>);
#[job(name = "redis.hold", tries = 2, timeout = 60.seconds())]
impl Hold {
async fn handle(self, gate: Inject<Gate>, records: Inject<Records>, attempt: &Attempt) {
records.push(format!("hold ran as attempt {}", attempt.number()));
let _ = gate.0.subscribe().wait_for(|open| *open >= attempt.number()).await;
}
}
const NOW: i64 = 1_800_000_000;
const NOW_MS: i64 = NOW * 1000;
fn configure(block_for: Option<Duration>) -> (ApplicationBuilder, String) {
let (url, queue) = (server(), key("jobs"));
let mut connection = RedisQueue::new().queue(&queue);
connection.block_for = block_for.map(Into::into);
let builder = Application::configure()
.replace_env(Env::default())
.with_config(move |config, _| {
config
.redis
.add_connection("default", ConnectionConfig::new(url).database(14));
config.queue.default = "redis".into();
config.queue.failed = FailedJobs::Discard;
config.queue.add_connection("redis", connection);
})
.with_services(|services| {
services.instance(Records::default());
services.instance(Gate::default());
});
(builder, queue)
}
fn application(block_for: Option<Duration>) -> (Application, String) {
let (builder, queue) = configure(block_for);
let app = builder.create();
app.travel_to(Timestamp::from_second(NOW).unwrap());
(app, queue)
}
async fn work(app: &Application, options: &str) -> TestCommandResult {
tokio::time::timeout(
Duration::from_secs(60),
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) {
app.scope(async || laravel::queue::dispatch(job).await).await.unwrap();
}
async fn records(app: &Application) -> Vec<String> {
app.resolve::<Records>().await.all()
}
#[derive(Debug, PartialEq, Eq)]
struct State {
available: Vec<String>,
delayed: Vec<(String, i64)>,
reserved: Vec<(String, i64)>,
attempts: BTreeMap<String, u32>,
payloads: usize,
notify: usize,
}
async fn state(app: &Application, queue: &str) -> State {
let mut redis = app.resolve::<RedisManager>().await.default_connection().unwrap();
let key = |suffix: &str| format!("queues:{{{queue}}}{suffix}");
let stored: BTreeMap<String, String> = client::cmd("HGETALL")
.arg(key(":payloads"))
.query_async(&mut redis)
.await
.unwrap();
let names: BTreeMap<String, String> = stored
.iter()
.map(|(id, payload)| {
assert!(id.len() == 36 && id.as_bytes()[14] == b'7', "{id} is a UUID v7");
(id.clone(), name(payload))
})
.collect();
let name_of = |id: String| names.get(&id).cloned().unwrap_or_else(|| format!("missing {id}"));
let available: Vec<String> = client::cmd("LRANGE")
.arg(key(""))
.arg(0)
.arg(-1)
.query_async(&mut redis)
.await
.unwrap();
let mut scored = async |suffix: &str| -> Vec<(String, i64)> {
client::cmd("ZRANGE")
.arg(key(suffix))
.arg(0)
.arg(-1)
.arg("WITHSCORES")
.query_async(&mut redis)
.await
.unwrap()
};
let delayed = scored(":delayed").await;
let reserved = scored(":reserved").await;
let attempts: BTreeMap<String, u32> = client::cmd("HGETALL")
.arg(key(":attempts"))
.query_async(&mut redis)
.await
.unwrap();
let notify = client::cmd("LLEN")
.arg(key(":notify"))
.query_async(&mut redis)
.await
.unwrap();
let scored_by_name = |jobs: Vec<(String, i64)>| jobs.into_iter().map(|(id, at)| (name_of(id), at)).collect();
State {
available: available.into_iter().map(name_of).collect(),
delayed: scored_by_name(delayed),
reserved: scored_by_name(reserved),
attempts: attempts.into_iter().map(|(id, count)| (name_of(id), count)).collect(),
payloads: stored.len(),
notify,
}
}
fn name(payload: &str) -> String {
let payload: serde_json::Value = serde_json::from_str(payload).unwrap();
match payload["job"].as_str().unwrap() {
"redis.flaky" => format!("flaky {}", payload["data"]["id"]),
"redis.note" => payload["data"][0].as_str().unwrap().to_owned(),
"redis.release_once" => "release".to_owned(),
"redis.hold" => "hold".to_owned(),
other => other.to_owned(),
}
}
fn named<const N: usize>(names: [&str; N]) -> Vec<String> {
names.map(str::to_owned).to_vec()
}
fn scored<const N: usize>(jobs: [(&str, i64); N]) -> Vec<(String, i64)> {
jobs.map(|(name, at)| (name.to_owned(), at)).to_vec()
}
fn attempts<const N: usize>(jobs: [(&str, u32); N]) -> BTreeMap<String, u32> {
jobs.into_iter().map(|(name, count)| (name.to_owned(), count)).collect()
}
fn empty() -> State {
State {
available: Vec::new(),
delayed: Vec::new(),
reserved: Vec::new(),
attempts: BTreeMap::new(),
payloads: 0,
notify: 0,
}
}
async fn wait_for(app: &Application, queue: &str, expected: impl Fn(&State) -> bool) -> State {
let waited = async {
loop {
let state = state(app, queue).await;
if expected(&state) {
return state;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
};
tokio::time::timeout(Duration::from_secs(20), waited)
.await
.expect("the queue should reach the expected state")
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn failed_attempts_wait_out_their_backoff_then_fail_for_good() {
let (app, queue) = application(None);
dispatch(&app, Flaky { id: 1, failures: 2 }).await;
dispatch(&app, Flaky { id: 2, failures: 5 }).await;
assert_eq!(
state(&app, &queue).await,
State {
available: named(["flaky 1", "flaky 2"]),
payloads: 2,
notify: 2,
..empty()
}
);
let result = work(&app, "").await;
result.assert_successful();
assert_eq!(
result.error_output().matches(" retrying ").count(),
2,
"{}",
result.error_output()
);
assert_eq!(
state(&app, &queue).await,
State {
delayed: scored([("flaky 1", NOW_MS + 10_000), ("flaky 2", NOW_MS + 10_000)]),
attempts: attempts([("flaky 1", 1), ("flaky 2", 1)]),
payloads: 2,
..empty()
},
"a failure waits out the first backoff"
);
app.travel(10.seconds());
work(&app, "").await.assert_successful();
assert_eq!(
state(&app, &queue).await.delayed,
scored([("flaky 1", NOW_MS + 70_000), ("flaky 2", NOW_MS + 70_000)]),
"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_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!(state(&app, &queue).await, empty());
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn released_jobs_go_to_the_back_of_the_queue_and_delayed_jobs_wait() {
let (app, queue) = application(None);
dispatch(&app, ReleaseOnce).await;
dispatch(&app, Note("first".into())).await;
app.scope(async || Note("delayed".into()).dispatch().delay(5.minutes()).await)
.await
.unwrap();
work(&app, "").await.assert_error_output_contains(" released ");
assert_eq!(records(&app).await, ["release ran as attempt 1", "first as attempt 1"]);
assert_eq!(
state(&app, &queue).await,
State {
delayed: scored([("release", NOW_MS + 30_000), ("delayed", NOW_MS + 300_000)]),
attempts: attempts([("release", 1)]),
payloads: 2,
..empty()
},
"the release waits its delay, keeping its attempt"
);
dispatch(&app, Note("second".into())).await;
app.travel(30.seconds());
assert_eq!(
crate::support::outcomes(work(&app, "--max-jobs=1").await.error_output()),
["done"]
);
assert_eq!(
state(&app, &queue).await.available,
["release"],
"the due job joined behind the second note"
);
work(&app, "").await.assert_successful();
assert_eq!(
records(&app).await[2..],
["second as attempt 1", "release ran as attempt 2"]
);
app.travel(5.minutes());
work(&app, "").await.assert_successful();
assert_eq!(records(&app).await[4..], ["delayed as attempt 1"]);
assert_eq!(state(&app, &queue).await, empty());
dispatch(&app, Note("cleared".into())).await;
app.scope(async || Note("cleared later".into()).dispatch().delay(1.minutes()).await)
.await
.unwrap();
app.command("queue:clear")
.await
.assert_successful()
.assert_error_output_contains("2 jobs cleared from `redis:");
assert_eq!(state(&app, &queue).await, empty());
dispatch(&app, Note("after clearing".into())).await;
assert_eq!(state(&app, &queue).await.available, ["after clearing"]);
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn a_lapsed_reservation_goes_to_another_worker_and_the_first_leaves_the_job_alone() {
let (app, queue) = application(None);
dispatch(&app, Hold).await;
let gate = app.resolve::<Gate>().await;
let (first_done, first_finished) = tokio::sync::oneshot::channel();
let first = async {
let result = work(&app, "").await;
first_done.send(()).unwrap();
result
};
let others = async {
let reserved = wait_for(&app, &queue, |state| !state.reserved.is_empty()).await;
assert_eq!(reserved.reserved, scored([("hold", NOW_MS + 60_000)]));
app.travel(45.seconds());
wait_for(&app, &queue, |state| {
state.reserved == scored([("hold", NOW_MS + 105_000)])
})
.await;
app.travel(30.seconds());
work(&app, "").await.assert_successful();
assert_eq!(
records(&app).await,
["hold ran as attempt 1"],
"no other worker took it"
);
app.travel(1.minutes());
let second = work(&app, "");
let settle = async {
let taken = wait_for(&app, &queue, |state| state.attempts.get("hold") == Some(&2)).await;
assert_eq!(taken.reserved, scored([("hold", NOW_MS + 195_000)]));
gate.0.send_replace(1);
first_finished.await.unwrap();
assert_eq!(
state(&app, &queue).await,
State {
reserved: scored([("hold", NOW_MS + 195_000)]),
attempts: attempts([("hold", 2)]),
payloads: 1,
..empty()
}
);
gate.0.send_replace(2);
};
let (second, ()) = tokio::join!(second, settle);
second.assert_successful();
assert!(
crate::support::outcomes(second.error_output()).contains(&"done"),
"{}",
second.error_output()
);
};
let (first, ()) = tokio::join!(first, others);
first.assert_successful();
assert_eq!(records(&app).await, ["hold ran as attempt 1", "hold ran as attempt 2"]);
assert_eq!(state(&app, &queue).await, empty());
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn workers_racing_for_jobs_each_take_different_ones() {
let (app, queue) = application(Some(Duration::from_millis(200)));
for note in 0..40 {
dispatch(&app, Note(format!("note {note:02}"))).await;
}
let (first, second, third) = tokio::join!(
work(&app, "--concurrency=4"),
work(&app, "--concurrency=4"),
work(&app, "--concurrency=4"),
);
first.assert_successful();
second.assert_successful();
third.assert_successful();
let mut notes = records(&app).await;
notes.sort();
assert_eq!(
notes,
(0..40)
.map(|note| format!("note {note:02} as attempt 1"))
.collect::<Vec<_>>()
);
assert_eq!(state(&app, &queue).await, empty());
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn a_waiting_worker_takes_a_job_once_it_is_pushed_and_stopping_it_loses_nothing() {
let (app, queue) = application(Some(Duration::from_secs(10)));
let waiting = tokio::time::timeout(Duration::from_millis(500), app.command("queue:work")).await;
assert!(waiting.is_err(), "the worker was still waiting");
tokio::time::sleep(Duration::from_millis(200)).await;
dispatch(&app, Note("kept".into())).await;
assert_eq!(
state(&app, &queue).await,
State {
available: named(["kept"]),
payloads: 1,
notify: 1,
..empty()
}
);
work(&app, "--max-jobs=1").await.assert_successful();
assert_eq!(records(&app).await, ["kept as attempt 1"]);
let started = Instant::now();
let worker = app.command("queue:work --sleep=30 --max-jobs=1");
let push = async {
tokio::time::sleep(Duration::from_millis(500)).await;
dispatch(&app, Note("woken".into())).await;
};
let (result, ()) = tokio::join!(worker, push);
result.assert_successful();
assert!(started.elapsed() < Duration::from_secs(3), "{:?}", started.elapsed());
assert_eq!(records(&app).await[1..], ["woken as attempt 1"]);
assert_eq!(state(&app, &queue).await, empty());
let worker = app.command("queue:work --sleep=30 --max-jobs=1");
let push = async {
tokio::time::sleep(Duration::from_millis(500)).await;
tokio::join!(
dispatch(&app, Note("first".into())),
dispatch(&app, Note("second".into()))
);
};
let (result, _) = tokio::join!(worker, push);
result.assert_successful();
let after = state(&app, &queue).await;
assert_eq!((after.available.len(), after.notify), (1, 1), "{after:?}");
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn a_waiting_worker_whose_job_was_taken_leaves_no_stale_notify_token() {
let (app, queue) = application(Some(Duration::from_secs(10)));
let mut redis = app.resolve::<RedisManager>().await.default_connection().unwrap();
let worker = app.command("queue:work --stop-when-empty");
let wake = async {
tokio::time::sleep(Duration::from_millis(300)).await;
let () = client::cmd("RPUSH")
.arg(format!("queues:{{{queue}}}:notify"))
.arg(1)
.query_async(&mut redis)
.await
.unwrap();
};
let (result, ()) = tokio::join!(worker, wake);
result.assert_successful();
assert_eq!(state(&app, &queue).await, empty());
let () = client::cmd("RPUSH")
.arg(format!("queues:{{{queue}}}:notify"))
.arg(1)
.query_async(&mut redis)
.await
.unwrap();
let waiting = tokio::time::timeout(Duration::from_millis(500), app.command("queue:work --stop-when-empty")).await;
assert!(waiting.is_err(), "the worker should keep blocking in BLPOP");
assert_eq!(state(&app, &queue).await, empty());
}
async fn sizes(app: &Application, queue: &str) -> QueueSizes {
app.scope(async || {
let manager = laravel::queue::manager();
manager.sizes("redis", queue).await
})
.await
.unwrap()
.expect("Redis counts its jobs")
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn sizes_count_due_jobs_and_lapsed_reservations_as_pending() {
let (app, queue) = application(None);
dispatch(&app, Note("first".into())).await;
app.scope(async || Note("later".into()).dispatch().delay(30.seconds()).await)
.await
.unwrap();
let mut redis = app.resolve::<RedisManager>().await.default_connection().unwrap();
let () = client::cmd("ZADD")
.arg(format!("queues:{{{queue}}}:reserved"))
.arg(NOW_MS + 60_000)
.arg("running")
.arg(NOW_MS - 1)
.arg("abandoned")
.query_async(&mut redis)
.await
.unwrap();
assert_eq!(
sizes(&app, &queue).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, &queue).await;
assert_eq!((due.pending, due.delayed, due.reserved), (3, 0, 1));
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn reserving_moves_at_most_a_hundred_due_jobs_per_script() {
let (app, queue) = application(None);
let notes: Vec<_> = (0..150).map(|note| format!("note {note:03}")).collect();
app.scope(async || {
for note in ¬es {
Note(note.clone()).dispatch().delay(30.seconds()).await?;
}
Ok::<_, laravel::Error>(())
})
.await
.unwrap();
app.travel(30.seconds());
work(&app, "--max-jobs=1").await.assert_successful();
assert_eq!(records(&app).await.len(), 1);
let after = state(&app, &queue).await;
assert_eq!((after.available.len(), after.delayed.len(), after.notify), (99, 50, 99));
work(&app, "").await.assert_successful();
assert_eq!(records(&app).await.len(), 150);
assert_eq!(state(&app, &queue).await, empty());
}
#[cfg(feature = "database-sqlite")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn batches_push_their_jobs_in_order_a_thousand_per_script() {
use laravel::config::database::ConnectionConfig as DatabaseConnection;
use laravel::db;
let directory = crate::support::TempDir::new("queue-redis-bulk");
let url = format!("sqlite://{}?mode=rwc", directory.join("batches.sqlite").display());
let (builder, queue) = configure(None);
let app = builder
.with_config(move |config, _| {
config.database.default = "primary".into();
config
.database
.connections
.insert("primary".into(), DatabaseConnection::new(url));
})
.create();
app.scope(async || {
let connection = db::default_connection()?;
for sql in crate::queue_batches::create_batch_tables(connection.driver()) {
connection.query(sql).statement().await?;
}
Ok::<_, laravel::Error>(())
})
.await
.unwrap();
let notes: Vec<_> = (0..1100).map(|note| format!("note {note:04}")).collect();
let id = app
.scope(async || laravel::queue::batch(notes.iter().cloned().map(Note).collect::<Vec<_>>()).await)
.await
.unwrap();
let state = state(&app, &queue).await;
assert_eq!(state.available, notes);
assert_eq!((state.payloads, state.notify), (1100, 1100));
work(&app, "").await.assert_successful();
let ran: Vec<_> = notes.iter().map(|note| format!("{note} as attempt 1")).collect();
assert_eq!(records(&app).await, ran);
let batch = app
.scope(async || laravel::queue::find_batch(id).await)
.await
.unwrap()
.unwrap();
assert!(batch.is_finished());
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_CLUSTER_URL pointing to a node of a disposable Redis Cluster"]
async fn each_queue_keeps_its_jobs_on_one_node_of_a_cluster() {
let node = std::env::var("LARAVEL_TEST_REDIS_CLUSTER_URL")
.expect("LARAVEL_TEST_REDIS_CLUSTER_URL points to a cluster node");
let queues: Vec<String> = (0..4).map(|_| key("cluster")).collect();
let app = Application::configure()
.replace_env(Env::default())
.with_config(move |config, _| {
config
.redis
.add_connection("default", ConnectionConfig::cluster([node]));
config.queue.default = "redis".into();
config.queue.failed = FailedJobs::Discard;
config.queue.add_connection("redis", RedisQueue::new());
})
.with_services(|services| {
services.instance(Records::default());
})
.create();
for queue in &queues {
app.scope(async || Note(queue.clone()).dispatch().on_queue(queue).await)
.await
.unwrap();
}
app.scope(async || ReleaseOnce.dispatch().on_queue(&queues[0]).await)
.await
.unwrap();
let result = work(&app, &format!("--queue={}", queues.join(","))).await;
result.assert_successful().assert_error_output_contains(" released ");
let notes: Vec<_> = records(&app)
.await
.into_iter()
.filter(|record| record.starts_with("laravel-test"))
.collect();
let expected: Vec<_> = queues.iter().map(|queue| format!("{queue} as attempt 1")).collect();
assert_eq!(notes, expected, "each queue's job ran, in the queues' order");
app.command(&format!("queue:clear --queue={}", queues[0]))
.await
.assert_successful()
.assert_error_output_contains("1 job cleared from `redis:");
}