Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/queue/src/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ mod middleware;
#[cfg(feature = "database")]
#[doc(hidden)]
pub mod models;
mod overlap;
mod payload;
mod queueable;
#[cfg(feature = "redis")]
Expand Down Expand Up @@ -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};
Expand Down
134 changes: 134 additions & 0 deletions crates/queue/src/queue/overlap.rs
Original file line number Diff line number Diff line change
@@ -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<Duration>,
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<ZonedDateTimeArithmetic>) -> 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<ZonedDateTimeArithmetic>) -> 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<String>) -> 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(())
}
}
74 changes: 73 additions & 1 deletion docs/queues.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -724,7 +725,7 @@ impl ProcessPodcast {
<a name="job-middleware"></a>
## 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.

<a name="defining-middleware"></a>
### Defining middleware
Expand Down Expand Up @@ -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).

<a name="preventing-job-overlaps"></a>
### 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()
}

// ...
}
```

<a name="job-chains"></a>
## Job chains

Expand Down
4 changes: 2 additions & 2 deletions src/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading