use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use laravel::Application;
use laravel::config::Env;
use laravel::config::queue::ConnectionConfig;
use laravel::console::Signal;
use laravel::container::Inject;
use laravel::foundation::StartupError;
use laravel::queue::Queueable;
use laravel::queue::{Attempt, Driver, Reservation, ReservedJob, job};
use laravel::testing::{MakesConsoleRequests, TestCommandResult};
use laravel::time::ToSpan;
use crate::queue::Records;
#[derive(Queueable)]
struct Flaky {
id: u32,
failures: u32,
}
#[job(name = "drivers.flaky", tries = 2, backoff = 1.seconds())]
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 Later;
#[job(name = "drivers.later", tries = 2)]
impl Later {
async fn handle(self, records: Inject<Records>, attempt: &Attempt) {
records.push(format!(
"later ran as attempt {} on {}",
attempt.number(),
attempt.queue()
));
if attempt.number() == 1 {
attempt.release(1.seconds());
}
}
}
#[derive(Queueable)]
struct Large {
data: String,
}
#[job(name = "drivers.large", tries = 2)]
impl Large {
async fn handle(self, records: Inject<Records>, attempt: &Attempt) {
records.push(format!(
"large job of {} bytes ran as attempt {}",
self.data.len(),
attempt.number()
));
}
}
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 records(app: &Application) -> Vec<String> {
app.resolve::<Records>().await.all()
}
#[derive(Default)]
struct Memory {
jobs: Mutex<VecDeque<(String, String, u32)>>,
}
struct MemoryDriver(Arc<Memory>);
struct MemoryJob {
memory: Arc<Memory>,
queue: String,
payload: String,
attempts: u32,
}
impl Driver for MemoryDriver {
type Job = MemoryJob;
async fn push(&self, queue: &str, payload: String, _delay: Duration) -> laravel::Result<()> {
self.0.jobs.lock().unwrap().push_back((queue.into(), payload, 0));
Ok(())
}
async fn reserve(&self, queues: &[String]) -> laravel::Result<Option<MemoryJob>> {
let mut jobs = self.0.jobs.lock().unwrap();
for queue in queues {
if let Some(index) = jobs.iter().position(|(name, ..)| name == queue) {
let (queue, payload, attempts) = jobs.remove(index).unwrap();
return Ok(Some(MemoryJob {
memory: Arc::clone(&self.0),
queue,
payload,
attempts: attempts + 1,
}));
}
}
Ok(None)
}
async fn clear(&self, queue: &str) -> laravel::Result<u64> {
let mut jobs = self.0.jobs.lock().unwrap();
let before = jobs.len();
jobs.retain(|(name, ..)| name != queue);
Ok((before - jobs.len()) as u64)
}
}
impl ReservedJob for MemoryJob {
fn queue(&self) -> &str {
&self.queue
}
fn payload(&self) -> &str {
&self.payload
}
fn attempts(&self) -> u32 {
self.attempts
}
async fn renew(&self) -> laravel::Result<Reservation> {
Ok(Reservation::Held)
}
async fn delete(&self) -> laravel::Result<Reservation> {
Ok(Reservation::Held)
}
async fn release(&self, _delay: Duration) -> laravel::Result<Reservation> {
self.memory
.jobs
.lock()
.unwrap()
.push_back((self.queue.clone(), self.payload.clone(), self.attempts));
Ok(Reservation::Held)
}
}
#[derive(Debug)]
struct MemorySettings {
queue: &'static str,
}
#[tokio::test]
async fn registered_drivers_keep_and_hand_out_jobs_for_the_worker() {
let memory = Arc::new(Memory::default());
let shared = Arc::clone(&memory);
let app = Application::configure()
.replace_env(Env::default())
.with_config(|config, _| {
config.queue.default = "memory".into();
config.queue.failed = laravel::config::queue::FailedJobs::Discard;
config.queue.add_connection(
"memory",
ConnectionConfig::custom("Memory")
.queue("drivers")
.settings(MemorySettings { queue: "drivers" }),
);
})
.with_services(|services| {
services.instance(Records::default());
})
.with_services(move |app| {
app.queue().extend("memory", move |_app, definition| {
let memory = Arc::clone(&shared);
async move {
assert_eq!(definition.name(), "memory");
assert_eq!(definition.settings::<MemorySettings>()?.queue, "drivers");
Ok(MemoryDriver(memory))
}
});
})
.create();
app.scope(async || {
Later.dispatch().await?;
Flaky { id: 1, failures: 1 }.dispatch().await?;
Flaky { id: 2, failures: 5 }.dispatch().await
})
.await
.unwrap();
assert_eq!(memory.jobs.lock().unwrap().len(), 3);
assert!(memory.jobs.lock().unwrap().iter().all(|(queue, ..)| queue == "drivers"));
let result = work(&app, "").await;
result
.assert_successful()
.assert_error_output_contains("from `memory:drivers`");
assert_eq!(
records(&app).await,
[
"later ran as attempt 1 on drivers",
"flaky 1 ran as attempt 1",
"flaky 2 ran as attempt 1",
"later ran as attempt 2 on drivers",
"flaky 1 ran as attempt 2",
"flaky 2 ran as attempt 2",
"failed hook for flaky 2: flaky 2 broke",
],
"{}",
result.output()
);
assert!(memory.jobs.lock().unwrap().is_empty());
let sizes = app
.scope(async || {
let manager = laravel::queue::manager();
manager.sizes("memory", "drivers").await
})
.await
.unwrap();
assert_eq!(sizes, None, "a driver that doesn't count its jobs says so");
}
struct PollingDriver;
impl Driver for PollingDriver {
type Job = MemoryJob;
async fn push(&self, _queue: &str, _payload: String, _delay: Duration) -> laravel::Result<()> {
Ok(())
}
async fn reserve(&self, _queues: &[String]) -> laravel::Result<Option<MemoryJob>> {
std::future::pending().await
}
async fn clear(&self, _queue: &str) -> laravel::Result<u64> {
Ok(0)
}
}
#[tokio::test]
async fn stopping_the_worker_cancels_a_reserve_that_is_waiting_for_a_job() {
let app = Application::configure()
.replace_env(Env::default())
.with_config(|config, _| {
config.queue.default = "polling".into();
config.queue.failed = laravel::config::queue::FailedJobs::Discard;
config
.queue
.add_connection("polling", ConnectionConfig::custom("polling"));
})
.with_services(|app| {
app.queue()
.extend("polling", |_app, _definition| async { Ok(PollingDriver) });
})
.create();
let result = tokio::time::timeout(
Duration::from_secs(10),
app.command("queue:work").sends_signal(Signal::Interrupt),
)
.await
.expect("the worker should stop without waiting for the poll to end");
result.assert_successful();
}
#[tokio::test]
async fn connections_using_an_unregistered_driver_stop_the_application() {
let error = Application::configure()
.replace_env(Env::default())
.with_config(|config, _| {
config
.queue
.add_connection("beanstalkd", ConnectionConfig::custom("beanstalkd"));
})
.try_create()
.unwrap_err();
assert_eq!(
error,
StartupError::Queue(
"queue connection `beanstalkd` uses the driver `beanstalkd`, which isn't registered".into()
)
);
}
#[cfg(all(feature = "sqs", feature = "database-sqlite"))]
mod sqs {
use aws_sdk_sqs::Client;
use aws_sdk_sqs::config::{BehaviorVersion, Credentials, Region};
use aws_sdk_sqs::types::QueueAttributeName;
use aws_smithy_http_client::tls::{Provider, rustls_provider::CryptoMode};
use laravel::config::database::ConnectionConfig as DatabaseConnection;
use laravel::config::queue::{CloudQueue, SqsOverflow, SqsQueue};
use laravel::db;
use laravel::queue::QueueSizes;
use super::*;
use crate::queue::database::create_failed_table;
use crate::queue_batches::create_batch_tables;
fn endpoint() -> String {
std::env::var("LARAVEL_TEST_SQS_ENDPOINT").expect("LARAVEL_TEST_SQS_ENDPOINT names an SQS emulator")
}
fn connection() -> SqsQueue {
SqsQueue::new()
.region("us-east-1")
.endpoint(endpoint())
.credentials("test", "test")
}
async fn client() -> Client {
let config = aws_sdk_sqs::Config::builder()
.behavior_version(BehaviorVersion::latest())
.http_client(
aws_smithy_http_client::Builder::new()
.tls_provider(Provider::Rustls(CryptoMode::Ring))
.build_https(),
)
.region(Region::new("us-east-1"))
.endpoint_url(endpoint())
.credentials_provider(Credentials::new("test", "test", None, None, "test"))
.build();
Client::from_conf(config)
}
async fn create_queue(client: &Client, name: &str) -> (String, String) {
let name = format!("{name}-{}", laravel::str::random(8).to_lowercase());
let output = client.create_queue().queue_name(&name).send().await.unwrap();
(name, output.queue_url.unwrap())
}
async fn create_fifo_queue(client: &Client, name: &str) -> (String, String) {
let name = format!("{name}-{}.fifo", laravel::str::random(8).to_lowercase());
let output = client
.create_queue()
.queue_name(&name)
.attributes(QueueAttributeName::FifoQueue, "true")
.send()
.await
.unwrap();
(name, output.queue_url.unwrap())
}
async fn application(directory: &crate::support::TempDir, connection: ConnectionConfig) -> Application {
let url = format!("sqlite://{}?mode=rwc", directory.join("failed.sqlite").display());
let app = Application::configure()
.replace_env(Env::default())
.with_config(move |config, _| {
config.queue.default = "remote".into();
config.queue.add_connection("remote", connection);
config.database.default = "primary".into();
config
.database
.connections
.insert("primary".into(), DatabaseConnection::new(url));
})
.with_services(|services| {
services.instance(Records::default());
})
.create();
app.scope(async || {
let connection = db::default_connection()?;
let driver = connection.driver();
for sql in std::iter::once(create_failed_table(driver)).chain(create_batch_tables(driver)) {
connection.query(sql).statement().await?;
}
Ok::<_, laravel::Error>(())
})
.await
.unwrap();
app
}
async fn dispatch_batch(app: &Application, count: u32) {
app.scope(async || {
laravel::queue::batch((0..count).map(|id| Flaky { id, failures: 0 }).collect::<Vec<_>>()).await
})
.await
.unwrap();
}
async fn sizes(app: &Application, queue: &str) -> QueueSizes {
app.scope(async || {
let manager = laravel::queue::manager();
manager.sizes("remote", queue).await
})
.await
.unwrap()
.expect("SQS counts its jobs")
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_SQS_ENDPOINT pointing to an SQS emulator"]
async fn batches_send_their_jobs_to_sqs_ten_at_a_time() {
let client = client().await;
let (name, url) = create_queue(&client, "bulk").await;
let directory = crate::support::TempDir::new("queue-sqs-bulk");
let app = application(&directory, connection().queue(&name).into()).await;
dispatch_batch(&app, 23).await;
assert_eq!(
count(&client, &url, QueueAttributeName::ApproximateNumberOfMessages).await,
23
);
assert_eq!(
sizes(&app, &name).await,
QueueSizes {
pending: 23,
approximate: true,
..QueueSizes::default()
}
);
work(&app, "").await.assert_successful();
let mut ran = records(&app).await;
ran.sort();
let mut expected: Vec<_> = (0..23).map(|id| format!("flaky {id} ran as attempt 1")).collect();
expected.sort();
assert_eq!(ran, expected);
assert_eq!(sizes(&app, &name).await.total(), 0);
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_SQS_ENDPOINT pointing to an SQS emulator"]
async fn cloud_batches_send_their_jobs_to_sqs_and_report_each_one_queued() {
let client = client().await;
let (name, url) = create_queue(&client, "managed-bulk").await;
let directory = crate::support::TempDir::new("queue-cloud-bulk");
let events_socket = directory.join("events.sock");
let events = events(&events_socket);
let config = serde_json::json!({
"driver": "cloud",
"connection": { "driver": "sqs", "region": "us-east-1", "key": "test", "secret": "test", "queue": name },
"queues": [name],
});
let mut cloud: CloudQueue = config.to_string().parse().unwrap();
cloud.connection.endpoint = Some(endpoint());
cloud.events = format!("unix://{}", events_socket.display());
let app = application(&directory, cloud.into()).await;
dispatch_batch(&app, 12).await;
assert_eq!(
count(&client, &url, QueueAttributeName::ApproximateNumberOfMessages).await,
12
);
assert_eq!(sizes(&app, &name).await.pending, 12);
let events = collected(&events, 12).await;
assert_eq!(of_type(&events, "queued").len(), 12, "{events:#?}");
}
#[derive(db::FromRow)]
struct Failed {
queue: String,
error: String,
}
async fn failed(app: &Application) -> Vec<(String, String)> {
let rows: Vec<Failed> = app
.scope(async || {
db::default_connection()?
.query("SELECT queue, error FROM failed_jobs ORDER BY id")
.select_as()
.await
})
.await
.unwrap();
rows.into_iter().map(|row| (row.queue, row.error)).collect()
}
async fn count(client: &Client, url: &str, attribute: QueueAttributeName) -> u64 {
let output = client
.get_queue_attributes()
.queue_url(url)
.attribute_names(attribute.clone())
.send()
.await
.unwrap();
output.attributes.unwrap()[&attribute].parse().unwrap()
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_SQS_ENDPOINT pointing to an SQS emulator"]
async fn sqs_queues_count_every_run_and_release_jobs_in_place() {
let client = client().await;
let (name, url) = create_queue(&client, "jobs").await;
let directory = crate::support::TempDir::new("queue-sqs");
let app = application(&directory, connection().queue(&name).into()).await;
app.scope(async || {
Later.dispatch().await?;
Flaky { id: 1, failures: 1 }.dispatch().await?;
Flaky { id: 2, failures: 5 }.dispatch().await
})
.await
.unwrap();
let result = work(&app, "").await;
result.assert_successful();
assert_eq!(
result.error_output().matches(" released ").count(),
1,
"{}",
result.error_output()
);
assert_eq!(
result.error_output().matches(" retrying ").count(),
2,
"{}",
result.error_output()
);
assert_eq!(
(
count(&client, &url, QueueAttributeName::ApproximateNumberOfMessagesNotVisible).await,
count(&client, &url, QueueAttributeName::ApproximateNumberOfMessagesDelayed).await,
),
(3, 0),
"released messages are hidden in place, not sent again"
);
tokio::time::sleep(Duration::from_millis(1500)).await;
let result = work(&app, "").await;
result.assert_successful();
let mut ran = records(&app).await;
ran.sort();
assert_eq!(
ran,
[
"failed hook for flaky 2: flaky 2 broke",
"flaky 1 ran as attempt 1",
"flaky 1 ran as attempt 2",
"flaky 2 ran as attempt 1",
"flaky 2 ran as attempt 2",
format!("later ran as attempt 1 on {name}").as_str(),
format!("later ran as attempt 2 on {name}").as_str(),
]
);
assert_eq!(failed(&app).await, [(name.clone(), "flaky 2 broke".to_owned())]);
assert_eq!(
count(&client, &url, QueueAttributeName::ApproximateNumberOfMessages).await,
0
);
assert_eq!(
count(&client, &url, QueueAttributeName::ApproximateNumberOfMessagesNotVisible).await,
0,
"every message was deleted"
);
app.command("queue:retry all").await.assert_successful();
let result = work(&app, "").await;
result.assert_successful().assert_error_output_contains(" retrying ");
assert!(records(&app).await.ends_with(&["flaky 2 ran as attempt 1".to_owned()]));
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_SQS_ENDPOINT pointing to an SQS emulator"]
async fn a_lapsed_sqs_reservation_counts_as_an_attempt() {
let client = client().await;
let (name, url) = create_queue(&client, "lapsed").await;
let directory = crate::support::TempDir::new("queue-sqs-lapsed");
let app = application(&directory, connection().queue(&name).into()).await;
app.scope(async || Flaky { id: 3, failures: 0 }.dispatch().await)
.await
.unwrap();
let received = client
.receive_message()
.queue_url(&url)
.visibility_timeout(0)
.send()
.await
.unwrap();
assert_eq!(received.messages.unwrap().len(), 1);
let result = work(&app, "").await;
result.assert_successful();
assert_eq!(
crate::support::outcomes(result.error_output()),
["done"],
"{}",
result.error_output()
);
assert_eq!(records(&app).await, ["flaky 3 ran as attempt 2"]);
app.scope(async || Flaky { id: 4, failures: 0 }.dispatch().await)
.await
.unwrap();
for _ in 0..2 {
client
.receive_message()
.queue_url(&url)
.visibility_timeout(0)
.send()
.await
.unwrap();
}
work(&app, "")
.await
.assert_successful()
.assert_error_output_contains(" failed ");
assert_eq!(
records(&app).await,
[
"flaky 3 ran as attempt 2",
"failed hook for flaky 4: `drivers.flaky` has been attempted more than its 2 `tries` allow",
],
"flaky 4 didn't run"
);
let failures = failed(&app).await;
assert_eq!(failures.len(), 1);
assert!(failures[0].1.contains("attempted more than"), "{}", failures[0].1);
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_SQS_ENDPOINT pointing to an SQS emulator"]
async fn jobs_waiting_longer_than_sqs_allows_are_sent_on_until_they_are_due() {
let client = client().await;
let (name, url) = create_queue(&client, "delays").await;
let directory = crate::support::TempDir::new("queue-sqs-delays");
let app = application(&directory, connection().queue(&name).into()).await;
let now = laravel::time::Timestamp::now().as_second();
let job = |id: u32| {
serde_json::json!({
"version": 1,
"id": laravel::str::uuid7().to_string(),
"job": "drivers.flaky",
"data": { "id": id, "failures": 0 },
"dispatched_at": now,
})
.to_string()
};
for (id, available_at) in [(5, now - 1), (6, now + 3600)] {
let body = serde_json::json!({ "payload": job(id), "available_at": available_at }).to_string();
client
.send_message()
.queue_url(&url)
.message_body(body)
.send()
.await
.unwrap();
}
work(&app, "").await.assert_successful();
assert_eq!(records(&app).await, ["flaky 5 ran as attempt 1"]);
assert_eq!(
count(&client, &url, QueueAttributeName::ApproximateNumberOfMessages).await,
0
);
assert_eq!(
count(&client, &url, QueueAttributeName::ApproximateNumberOfMessagesDelayed).await,
1,
"the job due in an hour waits for another 15 minutes"
);
app.command("queue:clear").await.assert_successful();
assert_eq!(
count(&client, &url, QueueAttributeName::ApproximateNumberOfMessagesDelayed).await,
0
);
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_SQS_ENDPOINT pointing to an SQS emulator"]
async fn fifo_queues_keep_groups_in_order_drop_duplicates_and_refuse_delays() {
let client = client().await;
let (name, url) = create_fifo_queue(&client, "ordered").await;
let directory = crate::support::TempDir::new("queue-sqs-fifo");
let app = application(&directory, connection().queue(&name).into()).await;
app.scope(async || {
for id in [10, 11, 12] {
Flaky { id, failures: 0 }.dispatch().on_group("user-1").await?;
}
Flaky { id: 13, failures: 0 }
.dispatch()
.deduplication_id("order-13")
.await?;
Flaky { id: 13, failures: 0 }
.dispatch()
.deduplication_id("order-13")
.await?;
Flaky { id: 15, failures: 1 }.dispatch().on_group("user-2").await?;
Flaky { id: 16, failures: 0 }.dispatch().on_group("user-2").await
})
.await
.unwrap();
let error = app
.scope(async || Flaky { id: 14, failures: 0 }.dispatch().delay(2.seconds()).await)
.await
.unwrap_err();
assert!(error.to_string().contains("can't delay jobs"), "{error}");
let result = work(&app, "").await;
result.assert_successful();
let ran = records(&app).await;
let user_1: Vec<_> = ran
.iter()
.filter(|run| {
["flaky 10 ", "flaky 11 ", "flaky 12 "]
.iter()
.any(|id| run.starts_with(id))
})
.collect();
assert_eq!(
user_1,
[
"flaky 10 ran as attempt 1",
"flaky 11 ran as attempt 1",
"flaky 12 ran as attempt 1",
],
"a group's jobs run in order"
);
assert_eq!(
ran.iter().filter(|run| run.starts_with("flaky 13")).count(),
1,
"a job with the same deduplication ID is dropped"
);
assert!(ran.contains(&"flaky 15 ran as attempt 1".to_owned()), "{ran:?}");
assert!(
!ran.iter().any(|run| run.starts_with("flaky 16")),
"the job behind a retried one waits for it: {ran:?}"
);
tokio::time::sleep(Duration::from_millis(1500)).await;
work(&app, "").await.assert_successful();
let ran = records(&app).await;
assert!(!ran.iter().any(|run| run.starts_with("flaky 14")), "{ran:?}");
let user_2: Vec<_> = ran
.iter()
.filter(|run| run.starts_with("flaky 15 ") || run.starts_with("flaky 16 "))
.collect();
assert_eq!(
user_2,
[
"flaky 15 ran as attempt 1",
"flaky 15 ran as attempt 2",
"flaky 16 ran as attempt 1",
],
"a retried job keeps its place in its group"
);
assert!(failed(&app).await.is_empty());
assert_eq!(
count(&client, &url, QueueAttributeName::ApproximateNumberOfMessagesNotVisible).await,
0
);
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_SQS_ENDPOINT pointing to an SQS emulator"]
async fn payloads_too_large_for_sqs_overflow_into_the_cache() {
let client = client().await;
let (name, url) = create_queue(&client, "large").await;
let directory = crate::support::TempDir::new("queue-sqs-large");
let app = application(
&directory,
connection().queue(&name).overflow(SqsOverflow::new()).into(),
)
.await;
let data = "x".repeat(1024 * 1024);
app.scope(async || Large { data: data.clone() }.dispatch().on_group("exports").await)
.await
.unwrap();
let received = client
.receive_message()
.queue_url(&url)
.visibility_timeout(0)
.send()
.await
.unwrap();
let body = received.messages.unwrap().remove(0).body.unwrap();
assert!(body.len() < 200, "{body}");
let envelope: serde_json::Value = serde_json::from_str(&body).unwrap();
assert_eq!(envelope["cached"], true);
let key = envelope["payload"].as_str().unwrap().to_owned();
assert!(key.starts_with("laravel:sqs-payloads:"), "{key}");
let cached = app
.scope(async || laravel::cache::get::<String>(&key).await)
.await
.unwrap();
assert!(cached.unwrap().contains(&data));
let result = work(&app, "").await;
result.assert_successful();
assert_eq!(
crate::support::outcomes(result.error_output()),
["done"],
"{}",
result.error_output()
);
assert_eq!(records(&app).await, ["large job of 1048576 bytes ran as attempt 2"]);
let cached = app
.scope(async || laravel::cache::get::<String>(&key).await)
.await
.unwrap();
assert!(
cached.is_some_and(|payload| payload.contains(&data)),
"a finished job's payload stays until it expires, for a worker that received the job after a lapsed lease"
);
let directory = crate::support::TempDir::new("queue-sqs-too-large");
let app = application(&directory, connection().queue(&name).into()).await;
let error = app.scope(async || Large { data }.dispatch().await).await.unwrap_err();
assert!(error.to_string().contains("more than an SQS message holds"), "{error}");
}
type Results = Arc<Mutex<Vec<serde_json::Value>>>;
async fn agent(socket: std::path::PathBuf, url: String, broken: bool) -> Results {
use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
let results = Arc::new(Mutex::new(Vec::new()));
let state = (client().await, url, Arc::clone(&results));
let router = axum::Router::new()
.route(
"/next",
get(|State((client, url, _)): State<(Client, String, _)>| async move {
let output = client
.receive_message()
.queue_url(&url)
.message_system_attribute_names(
aws_sdk_sqs::types::MessageSystemAttributeName::ApproximateReceiveCount,
)
.send()
.await
.unwrap();
let Some(message) = output.messages.and_then(|messages| messages.into_iter().next()) else {
return StatusCode::NO_CONTENT.into_response();
};
let count = message
.attributes
.unwrap_or_default()
.into_values()
.next()
.unwrap_or_else(|| "1".into());
Json(serde_json::json!({
"messageId": message.message_id,
"receiptHandle": message.receipt_handle,
"body": message.body,
"queueUrl": url,
"attributes": { "ApproximateReceiveCount": count },
}))
.into_response()
}),
)
.route(
"/result",
post(
move |State((client, url, results)): State<(Client, String, Results)>,
Json(result): Json<serde_json::Value>| async move {
if broken {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
}
let receipt = result["receiptHandle"].as_str().unwrap();
if result["status"] == "released" {
let delay = result["delay"].as_i64().unwrap();
client
.change_message_visibility()
.queue_url(&url)
.receipt_handle(receipt)
.visibility_timeout(i32::try_from(delay).unwrap())
.send()
.await
.unwrap();
} else {
client
.delete_message()
.queue_url(&url)
.receipt_handle(receipt)
.send()
.await
.unwrap();
}
results.lock().unwrap().push(result);
Response::new(axum::body::Body::empty()).into_response()
},
),
)
.with_state(state);
let listener = tokio::net::UnixListener::bind(socket).unwrap();
tokio::spawn(async move { axum::serve(listener, router).await });
results
}
fn events(socket: &std::path::Path) -> Results {
use tokio::io::AsyncBufReadExt;
let events = Results::default();
let listener = tokio::net::UnixListener::bind(socket).unwrap();
let collected = Arc::clone(&events);
tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
let collected = Arc::clone(&collected);
tokio::spawn(async move {
let mut lines = tokio::io::BufReader::new(stream).lines();
while let Ok(Some(line)) = lines.next_line().await {
collected.lock().unwrap().push(serde_json::from_str(&line).unwrap());
}
});
}
});
events
}
async fn collected(events: &Results, expected: usize) -> Vec<serde_json::Value> {
for _ in 0..50 {
if events.lock().unwrap().len() >= expected {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
events.lock().unwrap().clone()
}
fn of_type<'a>(events: &'a [serde_json::Value], kind: &str) -> Vec<&'a serde_json::Value> {
events.iter().filter(|event| event["type"] == kind).collect()
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_SQS_ENDPOINT pointing to an SQS emulator"]
async fn cloud_workers_take_jobs_from_the_agent_and_report_them_to_laravel_cloud() {
let client = client().await;
let (name, url) = create_queue(&client, "managed").await;
let directory = crate::support::TempDir::new("queue-cloud");
let socket = directory.join("agent.sock");
let results = agent(socket.clone(), url.clone(), false).await;
let events_socket = directory.join("events.sock");
let events = events(&events_socket);
let config = serde_json::json!({
"driver": "cloud",
"connection": { "driver": "sqs", "region": "us-east-1", "key": "test", "secret": "test", "queue": name },
"queues": [name],
"agent": { "enabled": true, "socket": socket },
});
let mut cloud: CloudQueue = config.to_string().parse().unwrap();
cloud.connection.endpoint = Some(endpoint());
cloud.events = format!("unix://{}", events_socket.display());
let app = application(&directory, cloud.into()).await;
app.scope(async || {
Later.dispatch().await?;
Flaky { id: 7, failures: 5 }.dispatch().await
})
.await
.unwrap();
let result = work(&app, "").await;
result.assert_successful();
assert_eq!(
result.error_output().matches(" released ").count(),
1,
"{}",
result.error_output()
);
assert_eq!(
result.error_output().matches(" retrying ").count(),
1,
"{}",
result.error_output()
);
tokio::time::sleep(Duration::from_millis(1500)).await;
let result = work(&app, "").await;
result.assert_successful().assert_error_output_contains(" failed ");
assert!(
crate::support::outcomes(result.error_output()).contains(&"done"),
"{}",
result.error_output()
);
let mut ran = records(&app).await;
ran.sort();
assert_eq!(
ran,
[
"failed hook for flaky 7: flaky 7 broke".to_owned(),
"flaky 7 ran as attempt 1".to_owned(),
"flaky 7 ran as attempt 2".to_owned(),
format!("later ran as attempt 1 on {name}"),
format!("later ran as attempt 2 on {name}"),
]
);
let results = results.lock().unwrap().clone();
let statuses: Vec<_> = results
.iter()
.map(|result| (result["status"].as_str(), result["delay"].as_i64()))
.collect();
assert_eq!(
statuses,
[
(Some("released"), Some(1)),
(Some("released"), Some(1)),
(Some("processed"), None),
(Some("processed"), None),
],
"the agent hides released jobs in place: {results:?}"
);
assert_eq!(
count(&client, &url, QueueAttributeName::ApproximateNumberOfMessages).await,
0
);
let events = collected(&events, 11).await;
assert!(
events.iter().all(|event| event["queue"] == name.as_str()),
"{events:#?}"
);
assert_eq!(of_type(&events, "queued").len(), 2, "{events:#?}");
assert_eq!(of_type(&events, "started").len(), 4, "{events:#?}");
assert_eq!(of_type(&events, "released").len(), 2, "{events:#?}");
assert_eq!(of_type(&events, "processed").len(), 1, "{events:#?}");
assert_eq!(of_type(&events, "failed").len(), 1, "{events:#?}");
assert!(of_type(&events, "failed")[0]["duration_ms"].is_u64());
let failed_jobs: Vec<_> = events
.iter()
.filter(|event| event["_cloud_event"] == "failed_job")
.collect();
assert_eq!(failed_jobs.len(), 1, "{events:#?}");
let failed_job = failed_jobs[0];
assert_eq!(failed_job["job_name"], "drivers.flaky");
assert_eq!(failed_job["attempts"], 2);
assert!(
failed_job["payload"].as_str().unwrap().contains(r#""id":7"#),
"{failed_job}"
);
let preview = failed_job["exception_preview"].as_str().unwrap();
assert!(
preview.contains(": flaky 7 broke in tests/queue_drivers.rs:"),
"{preview}"
);
assert!(failed_job["started_at"].as_str().unwrap().len() == 26, "{failed_job}");
assert!(failed_job.get("exception_id").is_none(), "{failed_job}");
assert!(
failed(&app).await.is_empty(),
"Laravel Cloud keeps the failed job, not the table"
);
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_SQS_ENDPOINT pointing to an SQS emulator"]
async fn cloud_workers_stop_once_the_agent_cant_take_a_result() {
let client = client().await;
let (name, url) = create_queue(&client, "managed-broken").await;
let directory = crate::support::TempDir::new("queue-cloud-broken");
let socket = directory.join("agent.sock");
agent(socket.clone(), url, true).await;
let config = serde_json::json!({
"driver": "cloud",
"connection": { "driver": "sqs", "region": "us-east-1", "key": "test", "secret": "test", "queue": name },
"queues": [name],
"agent": { "enabled": true, "socket": socket },
});
let mut cloud: CloudQueue = config.to_string().parse().unwrap();
cloud.connection.endpoint = Some(endpoint());
let app = application(&directory, cloud.into()).await;
app.scope(async || {
Flaky { id: 1, failures: 0 }.dispatch().await?;
Flaky { id: 2, failures: 0 }.dispatch().await
})
.await
.unwrap();
work(&app, "")
.await
.assert_exit_code(1)
.assert_error_output_contains("returned HTTP 500 from `POST /result`");
assert_eq!(
records(&app).await.len(),
1,
"the worker took no job after the agent failed"
);
}
}