use std::time::Duration;
use laravel::Application;
use laravel::cache::{MemoryStore, Store};
use laravel::config::Env;
use laravel::config::cache::StoreConfig;
use laravel::container::Inject;
use laravel::queue::Queueable;
use laravel::queue::{self, Attempt, IntoMiddleware, Next, job, middleware};
use laravel::time::ToSpan;
use crate::queue::Records;
#[derive(Queueable)]
struct Reindex {
product: u32,
revision: String,
}
impl Reindex {
fn new(product: u32, revision: &str) -> Self {
Self {
product,
revision: revision.into(),
}
}
}
#[job(debounce_for = 30.seconds())]
impl Reindex {
fn debounce_id(&self) -> u32 {
self.product
}
async fn handle(self, records: Inject<Records>) {
records.push(format!("reindexed {} at {}", self.product, self.revision));
}
}
#[derive(Queueable)]
struct RebuildSitemap(u32);
#[job(debounce_for = 30.seconds())]
impl RebuildSitemap {
async fn handle(self, records: Inject<Records>) {
records.push(format!("sitemap {}", self.0));
}
}
#[derive(Default)]
struct SharedStore(MemoryStore);
impl Store for SharedStore {
async fn get(&self, key: &str) -> laravel::Result<Option<String>> {
self.0.get(key).await
}
async fn put(&self, key: &str, value: String, ttl: Duration) -> laravel::Result<()> {
self.0.put(key, value, ttl).await?;
tokio::task::yield_now().await;
Ok(())
}
async fn add(&self, key: &str, value: String, ttl: Duration) -> laravel::Result<bool> {
self.0.add(key, value, ttl).await
}
async fn increment(&self, key: &str, by: i64) -> laravel::Result<Option<i64>> {
self.0.increment(key, by).await
}
async fn forget(&self, key: &str) -> laravel::Result<bool> {
self.0.forget(key).await
}
async fn flush(&self) -> laravel::Result<()> {
self.0.flush().await
}
}
#[tokio::test]
async fn concurrent_dispatches_on_the_sync_connection_all_run() {
let app = Application::configure()
.replace_env(Env::from_iter([("CACHE_STORE", "shared")]))
.with_config(|config, _| {
config.queue.default = "sync".into();
config.cache.add_store("shared", StoreConfig::custom("shared"));
})
.with_services(|services| {
services.instance(Records::default());
services
.cache()
.extend("shared", |_app, _definition| async { Ok(SharedStore::default()) });
})
.create();
app.scope(async || {
let (first, second) = tokio::join!(
Reindex::new(1, "first").dispatch(),
Reindex::new(1, "second").dispatch()
);
first.and(second)?;
Reindex::new(1, "third").dispatch_sync().await
})
.await
.unwrap();
let mut records = app.resolve::<Records>().await.all();
records[..2].sort();
assert_eq!(
records,
["reindexed 1 at first", "reindexed 1 at second", "reindexed 1 at third"]
);
}
#[derive(Queueable)]
struct Recount {
revision: u32,
hold: bool,
}
#[middleware]
async fn hold_back(attempt: &Attempt, _next: Next) -> laravel::Result<()> {
attempt.release(1.hours());
Ok(())
}
#[job(debounce_for = 30.seconds(), max_wait = 1.minutes())]
impl Recount {
fn middleware(&self) -> impl IntoMiddleware {
self.hold.then_some(hold_back)
}
async fn handle(self, records: Inject<Records>) {
records.push(format!("recount {}", self.revision));
}
}
#[tokio::test]
async fn fakes_record_the_debounced_delay() {
let app = Application::configure().replace_env(Env::default()).create();
let delays = app
.scope(async || {
let queue = queue::fake();
Reindex::new(1, "first").dispatch().await?;
Reindex::new(1, "second").dispatch().delay(5.seconds()).await?;
Recount {
revision: 1,
hold: false,
}
.dispatch()
.await?;
app.travel(50.seconds());
Recount {
revision: 2,
hold: false,
}
.dispatch()
.await?;
app.travel(11.seconds());
Recount {
revision: 3,
hold: false,
}
.dispatch()
.await?;
Recount {
revision: 4,
hold: false,
}
.dispatch()
.await?;
queue.assert_pushed_times::<Reindex>(2);
let reindexed: Vec<_> = queue.pushed::<Reindex>().iter().map(|job| job.delay()).collect();
let recounted: Vec<_> = queue.pushed::<Recount>().iter().map(|job| job.delay()).collect();
Ok::<_, laravel::Error>((reindexed, recounted))
})
.await
.unwrap();
let seconds = Duration::from_secs;
assert_eq!(delays.0, [seconds(30), seconds(5)], "a dispatch's own delay wins");
assert_eq!(
delays.1,
[seconds(30), seconds(30), Duration::ZERO, seconds(30)],
"the dispatch a minute after the first runs without waiting, and the next starts a new wait"
);
}
#[derive(Queueable)]
struct Resync(u32);
#[job(debounce_for = 10.seconds(), max_wait = 10.minutes())]
impl Resync {
async fn handle(self) {}
}
#[tokio::test]
async fn max_wait_holds_when_it_outlasts_the_debounce_id() {
let app = Application::configure().replace_env(Env::default()).create();
let delays = app
.scope(async || {
let queue = queue::fake();
for minute in 0..12 {
Resync(minute).dispatch().await?;
app.travel(1.minutes());
}
Ok::<_, laravel::Error>(
queue
.pushed::<Resync>()
.iter()
.map(|job| job.delay())
.collect::<Vec<_>>(),
)
})
.await
.unwrap();
let mut expected = vec![Duration::from_secs(10); 12];
expected[10] = Duration::ZERO;
assert_eq!(
delays, expected,
"the dispatch ten minutes after the first doesn't wait"
);
}
#[cfg(feature = "database-sqlite")]
mod database {
use laravel::cache;
use laravel::config::database::ConnectionConfig;
use laravel::config::queue::DatabaseQueue;
use laravel::db;
use laravel::event::Event;
use laravel::queue::events::JobProcessed;
use laravel::testing::{MakesConsoleRequests, TestCommandResult};
use laravel::time::Timestamp;
use super::*;
use crate::queue::database::create_table;
#[derive(Queueable)]
struct Note(String);
#[job]
impl Note {
async fn handle(self, records: Inject<Records>) {
records.push(self.0);
}
}
#[derive(Default)]
struct Seen(Records);
const NOW: i64 = 1_800_000_000;
async fn application(directory: &crate::support::TempDir) -> Application {
let url = format!("sqlite://{}?mode=rwc", directory.join("queue.sqlite").display());
let app = Application::configure()
.replace_env(Env::default())
.with_config(move |config, _| {
config.queue.default = "database".into();
config
.queue
.add_connection("broken", DatabaseQueue::new().table("missing_jobs"));
config.database.default = "primary".into();
config
.database
.connections
.insert("primary".into(), ConnectionConfig::new(url));
})
.with_services(|services| {
services.instance(Records::default());
services.instance(Seen::default());
})
.with_events(|events, _| {
events.listen(|event: Event<JobProcessed>, seen: Inject<Seen>| async move {
seen.0.push(format!("{} {}", event.job.name, event.outcome));
});
})
.create();
app.scope(async || {
let connection = db::default_connection()?;
connection.query(create_table(connection.driver())).statement().await
})
.await
.unwrap();
app.travel_to(Timestamp::from_second(NOW).unwrap());
app
}
async fn work(app: &Application) -> TestCommandResult {
tokio::time::timeout(Duration::from_secs(30), app.command("queue:work --stop-when-empty"))
.await
.expect("the worker should stop once no job is available")
}
#[derive(db::FromRow)]
struct Row {
available_at: Timestamp,
}
async fn available_at(app: &Application) -> Vec<i64> {
let rows: Vec<Row> = app
.scope(async || {
db::default_connection()?
.query("SELECT available_at FROM jobs ORDER BY id")
.select_as()
.await
})
.await
.unwrap();
rows.into_iter().map(|row| row.available_at.as_second() - NOW).collect()
}
async fn records(app: &Application) -> Vec<String> {
app.resolve::<Records>().await.all()
}
#[tokio::test]
async fn the_worker_runs_only_the_latest_dispatch_of_each_debounce_id() {
let directory = crate::support::TempDir::new("queue-debounce-worker");
let app = application(&directory).await;
app.scope(async || {
Reindex::new(1, "first").dispatch().await?;
Reindex::new(2, "only").dispatch().await?;
Reindex::new(1, "second").dispatch().await?;
RebuildSitemap(1).dispatch().await?;
app.travel(10.seconds());
RebuildSitemap(2).dispatch().delay(5.seconds()).await?;
Ok::<_, laravel::Error>(())
})
.await
.unwrap();
assert_eq!(available_at(&app).await, [30, 30, 30, 30, 15]);
app.travel(5.seconds());
let result = work(&app).await;
result.assert_successful();
assert_eq!(records(&app).await, ["sitemap 2"], "{}", result.output());
app.travel(15.seconds());
let result = work(&app).await;
result.assert_successful();
assert_eq!(
result.error_output().matches(" debounced ").count(),
2,
"{}",
result.error_output()
);
assert_eq!(
records(&app).await,
["sitemap 2", "reindexed 2 at only", "reindexed 1 at second"]
);
assert_eq!(
app.resolve::<Seen>().await.0.all(),
[
"integration::queue_debounce::RebuildSitemap succeeded",
"integration::queue_debounce::Reindex debounced",
"integration::queue_debounce::Reindex succeeded",
"integration::queue_debounce::Reindex succeeded",
"integration::queue_debounce::RebuildSitemap debounced",
]
);
assert!(available_at(&app).await.is_empty());
}
#[tokio::test]
async fn a_dispatch_runs_without_waiting_once_the_first_has_waited_max_wait() {
let directory = crate::support::TempDir::new("queue-debounce-max-wait");
let app = application(&directory).await;
let dispatch = |revision, hold| app.scope(async move || Recount { revision, hold }.dispatch().await.map(drop));
dispatch(1, false).await.unwrap();
app.travel(50.seconds());
dispatch(2, false).await.unwrap();
app.travel(11.seconds());
dispatch(3, false).await.unwrap();
dispatch(33, false).await.unwrap();
assert_eq!(available_at(&app).await, [30, 80, 61, 91]);
work(&app).await.assert_successful();
app.travel(20.seconds());
work(&app).await.assert_successful();
assert_eq!(
records(&app).await,
["recount 3"],
"the dispatch that ended the wait runs, though a later dispatch started a new one"
);
app.travel(10.minutes());
dispatch(4, false).await.unwrap();
app.travel(30.seconds());
work(&app).await.assert_successful();
app.travel(31.seconds());
dispatch(5, true).await.unwrap();
assert_eq!(available_at(&app).await, [742 + 30]);
app.travel(30.seconds());
work(&app).await.assert_successful();
app.travel(31.seconds());
dispatch(6, false).await.unwrap();
assert_eq!(available_at(&app).await, [772 + 3600, 803]);
assert_eq!(records(&app).await, ["recount 3", "recount 4"]);
}
#[tokio::test]
async fn replaced_chains_rolled_back_dispatches_failed_pushes_and_lost_keys() {
let directory = crate::support::TempDir::new("queue-debounce-edges");
let app = application(&directory).await;
app.scope(async || {
queue::chain(Reindex::new(1, "chained"))
.then(Note("after the chained job".into()))
.await?;
queue::chain(Note("first link".into()))
.then(Reindex::new(1, "latest"))
.await?;
Ok::<_, laravel::Error>(())
})
.await
.unwrap();
work(&app).await.assert_successful();
assert_eq!(available_at(&app).await, [30, 30]);
app.travel(30.seconds());
work(&app).await.assert_successful();
assert_eq!(records(&app).await, ["first link", "reindexed 1 at latest"]);
app.resolve::<Records>().await.clear();
app.scope(async || {
Reindex::new(2, "committed").dispatch().await?;
let rolled_back = db::default_connection()?
.transaction(async |_| {
Reindex::new(2, "rolled back").dispatch().await?;
Err::<(), _>(laravel::abort_with(500, "rolled back"))
})
.await;
assert!(rolled_back.is_err());
let refused = Reindex::new(2, "refused").dispatch().on_connection("broken").await;
assert!(refused.is_err());
Ok::<_, laravel::Error>(())
})
.await
.unwrap();
app.travel(30.seconds());
work(&app).await.assert_successful();
assert_eq!(records(&app).await, ["reindexed 2 at committed"]);
app.resolve::<Records>().await.clear();
app.scope(async || {
Reindex::new(3, "first").dispatch().await?;
Reindex::new(3, "second").dispatch().await?;
cache::flush().await
})
.await
.unwrap();
app.travel(30.seconds());
work(&app).await.assert_successful();
assert_eq!(records(&app).await, ["reindexed 3 at first", "reindexed 3 at second"]);
}
}