diff --git a/crates/queue/src/queue.rs b/crates/queue/src/queue.rs index e5c521ef..cd763630 100644 --- a/crates/queue/src/queue.rs +++ b/crates/queue/src/queue.rs @@ -22,6 +22,7 @@ mod middleware; #[cfg(feature = "database")] #[doc(hidden)] pub mod models; +mod overlap; mod payload; mod queueable; #[cfg(feature = "redis")] @@ -69,6 +70,7 @@ pub use self::job::__Registration; pub use self::job::duplicate_names; pub use self::job::{Job, JobId, JobOptions, JobResult, JobTimedOut, ParseIdError}; pub use self::middleware::{IntoMiddleware, Middleware, MiddlewareGroup, Next}; +pub use self::overlap::WithoutOverlapping; #[doc(hidden)] pub use self::payload::{Outcome, Payload, Place, Ran}; pub use self::queueable::{MissingModels, Queueable}; diff --git a/crates/queue/src/queue/overlap.rs b/crates/queue/src/queue/overlap.rs new file mode 100644 index 00000000..6f6fbb36 --- /dev/null +++ b/crates/queue/src/queue/overlap.rs @@ -0,0 +1,134 @@ +use std::fmt; +use std::time::Duration; + +use super::{Attempt, Middleware, Next}; +use jiff::ZonedDateTimeArithmetic; + +use crate::Result; +use crate::clock::exact_duration; + +/// Job middleware that stops a job from running while another attempt of it holds the same +/// [cache lock](crate::cache::lock). +/// +/// Give the middleware a key, such as a user's ID, so that only the jobs for the same key wait for +/// each other. By default, an attempt that finds the lock taken is released back onto the queue +/// right away. The lock is released when the attempt ends, even when the job fails, panics, or +/// times out. +/// +/// ``` +/// use laravel::queue::{IntoMiddleware, Queueable, WithoutOverlapping, job}; +/// use laravel::time::ToSpan; +/// +/// #[derive(Queueable)] +/// pub struct UpdateCreditScore { +/// pub user_id: i64, +/// } +/// +/// #[job] +/// impl UpdateCreditScore { +/// fn middleware(&self) -> impl IntoMiddleware { +/// WithoutOverlapping::new(self.user_id).release_after(10.seconds()) +/// } +/// +/// async fn handle(self) -> laravel::Result<()> { +/// Ok(()) +/// } +/// } +/// ``` +/// +/// The lock is named `laravel-queue-overlap:{job}:{key}`, after the job's name and the key. Call +/// [`shared`](Self::shared) to drop the job's name, so that different jobs with the same key +/// wait for each other. The lock lives in the default cache store, so the store must support +/// locks, and must be shared between workers, as the `database` and `redis` stores are, for the +/// lock to cover jobs on more than one worker. +#[derive(Clone, Debug)] +#[must_use = "a middleware does nothing until a job's `middleware` method returns it"] +pub struct WithoutOverlapping { + key: String, + release_after: Option, + expire_after: Duration, + prefix: String, + shared: bool, +} + +impl WithoutOverlapping { + /// The lock's duration, unless [`expire_after`](Self::expire_after) sets another. + /// + /// A lock needs a duration, so a worker that dies while holding it doesn't keep the job from + /// running forever. + pub const DEFAULT_EXPIRATION: Duration = Duration::from_hours(24); + + /// A middleware that stops two attempts with the same `key` from running at once. + /// + /// Pass an empty key, as `WithoutOverlapping::new("")`, so that no two attempts of the job + /// run at once. + pub fn new(key: impl fmt::Display) -> Self { + Self { + key: key.to_string(), + release_after: Some(Duration::ZERO), + expire_after: Self::DEFAULT_EXPIRATION, + prefix: "laravel-queue-overlap:".to_owned(), + shared: false, + } + } + + /// Release an attempt that finds the lock taken back onto the queue after `delay`, instead of + /// right away. + /// + /// The release counts toward the job's `tries`, as any other release does. + pub fn release_after(mut self, delay: impl Into) -> Self { + self.release_after = Some(exact_duration(delay)); + self + } + + /// End an attempt that finds the lock taken without running the job or releasing it, so the + /// job is removed from the queue. + pub fn dont_release(mut self) -> Self { + self.release_after = None; + self + } + + /// Hold the lock for at most `ttl`, instead of [`DEFAULT_EXPIRATION`](Self::DEFAULT_EXPIRATION). + /// + /// Choose a duration longer than the job takes, since another attempt may start once the lock + /// expires. + pub fn expire_after(mut self, ttl: impl Into) -> Self { + self.expire_after = exact_duration(ttl); + self + } + + /// Start the lock's name with `prefix`, instead of `laravel-queue-overlap:`. + pub fn with_prefix(mut self, prefix: impl Into) -> Self { + self.prefix = prefix.into(); + self + } + + /// Share the lock with every job that uses the same key, by leaving the job's name out of the + /// lock's name. + pub fn shared(mut self) -> Self { + self.shared = true; + self + } + + /// The name of the lock this middleware takes for an attempt of the job named `job`. + pub fn lock_name(&self, job: &str) -> String { + if self.shared { + format!("{}{}", self.prefix, self.key) + } else { + format!("{}{job}:{}", self.prefix, self.key) + } + } +} + +impl Middleware for WithoutOverlapping { + async fn handle(self, attempt: &Attempt, next: Next) -> Result<()> { + let lock = crate::cache::lock(&self.lock_name(attempt.name()), self.expire_after)?; + if lock.get(|| next.run()).await?.is_none() + && let Some(delay) = self.release_after + { + attempt.release(delay); + } + + Ok(()) + } +} diff --git a/docs/queues.md b/docs/queues.md index 7ead7394..addd1996 100644 --- a/docs/queues.md +++ b/docs/queues.md @@ -26,6 +26,7 @@ - [Job middleware](#job-middleware) - [Defining middleware](#defining-middleware) - [Assigning middleware to jobs](#assigning-middleware-to-jobs) + - [Preventing job overlaps](#preventing-job-overlaps) - [Job chains](#job-chains) - [Adding jobs to the chain](#adding-jobs-to-the-chain) - [Chain failures](#chain-failures) @@ -724,7 +725,7 @@ impl ProcessPodcast { ## Job middleware -When multiple jobs share the same guard or rate-limiting logic, such as staying within a mail provider's sending limit or skipping unverified users, extract it into job middleware instead of repeating it in every `handle` method. To stop a job from overlapping with itself, build a middleware around a [cache lock](cache.md#atomic-locks). +When multiple jobs share the same guard or rate-limiting logic, such as staying within a mail provider's sending limit or skipping unverified users, extract it into job middleware instead of repeating it in every `handle` method. To stop a job from overlapping with itself, use the built-in [`WithoutOverlapping`](#preventing-job-overlaps) middleware. ### Defining middleware @@ -845,6 +846,77 @@ impl SendNewsletter { A job's [`timeout`](#job-options) applies to its middleware and `handle` method together. Middleware runs wherever the job executes, including on the `sync` connection and in [test attempts](#testing-a-job). + +### Preventing job overlaps + +The `WithoutOverlapping` middleware prevents job overlaps based on an arbitrary key. This can be helpful when a queued job modifies a resource that should only be modified by one job at a time. + +For example, imagine you have a queued job that updates a user's credit score, and you want to prevent credit score update jobs for the same user ID from overlapping. To accomplish this, return the `WithoutOverlapping` middleware from your job's `middleware` method: + +```rust +use laravel::queue::{IntoMiddleware, WithoutOverlapping, job}; + +#[job] +impl UpdateCreditScore { + fn middleware(&self) -> impl IntoMiddleware { + WithoutOverlapping::new(self.user_id) + } + + async fn handle(self) -> laravel::Result<()> { + // Update the user's credit score... + + Ok(()) + } +} +``` + +Jobs with different keys run concurrently. To prevent any two attempts of the job from running at once, pass an empty key, as in `WithoutOverlapping::new("")`. + +When an attempt finds the lock taken, the middleware releases it back onto the queue right away, without running `handle`. A release counts toward the job's `tries`, as any other release does. To release the job after a delay instead, call `release_after`: + +```rust +WithoutOverlapping::new(self.user_id).release_after(10.seconds()) +``` + +If you would rather remove an overlapping job from the queue so that it is not retried, call `dont_release`: + +```rust +WithoutOverlapping::new(self.user_id).dont_release() +``` + +The middleware is built on Laravel's [atomic locks](cache.md#atomic-locks) and uses your application's default cache store. The lock is released when the attempt ends, even if the job fails, panics, or times out. Because every cache lock needs a duration, the lock expires after 24 hours by default, so a worker that dies while holding it doesn't block the job forever. You may choose a different duration with `expire_after`. Choose a duration longer than the job takes, since another attempt may start once the lock expires: + +```rust +WithoutOverlapping::new(self.user_id).expire_after(3.minutes()) +``` + +> [!WARNING] +> The `WithoutOverlapping` middleware requires a cache store that supports [locks](cache.md#atomic-locks). To prevent overlaps across workers on different servers, use a shared store such as `database` or `redis`; locks on the `memory` store only coordinate jobs within a single process. + +By default, the lock's name includes the job's name, so different job types with the same key run independently. Call `shared` to have different jobs with the same key wait for each other: + +```rust +use laravel::queue::{IntoMiddleware, WithoutOverlapping, job}; + +#[job] +impl ProviderIsDown { + fn middleware(&self) -> impl IntoMiddleware { + WithoutOverlapping::new(&self.provider).shared() + } + + // ... +} + +#[job] +impl ProviderIsUp { + fn middleware(&self) -> impl IntoMiddleware { + WithoutOverlapping::new(&self.provider).shared() + } + + // ... +} +``` + ## Job chains diff --git a/src/queue.rs b/src/queue.rs index e57f8ff4..d020062d 100644 --- a/src/queue.rs +++ b/src/queue.rs @@ -97,8 +97,8 @@ pub use laravel_queue::queue::{ Drivers, Failed, Finally, HEARTBEAT, IntoBatchJob, IntoBatchJobs, IntoJobs, IntoMiddleware, Job, JobId, JobList, JobOptions, JobResult, JobTimedOut, JobTypes, LEASE, Middleware, MiddlewareGroup, MissingModels, Next, ParseIdError, PendingBatch, PendingBulk, PendingChain, PendingDispatch, Pushed, PushedBatch, QueueFake, - QueueManager, QueueSizes, Queueable, Reservation, ReservedJob, Then, batch, bulk, callback, cancel_batch, chain, - dispatch, dispatch_sync, events, fake, find_batch, job, manager, middleware, + QueueManager, QueueSizes, Queueable, Reservation, ReservedJob, Then, WithoutOverlapping, batch, bulk, callback, + cancel_batch, chain, dispatch, dispatch_sync, events, fake, find_batch, job, manager, middleware, }; /// Define a migration's `migrate` function to create the `database` queue driver's tables. diff --git a/tests/queue_overlap.rs b/tests/queue_overlap.rs new file mode 100644 index 00000000..b8fd4157 --- /dev/null +++ b/tests/queue_overlap.rs @@ -0,0 +1,207 @@ +use std::time::Duration; + +use laravel::Application; +use laravel::cache; +use laravel::config::Env; +use laravel::container::Inject; +use laravel::queue::{IntoMiddleware, Queueable, WithoutOverlapping, job}; +use laravel::testing::RunsJobs; +use laravel::time::ToSpan; +use serde::{Deserialize, Serialize}; + +use crate::queue::Records; + +#[derive(Debug, thiserror::Error)] +#[error("the report broke")] +struct Broke; + +#[derive(Clone, Copy, Serialize, Deserialize)] +enum Busy { + Release, + ReleaseAfter, + DontRelease, + Shared, +} + +#[derive(Queueable)] +struct BuildReport { + user_id: i64, + busy: Busy, + outcome: String, +} + +impl BuildReport { + fn new(user_id: i64, busy: Busy) -> Self { + Self { + user_id, + busy, + outcome: "ok".into(), + } + } +} + +#[job(tries = 3)] +impl BuildReport { + fn middleware(&self) -> impl IntoMiddleware { + let middleware = WithoutOverlapping::new(self.user_id); + match self.busy { + Busy::Release => middleware, + Busy::ReleaseAfter => middleware.release_after(30.seconds()), + Busy::DontRelease => middleware.dont_release(), + Busy::Shared => middleware.shared(), + } + } + + async fn handle(self, records: Inject) -> laravel::Result<()> { + records.push(format!("built report {}", self.user_id)); + match self.outcome.as_str() { + "error" => Err(Broke.into()), + "panic" => panic!("the report panicked"), + _ => Ok(()), + } + } +} + +fn application() -> Application { + Application::configure() + .replace_env(Env::default()) + .with_config(|config, _| { + config.queue.default = "discard".into(); + }) + .with_services(|services| { + services.instance(Records::default()); + }) + .create() +} + +async fn take(app: &Application) -> Vec { + let records = app.resolve::().await; + let all = records.all(); + records.clear(); + + all +} + +/// Whether the lock is free, by taking it and releasing it again. +async fn is_free(app: &Application, name: &str) -> bool { + app.scope(async || { + let lock = cache::lock(name, 1.minutes())?; + let free = lock.acquire().await?; + if free { + lock.release().await?; + } + + Ok::<_, laravel::Error>(free) + }) + .await + .unwrap() +} + +/// Takes the lock for another worker's attempt, and returns its owner token. +async fn hold(app: &Application, name: &str) -> String { + app.scope(async || { + let lock = cache::lock(name, 1.minutes())?; + assert!(lock.acquire().await?, "`{name}` is free"); + + Ok::<_, laravel::Error>(lock.owner().to_owned()) + }) + .await + .unwrap() +} + +async fn free(app: &Application, name: &str, owner: &str) { + app.scope(async || cache::restore_lock(name, owner)?.release().await) + .await + .unwrap(); +} + +fn lock_name(user_id: i64) -> String { + WithoutOverlapping::new(user_id).lock_name(std::any::type_name::()) +} + +#[test] +fn the_lock_is_named_after_the_job_and_the_key() { + let middleware = WithoutOverlapping::new(7); + assert_eq!( + middleware.lock_name("app::jobs::BuildReport"), + "laravel-queue-overlap:app::jobs::BuildReport:7" + ); + assert_eq!( + middleware.clone().shared().lock_name("app::jobs::BuildReport"), + "laravel-queue-overlap:7" + ); + assert_eq!( + middleware.with_prefix("reports:").lock_name("BuildReport"), + "reports:BuildReport:7" + ); +} + +#[tokio::test] +async fn a_free_lock_runs_the_job_and_is_released_afterward() { + let app = application(); + + app.job(BuildReport::new(1, Busy::Release)).await.assert_succeeded(); + assert_eq!(take(&app).await, ["built report 1"]); + assert!(is_free(&app, &lock_name(1)).await); +} + +#[tokio::test] +async fn a_taken_lock_releases_the_job_without_running_it() { + let app = application(); + let owner = hold(&app, &lock_name(1)).await; + + app.job(BuildReport::new(1, Busy::Release)) + .await + .assert_released_after(Duration::ZERO); + app.job(BuildReport::new(1, Busy::ReleaseAfter)) + .await + .assert_released_after(30.seconds()); + assert_eq!(take(&app).await, Vec::::new()); + + app.job(BuildReport::new(2, Busy::Release)).await.assert_succeeded(); + assert_eq!(take(&app).await, ["built report 2"], "another key has its own lock"); + assert!( + !is_free(&app, &lock_name(1)).await, + "the attempt left the other worker's lock alone" + ); + + free(&app, &lock_name(1), &owner).await; + app.job(BuildReport::new(1, Busy::Release)).await.assert_succeeded(); + assert_eq!(take(&app).await, ["built report 1"]); +} + +#[tokio::test] +async fn dont_release_ends_the_attempt_without_running_the_job() { + let app = application(); + hold(&app, &lock_name(1)).await; + + app.job(BuildReport::new(1, Busy::DontRelease)).await.assert_succeeded(); + assert_eq!(take(&app).await, Vec::::new()); +} + +#[tokio::test] +async fn shared_locks_leave_out_the_jobs_name() { + let app = application(); + hold(&app, "laravel-queue-overlap:1").await; + + app.job(BuildReport::new(1, Busy::Shared)) + .await + .assert_released_after(Duration::ZERO); + app.job(BuildReport::new(1, Busy::Release)).await.assert_succeeded(); + assert_eq!(take(&app).await, ["built report 1"]); +} + +#[tokio::test] +async fn the_lock_is_released_when_the_job_fails_or_panics() { + let app = application(); + + let mut failing = BuildReport::new(1, Busy::Release); + failing.outcome = "error".into(); + app.job(failing).await.assert_failed_with::(); + assert!(is_free(&app, &lock_name(1)).await, "after an error"); + + let mut panicking = BuildReport::new(1, Busy::Release); + panicking.outcome = "panic".into(); + app.job(panicking).await.assert_failed(); + assert!(is_free(&app, &lock_name(1)).await, "after a panic"); +} diff --git a/tests/suite_queue.rs b/tests/suite_queue.rs index 3a4825b3..6336bd10 100644 --- a/tests/suite_queue.rs +++ b/tests/suite_queue.rs @@ -20,6 +20,7 @@ mod queue_listeners; mod queue_middleware; #[cfg(feature = "database-sqlite")] mod queue_models; +mod queue_overlap; #[cfg(feature = "redis")] mod queue_redis; #[cfg(feature = "database")]