use std::sync::Mutex;
use laravel::Application;
use laravel::config::Env;
use laravel::container::Inject;
use laravel::foundation::StartupError;
use laravel::queue::Queueable;
use laravel::queue::{self, Attempt, job};
use laravel::testing::{MakesHttpRequests, RunsJobs};
use laravel::time::ToSpan;
#[derive(Default)]
pub(crate) struct Records(Mutex<Vec<String>>);
impl Records {
pub(crate) fn push(&self, value: impl Into<String>) {
self.0.lock().unwrap().push(value.into());
}
pub(crate) fn all(&self) -> Vec<String> {
self.0.lock().unwrap().clone()
}
pub(crate) fn clear(&self) {
self.0.lock().unwrap().clear();
}
}
#[derive(Debug, thiserror::Error)]
#[error("the podcast is corrupt")]
struct Corrupt;
#[derive(Queueable)]
struct ProcessPodcast {
podcast_id: i64,
outcome: Option<String>,
}
impl ProcessPodcast {
fn new(podcast_id: i64) -> Self {
Self {
podcast_id,
outcome: None,
}
}
fn then(mut self, outcome: &str) -> Self {
self.outcome = Some(outcome.to_owned());
self
}
}
#[job(queue = "podcasts", tries = 3, backoff = [10.seconds(), 1.minutes()], timeout = 2.minutes(), retry_for = 1.hours())]
impl ProcessPodcast {
async fn handle(self, records: Inject<Records>, attempt: &Attempt) -> laravel::Result<()> {
let tenant = laravel::context::get::<String>("tenant").unwrap_or_default();
records.push(format!(
"processed {} for {tenant:?} on {}/{} as attempt {}",
self.podcast_id,
attempt.connection(),
attempt.queue(),
attempt.number(),
));
match self.outcome.as_deref() {
Some("error") => Err(Corrupt.into()),
Some("fail") => {
attempt.fail(Corrupt);
Ok(())
}
Some("release") => {
attempt.release(30.seconds());
Ok(())
}
Some("delete") => {
attempt.delete();
Ok(())
}
Some("panic") => panic!("the encoder crashed"),
_ => Ok(()),
}
}
async fn failed(self, error: &laravel::Error, records: Inject<Records>) {
records.push(format!("failed {}: {error}", self.podcast_id));
}
}
#[derive(Queueable)]
struct Ping;
#[job]
impl Ping {
async fn handle(self, records: Inject<Records>) {
records.push("ping");
}
}
#[derive(Queueable)]
struct Renamed;
#[job(name = "podcasts.renamed")]
impl Renamed {
async fn handle(self) {}
}
fn configure(connection: &'static str) -> laravel::foundation::ApplicationBuilder {
Application::configure()
.replace_env(Env::default())
.with_config(move |config, _| {
config.queue.default = connection.into();
})
.with_services(|services| {
services.instance(Records::default());
})
}
async fn records(app: &Application) -> Vec<String> {
app.resolve::<Records>().await.all()
}
#[tokio::test]
async fn the_sync_connection_runs_jobs_in_a_fresh_context_with_the_dispatching_contexts_values() {
let app = configure("sync").create();
app.scope(async || {
laravel::context::add("tenant", "acme");
ProcessPodcast::new(42).dispatch().await.unwrap();
ProcessPodcast::new(43).dispatch().on_queue("urgent").await.unwrap();
})
.await;
assert_eq!(
records(&app).await,
[
"processed 42 for \"acme\" on sync/podcasts as attempt 1",
"processed 43 for \"acme\" on sync/urgent as attempt 1",
]
);
}
#[tokio::test]
async fn sync_failures_run_the_failed_hook_once_and_return_the_error() {
let app = configure("sync").create();
let errors = app
.scope(async || {
let returned = ProcessPodcast::new(1).then("error").dispatch().await.unwrap_err();
let failed = ProcessPodcast::new(2).then("fail").dispatch().await.unwrap_err();
let panicked = ProcessPodcast::new(3).then("panic").dispatch().await.unwrap_err();
ProcessPodcast::new(4).then("release").dispatch().await.unwrap();
ProcessPodcast::new(5).then("delete").dispatch().await.unwrap();
[returned, failed, panicked]
})
.await;
assert!(errors[0].is::<Corrupt>() && errors[1].is::<Corrupt>(), "{errors:?}");
assert!(errors[2].to_string().contains("the encoder crashed"), "{}", errors[2]);
let records = records(&app).await;
let failures: Vec<_> = records.iter().filter(|record| record.starts_with("failed")).collect();
assert_eq!(
failures[..2],
["failed 1: the podcast is corrupt", "failed 2: the podcast is corrupt"]
);
assert!(
failures[2].starts_with("failed 3: ") && failures[2].ends_with("the encoder crashed"),
"{failures:?}"
);
assert_eq!(records.len(), 8, "each job ran once: {records:?}");
}
#[tokio::test]
async fn dispatch_sync_runs_jobs_now_whatever_the_default_connection() {
let app = configure("discard").create();
app.scope(async || {
Ping.dispatch().await.unwrap();
assert!(records(&app).await.is_empty(), "the discard connection discards jobs");
Ping.dispatch_sync().await.unwrap();
queue::dispatch_sync(Ping).await.unwrap();
let error = ProcessPodcast::new(7).then("error").dispatch_sync().await.unwrap_err();
assert!(error.is::<Corrupt>());
})
.await;
assert_eq!(
records(&app).await,
[
"ping",
"ping",
"processed 7 for \"\" on sync/podcasts as attempt 1",
"failed 7: the podcast is corrupt",
]
);
}
#[tokio::test]
async fn dispatching_to_an_undefined_connection_fails() {
let app = configure("sync").create();
let error = app
.scope(async || Ping.dispatch().on_connection("beanstalkd").await)
.await
.unwrap_err();
assert_eq!(error.to_string(), "queue connection `beanstalkd` isn't defined");
assert_eq!(
app.scope(async || { queue::manager().connection_names() }).await,
["database", "discard", "redis", "sqs", "sync"],
);
}
#[tokio::test]
async fn the_application_refuses_to_start_with_an_undefined_default_connection() {
let undefined = Application::configure()
.replace_env(Env::from_iter([("QUEUE_CONNECTION", "beanstalkd")]))
.try_create()
.unwrap_err();
assert_eq!(
undefined,
StartupError::Queue("the default queue connection `beanstalkd` isn't defined".into())
);
}
#[tokio::test]
async fn fakes_record_jobs_with_where_they_were_sent() {
let app = configure("sync").create();
app.scope(async || {
let queue = queue::fake();
let id = ProcessPodcast::new(42)
.dispatch()
.on_connection("database")
.delay(5.minutes())
.await
.unwrap();
ProcessPodcast::new(43).dispatch().on_queue("urgent").await.unwrap();
Ping.dispatch().await.unwrap();
queue
.assert_pushed::<ProcessPodcast>()
.assert_pushed_times::<ProcessPodcast>(2)
.assert_pushed_where::<ProcessPodcast>(|job| job.podcast_id == 42 && job.queue() == "podcasts")
.assert_pushed_where::<ProcessPodcast>(|job| job.queue() == "urgent" && job.connection() == "sync")
.assert_not_pushed_where::<ProcessPodcast>(|job| job.podcast_id == 44)
.assert_pushed_times::<Ping>(1)
.assert_not_pushed::<Renamed>();
let pushed = queue.pushed::<ProcessPodcast>();
assert_eq!(pushed[0].id(), id);
assert_eq!(pushed[0].connection(), "database");
assert_eq!(pushed[0].delay(), 5.minutes());
assert_eq!(pushed[0].delay(), std::time::Duration::from_secs(300));
assert_ne!(pushed[0].delay(), 4.minutes());
assert_ne!(pushed[0].delay(), 300.milliseconds());
assert_eq!(pushed[1].delay(), std::time::Duration::ZERO);
assert_eq!(queue.pushed::<Ping>()[0].queue(), "default");
})
.await;
assert!(records(&app).await.is_empty(), "faked jobs don't run");
}
#[tokio::test]
async fn tests_run_jobs_on_the_default_connection_even_when_they_name_their_own() {
let app = Application::configure()
.for_testing(env!("CARGO_MANIFEST_DIR"))
.with_services(|services| {
services.instance(Records::default());
})
.create();
app.scope(async || {
ProcessPodcast::new(7).dispatch().on_connection("redis").await.unwrap();
queue::bulk([ProcessPodcast::new(8)])
.on_connection("database")
.await
.unwrap();
queue::chain(ProcessPodcast::new(9)).on_connection("sqs").await.unwrap();
let undefined = Ping.dispatch().on_connection("beanstalkd").await.unwrap_err();
assert_eq!(undefined.to_string(), "queue connection `beanstalkd` isn't defined");
let queue = queue::fake();
ProcessPodcast::new(10).dispatch().on_connection("redis").await.unwrap();
assert_eq!(
queue.pushed::<ProcessPodcast>()[0].connection(),
"redis",
"fakes record the connection the job names"
);
})
.await;
assert_eq!(
records(&app).await,
[
"processed 7 for \"\" on sync/podcasts as attempt 1",
"processed 8 for \"\" on sync/podcasts as attempt 1",
"processed 9 for \"\" on sync/podcasts as attempt 1",
]
);
}
#[tokio::test]
async fn bulk_dispatches_push_each_job_where_it_goes_in_order() {
let app = configure("sync").create();
app.scope(async || {
let queue = queue::fake();
let ids = queue::bulk((ProcessPodcast::new(1), Ping, ProcessPodcast::new(2)))
.on_connection("database")
.await
.unwrap();
queue::bulk([Ping]).on_queue("urgent").await.unwrap();
assert!(queue::bulk(Vec::<Ping>::new()).await.unwrap().is_empty());
let iterator_ids = queue::bulk((3..=6).filter(|id| id % 2 == 1).map(ProcessPodcast::new))
.on_queue("imports")
.await
.unwrap();
let podcasts = queue.pushed::<ProcessPodcast>();
assert_eq!([podcasts[0].id(), podcasts[1].id()], [ids[0], ids[2]]);
assert_eq!(
podcasts.iter().map(|job| job.podcast_id).collect::<Vec<_>>(),
[1, 2, 3, 5]
);
assert_eq!([podcasts[2].id(), podcasts[3].id()], iterator_ids.as_slice());
assert!(podcasts[2..].iter().all(|job| job.queue() == "imports"));
assert!(
podcasts[..2]
.iter()
.all(|job| job.connection() == "database" && job.queue() == "podcasts")
);
let pings: Vec<_> = queue
.pushed::<Ping>()
.iter()
.map(|job| job.queue().to_owned())
.collect();
assert_eq!(pings, ["default", "urgent"]);
assert_eq!(queue.pushed::<Ping>()[0].id(), ids[1]);
let batch = queue::bulk(queue::batch([Ping])).await.unwrap_err();
assert!(batch.to_string().contains("not batches"), "{batch}");
})
.await;
assert!(records(&app).await.is_empty(), "faked jobs don't run");
}
#[tokio::test]
async fn bulk_dispatches_on_sync_run_in_order_and_stop_at_the_first_error() {
let app = configure("sync").create();
let error = app
.scope(async || {
queue::bulk([
ProcessPodcast::new(1),
ProcessPodcast::new(2).then("error"),
ProcessPodcast::new(3),
])
.await
})
.await
.unwrap_err();
assert!(error.is::<Corrupt>(), "{error}");
assert_eq!(
records(&app).await,
[
"processed 1 for \"\" on sync/podcasts as attempt 1",
"processed 2 for \"\" on sync/podcasts as attempt 1",
"failed 2: the podcast is corrupt",
]
);
}
#[tokio::test]
async fn selective_fakes_let_other_jobs_run_and_dropping_a_fake_restores_dispatch() {
let app = configure("sync").create();
app.scope(async || {
{
let queue = queue::fake().only::<Ping>();
Ping.dispatch().await.unwrap();
ProcessPodcast::new(1).dispatch().await.unwrap();
queue.assert_pushed::<Ping>().assert_not_pushed::<ProcessPodcast>();
}
{
let queue = queue::fake().except::<Ping>();
Ping.dispatch().await.unwrap();
ProcessPodcast::new(2).dispatch_sync().await.unwrap();
queue.assert_not_pushed::<Ping>().assert_pushed::<ProcessPodcast>();
assert_eq!(queue.pushed::<ProcessPodcast>()[0].connection(), "sync");
}
Ping.dispatch().await.unwrap();
})
.await;
assert_eq!(
records(&app).await,
["processed 1 for \"\" on sync/podcasts as attempt 1", "ping", "ping"]
);
}
#[tokio::test]
#[should_panic(
expected = "expected job `integration::queue::Ping` to be pushed at least once; recorded jobs: [\"podcasts.renamed\"]"
)]
async fn failed_fake_assertions_name_the_recorded_jobs() {
let app = configure("sync").create();
app.scope(async || {
let queue = queue::fake();
Renamed.dispatch().await.unwrap();
queue.assert_pushed::<Ping>();
})
.await;
}
#[tokio::test]
async fn handlers_dispatch_jobs() {
async fn upload() -> laravel::Result<&'static str> {
ProcessPodcast::new(42).dispatch().await?;
Ok("queued")
}
let app = configure("sync")
.with_routing(|routing, _| {
routing.routes(|routes| {
routes.post("/podcasts", upload);
});
})
.create();
let queue = app.scope(async || queue::fake()).await;
app.post("/podcasts").await.assert_ok().assert_see("queued");
queue.assert_pushed_where::<ProcessPodcast>(|job| job.podcast_id == 42);
}
#[tokio::test]
async fn test_jobs_report_how_an_attempt_ended() {
let app = configure("discard").create();
app.job(ProcessPodcast::new(1)).await.assert_succeeded();
app.job(ProcessPodcast::new(2).then("release"))
.await
.assert_released()
.assert_released_after(30.seconds());
app.job(ProcessPodcast::new(3).then("delete")).await.assert_deleted();
app.job(ProcessPodcast::new(4).then("fail"))
.attempt(2)
.await
.assert_failed()
.assert_failed_with::<Corrupt>();
let panicked = app.job(ProcessPodcast::new(5).then("panic")).await;
assert!(
panicked
.assert_failed()
.error()
.unwrap()
.to_string()
.contains("encoder crashed")
);
assert_eq!(
records(&app).await,
[
"processed 1 for \"\" on discard/podcasts as attempt 1",
"processed 2 for \"\" on discard/podcasts as attempt 1",
"processed 3 for \"\" on discard/podcasts as attempt 1",
"processed 4 for \"\" on discard/podcasts as attempt 2",
"processed 5 for \"\" on discard/podcasts as attempt 1",
],
"test jobs don't run failed hooks"
);
}
#[tokio::test]
#[should_panic(
expected = "expected job `integration::queue::ProcessPodcast` to be released for 60s, but it was released for 30s"
)]
async fn failed_test_job_assertions_say_how_the_job_ended() {
let app = configure("discard").create();
app.job(ProcessPodcast::new(1).then("release"))
.await
.assert_released_after(1.minutes());
}
#[tokio::test]
async fn missing_services_fail_the_job_naming_it() {
#[derive(Queueable)]
struct NeedsMailer;
struct Mailer;
#[job]
impl NeedsMailer {
async fn handle(self, _mailer: Inject<Mailer>) {}
}
let app = configure("sync").create();
let result = app.job(NeedsMailer).await;
let error = result.assert_failed().error().unwrap().to_string();
assert!(
error.contains("injecting `integration::queue::NeedsMailer` failed"),
"{error}"
);
}
#[cfg(feature = "database")]
pub(crate) mod database {
use laravel::config::database::ConnectionConfig;
use laravel::db::{self, AnyConnection, Driver};
use serde_json::Value;
use super::*;
pub(crate) fn create_table(driver: Driver) -> &'static str {
match driver {
Driver::Postgres => {
"CREATE TABLE jobs (
id BIGSERIAL PRIMARY KEY,
queue VARCHAR(255) NOT NULL,
payload TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
reserved_at TIMESTAMP(6),
available_at TIMESTAMP(6) NOT NULL,
created_at TIMESTAMP(6) NOT NULL
)"
}
Driver::MySql | Driver::MariaDb => {
"CREATE TABLE jobs (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
queue VARCHAR(255) NOT NULL,
payload LONGTEXT NOT NULL,
attempts INT NOT NULL DEFAULT 0,
reserved_at DATETIME(6) NULL,
available_at DATETIME(6) NOT NULL,
created_at DATETIME(6) NOT NULL,
INDEX jobs_queue_index (queue)
)"
}
_ => {
"CREATE TABLE jobs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
queue VARCHAR(255) NOT NULL,
payload TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
reserved_at TIMESTAMP(6),
available_at TIMESTAMP(6) NOT NULL,
created_at TIMESTAMP(6) NOT NULL
)"
}
}
}
pub(crate) async fn application(url: impl Into<String>) -> Application {
let url = url.into();
let app = configure("database")
.with_config(move |config, _| {
let mut connection = ConnectionConfig::new(url);
connection.max_connections = 1;
connection.idle_timeout = None;
connection.max_lifetime = None;
config.database.default = "primary".into();
config.database.connections.insert("primary".into(), connection);
})
.create();
app.scope(async || {
let connection = db::default_connection()?;
connection.query("DROP TABLE IF EXISTS jobs").statement().await?;
connection.query(create_table(connection.driver())).statement().await
})
.await
.unwrap();
app
}
#[derive(Debug, db::FromRow)]
struct Row {
queue: String,
payload: String,
attempts: i64,
reserved_at: Option<laravel::time::Timestamp>,
available_at: laravel::time::Timestamp,
created_at: laravel::time::Timestamp,
}
async fn rows(connection: &AnyConnection) -> Vec<Row> {
connection
.query("SELECT queue, payload, attempts, reserved_at, available_at, created_at FROM jobs ORDER BY id")
.select_as()
.await
.unwrap()
}
pub(crate) fn create_failed_table(driver: Driver) -> &'static str {
match driver {
Driver::Postgres => {
"CREATE TABLE failed_jobs (
id BIGSERIAL PRIMARY KEY,
job_id VARCHAR(36) NOT NULL UNIQUE,
connection VARCHAR(255) NOT NULL,
queue VARCHAR(255) NOT NULL,
payload TEXT NOT NULL,
error TEXT NOT NULL,
failed_at TIMESTAMP(6) NOT NULL
)"
}
Driver::MySql | Driver::MariaDb => {
"CREATE TABLE failed_jobs (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
job_id VARCHAR(36) NOT NULL UNIQUE,
connection VARCHAR(255) NOT NULL,
queue VARCHAR(255) NOT NULL,
payload LONGTEXT NOT NULL,
error LONGTEXT NOT NULL,
failed_at DATETIME(6) NOT NULL
)"
}
_ => {
"CREATE TABLE failed_jobs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
job_id VARCHAR(36) NOT NULL UNIQUE,
connection VARCHAR(255) NOT NULL,
queue VARCHAR(255) NOT NULL,
payload TEXT NOT NULL,
error TEXT NOT NULL,
failed_at TIMESTAMP(6) NOT NULL
)"
}
}
}
#[tokio::test]
async fn the_application_refuses_to_start_with_an_invalid_table() {
let invalid = Application::configure()
.replace_env(Env::default())
.with_config(|config, _| {
config.queue.add_connection(
"jobs",
laravel::config::queue::DatabaseQueue::new().table("jobs; DROP TABLE users"),
);
})
.try_create()
.unwrap_err();
assert!(
matches!(&invalid, StartupError::Queue(message) if message.contains("queue connection `jobs` uses the table")),
"{invalid:?}"
);
}
pub(crate) async fn push_contract(app: &Application) {
let now = laravel::time::Timestamp::from_second(1_800_000_000).unwrap();
app.travel_to(now);
let now = now.as_second();
let (first, rows) = app
.scope(async || {
laravel::context::add("tenant", "acme");
laravel::context::add_hidden("token", "secret");
let first = ProcessPodcast::new(42).dispatch().await.unwrap();
Ping.dispatch().delay(90.seconds()).await.unwrap();
Ping.dispatch()
.on_queue("later")
.delay(laravel::time::Timestamp::from_second(now + 3600).unwrap())
.await
.unwrap();
(first, rows(&db::default_connection().unwrap()).await)
})
.await;
assert!(records(app).await.is_empty(), "nothing runs until a worker takes it");
let queues: Vec<_> = rows
.iter()
.map(|row| (row.queue.as_str(), row.available_at.as_second() - now))
.collect();
assert_eq!(queues, [("podcasts", 0), ("default", 90), ("later", 3600)]);
assert!(
rows.iter()
.all(|row| row.attempts == 0 && row.reserved_at.is_none() && row.created_at.as_second() == now)
);
let payload: Value = serde_json::from_str(&rows[0].payload).unwrap();
assert_eq!(
payload,
serde_json::json!({
"version": 1,
"id": first.to_string(),
"job": "integration::queue::ProcessPodcast",
"data": { "podcast_id": 42, "outcome": null },
"context": { "tenant": "acme" },
"hidden_context": { "token": "secret" },
"dispatched_at": now,
})
);
}
pub(crate) async fn transaction_contract(app: &Application) {
let (during, after) = app
.scope(async || {
db::default_connection()?.query("DELETE FROM jobs").statement().await?;
let connection = db::default_connection().unwrap();
let during = connection
.transaction(async |tx| {
ProcessPodcast::new(1).dispatch().await?;
tx.query("SELECT COUNT(*) FROM jobs").scalar::<i64>().await
})
.await
.unwrap();
let rolled_back = connection
.transaction(async |_| {
ProcessPodcast::new(2).dispatch().await?;
Err::<(), _>(laravel::abort_with(500, "rolled back"))
})
.await;
assert!(rolled_back.is_err());
Ok::<_, laravel::Error>((during, rows(&connection).await))
})
.await
.unwrap();
assert_eq!(during, Some(0), "the job waits for the commit");
let payloads: Vec<Value> = after
.iter()
.map(|row| serde_json::from_str(&row.payload).unwrap())
.collect();
assert_eq!(payloads.len(), 1);
assert_eq!(payloads[0]["data"]["podcast_id"], 1);
}
pub(crate) async fn bulk_contract(app: &Application) {
let (ids, during, after) = app
.scope(async || {
db::default_connection()?.query("DELETE FROM jobs").statement().await?;
let connection = db::default_connection().unwrap();
let (ids, during) = connection
.transaction(async |tx| {
let ids = queue::bulk((ProcessPodcast::new(1), Ping, ProcessPodcast::new(2), Ping)).await?;
let during = tx.query("SELECT COUNT(*) FROM jobs").scalar::<i64>().await?;
Ok::<_, laravel::Error>((ids, during))
})
.await
.unwrap();
let rolled_back = connection
.transaction(async |_| {
queue::bulk([Ping, Ping]).await?;
Err::<(), _>(laravel::abort_with(500, "rolled back"))
})
.await;
assert!(rolled_back.is_err());
queue::bulk([ProcessPodcast::new(3), ProcessPodcast::new(4)])
.on_queue("urgent")
.await
.unwrap();
Ok::<_, laravel::Error>((ids, during, rows(&connection).await))
})
.await
.unwrap();
assert_eq!(during, Some(0), "the jobs wait for the commit");
let stored: Vec<_> = after
.iter()
.map(|row| {
let payload: Value = serde_json::from_str(&row.payload).unwrap();
(row.queue.as_str(), payload["id"].as_str().unwrap().to_owned())
})
.collect();
let queues: Vec<_> = stored.iter().map(|(queue, _)| *queue).collect();
assert_eq!(
queues,
["podcasts", "default", "podcasts", "default", "urgent", "urgent"]
);
let first_ids: Vec<_> = stored[..4].iter().map(|(_, id)| id.clone()).collect();
assert_eq!(first_ids, ids.iter().map(ToString::to_string).collect::<Vec<_>>());
}
#[cfg(feature = "database-sqlite")]
#[tokio::test]
async fn sqlite_stores_jobs_with_their_queue_delay_and_context() {
let app = application("sqlite::memory:").await;
push_contract(&app).await;
transaction_contract(&app).await;
bulk_contract(&app).await;
}
#[cfg(feature = "database-sqlite")]
#[tokio::test]
async fn sync_jobs_in_a_transaction_run_once_it_commits_and_dispatch_sync_runs_at_once() {
let app = configure("sync")
.with_config(|config, _| {
let mut connection = ConnectionConfig::new("sqlite::memory:");
connection.max_connections = 1;
config.database.default = "primary".into();
config.database.connections.insert("primary".into(), connection);
})
.create();
let during = app
.scope(async || {
db::default_connection()
.unwrap()
.transaction(async |_| {
Ping.dispatch().await?;
ProcessPodcast::new(1).dispatch_sync().await?;
Ok(app.resolve::<Records>().await.all())
})
.await
.unwrap()
})
.await;
assert_eq!(during, ["processed 1 for \"\" on sync/podcasts as attempt 1"]);
assert_eq!(
records(&app).await,
["processed 1 for \"\" on sync/podcasts as attempt 1", "ping"]
);
}
#[derive(Queueable)]
struct CountPodcasts;
#[job]
impl CountPodcasts {
async fn handle(self, records: Inject<Records>) -> laravel::Result<()> {
let count = db::default_connection()?
.query("SELECT COUNT(*) FROM podcasts")
.scalar::<i64>()
.await?
.unwrap_or_default();
records.push(format!("{count} podcasts"));
Ok(())
}
}
#[cfg(feature = "database-sqlite")]
#[tokio::test]
async fn dispatch_sync_in_a_transaction_sees_its_rows() {
let directory = crate::support::TempDir::new("dispatch-sync-transaction");
let url = format!("sqlite://{}?mode=rwc", directory.join("podcasts.sqlite").display());
let app = configure("sync")
.with_config(move |config, _| {
let mut connection = ConnectionConfig::new(url);
connection.max_connections = 2;
config.database.default = "primary".into();
config.database.connections.insert("primary".into(), connection);
})
.create();
app.scope(async || {
let connection = db::default_connection()?;
connection
.query("CREATE TABLE podcasts (id INTEGER PRIMARY KEY)")
.statement()
.await?;
connection
.transaction(async |transaction| {
transaction
.query("INSERT INTO podcasts (id) VALUES (1)")
.statement()
.await?;
CountPodcasts.dispatch_sync().await
})
.await
})
.await
.unwrap();
assert_eq!(records(&app).await, ["1 podcasts"]);
}
}