diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fa5fe7..bee67f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,71 @@ All notable changes to `initphp/queue` are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- `Contracts\OwnershipAwareIdempotencyStore` (extends `IdempotencyStore`, optional, + independent of `CompletionAwareIdempotencyStore`): `claimOwned()` returns a token + for the claim it took, `forgetOwned()` releases a claim only while that token + still owns the key. The `Dispatcher` uses them when the store implements the + interface; a store that does not keeps `claim()` and `forget()` exactly as before. + The bundled `InMemoryIdempotencyStore` implements it. +- `ReceivedMessage` has a new optional last constructor argument `$abandoned` and + `wasAbandoned()`: the transport has handed the message out again after a delivery + that never ended in an ack, release or dead-letter, and has already counted that + delivery in `attempts()`. +- `RedisTransport` has a new optional last constructor argument `$startedSuffix` + (default `:started`). + +### Fixed + +- **A handler that kills its process now counts as an attempt.** A handler killed by + out-of-memory, `exit` or `SIGKILL` never reports a failure, so its message used to + come back with the same `attempts` for ever. The transport now counts the + unfinished delivery when it hands the message out again, and the `Worker` + dead-letters it (reason `failed`) once `attempts` reaches `maxAttempts`, without + running the handler again. PDO: a row taken over after its reservation lapsed gets + `attempts` (column and envelope) raised in the same `UPDATE` that takes it, so one + worker counts it; no schema change. Redis: `reserve()` records each delivery in a + `:started` sorted set (SHA-1 of the body) that `ack()`, `release()` and + `deadLetter()` clear, and a body that returns with its entry still there is + counted, in the body and in the processing entry, so the count survives the next + crash; the body format is unchanged and a client without the sorted-set commands + switches the counting off. RabbitMQ: the broker's `redelivered` flag counts one + attempt (a classic queue keeps no delivery count, so repeated crashes are not + bounded there). Waiting for another handler's in-flight key is a release and is + never counted, so `inFlightDelaySeconds` waits still use no attempts. +- **A handler that outlived its lease no longer deletes the new holder's claim.** On + a store that implements `OwnershipAwareIdempotencyStore`, the late failure releases + only its own claim, so the claim or completed record of the worker that took over + stays. +- An abandoned message that is out of attempts is checked against the idempotency + store before it is dead-lettered: a key recorded as processed drops it as a + `duplicate` (the handler finished, only its ack was lost) and a key still claimed + releases it as `in_flight`. `Dispatcher::dispatch()` has a new optional second + argument, `$exhausted`, for this; the `Worker` passes it. A message that is put + back this way is treated as exhausted when it returns: any message that arrives + with `attempts` at or above `maxAttempts` and no `dead_letter` block is, so a + handler that kills its process every time reaches the dead-letter queue even when + `leaseSeconds` is longer than the transport's redelivery time. A store that cannot + tell a recorded key from a claimed one now dead-letters such a message instead of + discarding it. +- `RedisTransport` counting never fails a reservation: a `NOPERM`/unknown-command + refusal of `ZREMRANGEBYSCORE`, `LINSERT` or the other commands it adds switches the + counting off, and any other failure while counting hands the message out + uncounted, instead of leaving it on `:processing`. +- `PdoTransport::release()` for a worker whose reservation was taken over records + the back-off even when the stored `attempts` already equals the one it reports + (the take-over counted it); `attempts` still never goes back. + +### Notes + +- Nothing changes for existing stores, transports or message bodies; see + `docs/Idempotent-Consumption.md` (Upgrading from 2.3) for rolling deploys. A + handler that outlives `retryAfter` (PDO) or your Redis reaper's delay while its + worker is alive looks like a dead one and its second delivery is counted. + ## [2.3.0] - 2026-11-25 ### Added diff --git a/README.md b/README.md index 5464bc4..cd12d05 100644 --- a/README.md +++ b/README.md @@ -222,12 +222,17 @@ is discarded. before `remember()` leaves no record; once the lease lapses the redelivery runs the handler again. This is not "at most once". 2. **A handler that outlives its lease can run twice**, because a second worker - then wins the claim. + then wins the claim. With a store that implements `OwnershipAwareIdempotencyStore` + its later failure releases only its own claim; with one that does not, the + failure's `forget()` can delete the newer claim or the completed record. 3. **A claim that never lapses keeps its message waiting.** Give every claim a lease; `leaseSeconds: 0` holds it until `forget()`. -4. **A handler that kills its process never counts as failed**, so its `attempts` - does not rise and it never reaches the dead-letter queue; it is picked up again - each time the lease lapses. +4. **A handler that kills its process is counted by the transport.** It never + reports a failure, so when the transport hands the message out again it counts + that unfinished delivery as one attempt, and the worker dead-letters the message + at `maxAttempts` without running the handler. PDO and Redis count every one; + RabbitMQ counts one (no delivery count on a classic queue). Waiting for an + in-flight key is never counted. See `docs/Retries-and-Dead-Letters.md`. 5. **On Redis, a reaper that rewrites the envelope hides the late failure.** A handler that outlives the reaper still has its failure counted (it replaces the reclaimed copy, so `maxAttempts` ends the message), but only while the copy has diff --git a/docs/API-Reference.md b/docs/API-Reference.md index 41d9a54..843b5c5 100644 --- a/docs/API-Reference.md +++ b/docs/API-Reference.md @@ -111,7 +111,8 @@ public function keyFor(InitPHP\Queue\Message\ReceivedMessage $message): ?string A negative `ttl` or `leaseSeconds`, or an `inFlightDelaySeconds` below 1, throws `ConfigurationException`. `InitPHP\Queue\Consumer\InMemoryIdempotencyStore` -implements `CompletionAwareIdempotencyStore` and adds `count(): int`. +implements `CompletionAwareIdempotencyStore` and `OwnershipAwareIdempotencyStore` and +adds `count(): int`. ### Outcome / OutcomeKind @@ -213,6 +214,23 @@ failed claim on a completed key is dropped, on an in-flight key the message is released. A store that implements only `IdempotencyStore` keeps the previous behaviour (always dropped). See [Idempotent Consumption](Idempotent-Consumption.md). +### OwnershipAwareIdempotencyStore + +```php +interface OwnershipAwareIdempotencyStore extends IdempotencyStore +{ + public function claimOwned(string $key, int $leaseSeconds = 0): ?string; // token, or null when not won + public function forgetOwned(string $key, string $token): void; // releases only the claim the token owns +} +``` + +Optional and independent of `CompletionAwareIdempotencyStore`. When the store +implements it, the `Dispatcher` takes the claim with `claimOwned()` and releases a +failed handler's claim with `forgetOwned()`, so a handler that outlived its lease +cannot delete the claim or the completed record of the worker that took over. A store +without it keeps `claim()` and `forget()`. `InMemoryIdempotencyStore` implements it. +See [Claim ownership](Idempotent-Consumption.md#claim-ownership). + ### ConsumerTransport ```php @@ -234,7 +252,7 @@ interface ConsumerTransport `InitPHP\Queue\Message\ReceivedMessage implements BabelQueue\Contracts\InboundMessage`. ```php -public function __construct(string $queue, string $rawBody, array $envelope, mixed $receipt) +public function __construct(string $queue, string $rawBody, array $envelope, mixed $receipt, bool $abandoned = false) // InboundMessage: public function getUrn(): string @@ -248,6 +266,7 @@ public function rawBody(): string public function envelope(): array public function attempts(): int public function receipt(): mixed +public function wasAbandoned(): bool // a previous delivery never ended; the transport counted it in attempts() ``` --- @@ -286,6 +305,7 @@ public function __construct( string $processingSuffix = ':processing', string $failedSuffix = ':failed', string $delayedSuffix = ':delayed', + string $startedSuffix = ':started', ) ``` diff --git a/docs/Idempotent-Consumption.md b/docs/Idempotent-Consumption.md index fff61e4..10d9ac9 100644 --- a/docs/Idempotent-Consumption.md +++ b/docs/Idempotent-Consumption.md @@ -28,7 +28,8 @@ exactly as before — this is fully backward-compatible. dedup key from the message and *claims* it in the store, holding the claim under a lease (`leaseSeconds`). If the claim succeeds the handler runs; when it returns, the key is **recorded** (`remember()`, kept for `ttl` seconds); when it throws, -the claim is released (`forget()`), so the normal retry runs it again. +the claim is released (`forget()`, or `forgetOwned()` with the claim's token on a +store that [tracks ownership](#claim-ownership)), so the normal retry runs it again. If the claim fails, one of two things is true: @@ -94,8 +95,11 @@ were not run as separate scenarios. must stay idempotent. 2. **A handler that outlives its lease can run twice.** If the lease lapses while the first handler is still running, the next redelivery wins the claim and runs - the same message concurrently. When the first handler then throws, its - `forget()` also frees the newer claim, because a claim carries no owner. + the same message concurrently. On a store that implements + `OwnershipAwareIdempotencyStore` the first handler's later failure releases only + its own claim, so the newer claim and a completed record stay. On a store that + does not, its `forget()` also frees the newer claim, or deletes the completed + record, because the claim carries no owner (see [Claim ownership](#claim-ownership)). 3. **A key stuck in flight keeps its message waiting.** With a lease that never lapses (`leaseSeconds: 0` on a store that then holds the claim forever) a dead worker's claim is never released, and the message is deferred again and again @@ -103,12 +107,18 @@ were not run as separate scenarios. `forget()` on the key (or a lease) frees it, so give every claim a lease. 4. **A store without `isCompleted()` still discards.** See above: such a store keeps the pre-2.3 behaviour, including the message loss it had. -5. **A handler that kills its process never counts as failed.** A message whose - handler is killed each time (out of memory, a fatal error) never reaches the - retry path, so its `attempts` stays the same and it never reaches the - dead-letter queue. Without deduplication it simply crashed the worker again on - every redelivery; with it, the message is picked up again each time the lease - lapses. Watch for a message that keeps appearing. +5. **A handler that kills its process is counted by the transport, not by the + worker.** A handler that is killed (out of memory, `exit`, `SIGKILL`) never + reports a failure. When the transport hands such a message out again, it counts + that unfinished delivery as one attempt, and the worker dead-letters the message + (reason `failed`) once the count reaches `maxAttempts`, without running the + handler again, after checking the store: a key recorded as processed drops the + message as a duplicate, and a key still claimed releases it as `in_flight` (it + stays out of attempts and is dead-lettered once the claim has lapsed). This + does not touch waiting: a message put back for an in-flight + key is released, not abandoned, and is never counted. PDO and Redis count every + unfinished delivery, RabbitMQ counts one (it keeps no delivery count on a classic + queue); see [Retries & Dead-Letters](Retries-and-Dead-Letters.md#a-handler-that-kills-its-process). 6. **On Redis, a reaper that rewrites the envelope hides the late failure.** Redis never redelivers a message by itself; a reaper moves it from `:processing` back onto the queue. If the original handler is still @@ -117,8 +127,11 @@ were not run as separate scenarios. [Transport: Redis](Transport-Redis.md#delivery-semantics)). That only works while the copy still has the body the handler was given: a reaper that rewrites it (to increment `attempts`, say) makes the late failure unmatchable, and only the - reaper's own count applies. A client without `EVAL` keeps the same rules but can - lose a message to a crash in the middle of a retry. + reaper's own count applies. The same holds for the count of a delivery that never + finished (item 5): the transport raises `attempts` in the body it hands out, and + that count is kept only while the reaper moves the body back unchanged. A client + without `EVAL` keeps the same rules but can lose a message to a crash in the + middle of a retry. ### Choosing `leaseSeconds` @@ -140,6 +153,62 @@ Redis store below then hold the claim with no expiry, so a dead worker's claim never lapses. `InMemoryIdempotencyStore` lives and dies with its worker, so it has no orphaned claim, but it also remembers nothing across a restart. +## Claim ownership + +`forget()` removes whatever is stored under the key. A handler that outlives its +lease and then throws would therefore delete the claim, or the completed record, of +the worker that took the key over, and the message would run again. A store that +implements `InitPHP\Queue\Contracts\OwnershipAwareIdempotencyStore` avoids this: + +- `claimOwned(string $key, int $leaseSeconds = 0): ?string` takes the claim like + `claim()` and returns an opaque token that identifies it (`null` when the claim was + not won); +- `forgetOwned(string $key, string $token): void` releases the claim **only if** the + token still owns the key, in one atomic step. A claim another worker took over, or + a key that has since been recorded, is left alone. + +The dispatcher uses these two instead of `claim()` and `forget()` when the store +implements the interface, and only for releasing a failed handler's claim: +`remember()` is unchanged. The interface is optional and independent of +`CompletionAwareIdempotencyStore`; a store may implement either or both, and a store +that implements neither keeps using `claim()` and `forget()` exactly as before. +`claim()`, `remember()` and `forget()` must keep working on a store that adds it. +`InMemoryIdempotencyStore` implements it. A durable example is in +[Bring your own store](#bring-your-own-store). + +## Upgrading from 2.3 + +Nothing has to change: no signature of `IdempotencyStore`, +`CompletionAwareIdempotencyStore`, `ConsumerTransport` or `Handler` changed, the +message body format is unchanged, and `ReceivedMessage` has a new optional last +constructor argument. + +- **Ownership is opt-in.** A custom store keeps `claim()` and `forget()` until you + implement `OwnershipAwareIdempotencyStore`. For a Redis store, store the token as + the claim's value and release with a compare-and-delete script. For a PDO store, + add a nullable `claim_token` column that `claim()` sets (also when it takes over a + lapsed row), that `remember()` clears, and `DELETE … WHERE dedup_key = ? AND + claim_token = ?` in `forgetOwned()`. +- **The count of unfinished deliveries needs no schema change.** PDO reuses + `reserved_at`, Redis adds a `:started` sorted set, RabbitMQ reads the + broker's `redelivered` flag. Rows and messages left by 2.3 are counted like any + other the first time a 2.4 worker takes them over. +- **Rolling deploys are safe in both directions.** A 2.3 worker does not count an + unfinished delivery, so such a delivery is only counted while a 2.4 worker is the + one that takes it over (on Redis, only if a 2.4 worker reserved it first and left + its started entry). A 2.3 worker reading a row or message that a 2.4 worker + counted sees an ordinary `attempts` and the usual body. Deploying all workers gives + the full behaviour; none has to be drained. +- **A late 2.3 worker can lose a back-off.** While 2.3 and 2.4 workers run side by + side, a 2.3 worker whose PDO reservation was taken over by a 2.4 worker still uses + the old rule and skips recording its back-off when the stored `attempts` already + equals its own. The count is right; only that one delay is lost, and only until + the last 2.3 worker has stopped. +- **`retryAfter` and your Redis reaper now matter for `attempts`.** A handler that + runs longer than `retryAfter` (PDO) or than your reaper's delay (Redis) while its + worker is alive is indistinguishable from one that died, so the second delivery is + counted. Keep both above your slowest handler, as before. + ## Upgrading from 2.1 and 2.2 Nothing has to change: `IdempotencyStore`, its method signatures and the @@ -273,6 +342,42 @@ final class RedisIdempotencyStore implements CompletionAwareIdempotencyStore `isCompleted()`, is what lets the dispatcher keep an in-flight message instead of discarding it. Without it a store still works, with the 2.2 behaviour. +To also stop a late failure from releasing a claim that is no longer yours, add +`OwnershipAwareIdempotencyStore` (see [Claim ownership](#claim-ownership)). On Redis, +keep the token as the claim's value and compare it in a script: + +```php +use InitPHP\Queue\Contracts\CompletionAwareIdempotencyStore; +use InitPHP\Queue\Contracts\OwnershipAwareIdempotencyStore; + +final class OwnedRedisIdempotencyStore implements CompletionAwareIdempotencyStore, OwnershipAwareIdempotencyStore +{ + // seen(), claim(), isCompleted(), remember() and forget() as above, with one + // change: isCompleted() must treat a value that starts with 'claimed:' as in flight. + + public function claimOwned(string $key, int $leaseSeconds = 0): ?string + { + $token = bin2hex(random_bytes(16)); + $options = ['NX']; + if ($leaseSeconds > 0) { + $options['EX'] = $leaseSeconds; + } + + return $this->redis->set($key, 'claimed:' . $token, $options) ? $token : null; + } + + public function forgetOwned(string $key, string $token): void + { + // Compare and delete in one step: only the claim that carries our token goes. + $this->redis->eval( + "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end return 0", + [$key, 'claimed:' . $token], + 1, + ); + } +} +``` + A PDO-backed store needs one more step than the Redis one, because a unique constraint does not expire rows by itself. Redis `EX` frees a lapsed claim on its own; with a table, `claim()` must free it explicitly or a dead worker's key stays diff --git a/docs/Retries-and-Dead-Letters.md b/docs/Retries-and-Dead-Letters.md index deaa802..9570186 100644 --- a/docs/Retries-and-Dead-Letters.md +++ b/docs/Retries-and-Dead-Letters.md @@ -25,11 +25,53 @@ The delay between attempts comes from `WorkerOptions::$backoff` > (a delayed sorted set). RabbitMQ retries immediately unless you install the > delayed-message-exchange plugin — see [Transport: RabbitMQ](Transport-RabbitMQ.md). +## A handler that kills its process + +A handler that is killed (out of memory, `exit`, `SIGKILL`) never throws, so the +worker never learns that it failed. The transport does: the message comes back +because its reservation lapsed, or the broker or your reaper returned it. A +delivery that ended without an ack, a release or a dead-letter counts as **one +attempt**, recorded by the transport before it hands the message out again. If that +brings `attempts` to `maxAttempts`, the worker dead-letters the message with reason +`failed` and does not run the handler again. + +| Transport | How the unfinished delivery is found | Counted | +| --------- | ------------------------------------ | ------- | +| PDO | a row that is still stamped `reserved_at` when its reservation lapses (`retryAfter`) | every one, in the same `UPDATE` that takes the row | +| Redis | the body is back on the queue while its `:started` entry is still there | every one, in the body and in the processing entry | +| RabbitMQ | the broker's `redelivered` flag | **one**: classic queues keep no delivery count and the unacked body cannot be rewritten, so a handler that kills its process on every delivery is counted once, not once per crash | + +With [deduplication](Idempotent-Consumption.md) on, the idempotency record is read +before the message is dead-lettered, so a message is not failed for a handler that +did finish. If the key is recorded as processed (the handler finished and only its +ack was lost) the message is acknowledged and discarded as a `duplicate`; if the key +is still claimed (another handler is running, or a dead one's lease has not lapsed) +the message is put back as `in_flight`; only a message with neither is dead-lettered. +A message that is put back this way returns out of attempts: the worker treats any +message that arrives with `attempts` at or above `maxAttempts` and no `dead_letter` +block as exhausted, whether or not the transport still marks it as unfinished, so +the crash loop ends as soon as the dead handler's claim has lapsed, even when +`leaseSeconds` is longer than `retryAfter`. A store that cannot tell a recorded key +from a claimed one cannot say whether the handler finished, so the message is +dead-lettered, never discarded. A [replayed](#replaying-a-dead-lettered-message) +message that still has its `dead_letter` block runs normally. + +A message put back without an outcome of its own, such as one waiting for another +handler's [in-flight key](Idempotent-Consumption.md), has its reservation cleared by +`release()` and is not counted, however many times it waits. A normal failure is not +counted twice either: the unfinished delivery and the failure that follows it are two +different deliveries. + +A handler that outlives `retryAfter` (PDO) or the delay of your Redis reaper while +its worker is alive looks like a dead one: the second delivery is counted. Keep both +above your slowest handler. + ## When a message is dead-lettered | Cause | Reason in the `dead_letter` block | | ----- | --------------------------------- | | Exhausted retries — a handler kept throwing until `attempts` reached `maxAttempts` | `failed` | +| Exhausted deliveries — a handler's process died until `attempts` reached `maxAttempts` (see [above](#a-handler-that-kills-its-process)) | `failed` | | Malformed / poison envelope (missing URN, non-object `data`, bad `attempts`) | an `EnvelopeValidator::REASON_*` value | | Unsupported `meta.schema_version` (a newer producer) — **quarantined, never dropped** | `unsupported_schema_version` | | Unknown URN with the `DEAD_LETTER` strategy (or `FAIL` after retries) | `unknown_urn` | diff --git a/docs/Transport-PDO.md b/docs/Transport-PDO.md index 9a5be82..73ec1c9 100644 --- a/docs/Transport-PDO.md +++ b/docs/Transport-PDO.md @@ -92,7 +92,9 @@ alike, without `SELECT … FOR UPDATE SKIP LOCKED`: 1. `SELECT` the oldest ready row for the queue (`available_at <= now`, not currently reserved). -2. `UPDATE … SET reserved_at = now WHERE id = ? AND (reserved_at IS NULL OR reserved_at <= :stale)`. +2. `UPDATE … SET reserved_at = now WHERE id = ? AND reserved_at IS NULL`; for a row + whose reservation has lapsed, `… AND reserved_at = ` + instead (see below). 3. If exactly one row was affected, the claim succeeded; otherwise another worker won it, so try the next row. @@ -105,6 +107,18 @@ reservation older than `retryAfter` seconds (default 90) is treated as abandoned and becomes reservable again, so the message is delivered again (at-least-once) instead of staying stuck. Set it comfortably above your slowest handler's runtime. +**A lapsed reservation counts as an attempt.** A row that is still stamped +`reserved_at` when it is taken over was never acked, released or dead-lettered: its +worker died (a handler killed by out-of-memory, `exit` or `SIGKILL` reports nothing), +or its handler outlived `retryAfter`. The take-over raises `attempts` by one, in the +column and in the envelope in `payload`, in the same `UPDATE` that takes the row, so +only one of several workers racing for it counts it, and the worker dead-letters the +message when the count reaches `maxAttempts` (see +[Retries & Dead-Letters](Retries-and-Dead-Letters.md#a-handler-that-kills-its-process)). +`release()` clears the stamp, so a message that waits for another handler's +in-flight key is never counted. Nothing changes in the schema, and a row left by +version 2.3 is counted the first time a newer worker takes it over. + If you also enable the dispatcher's [deduplication](Idempotent-Consumption.md), a redelivery that arrives while another handler's claim is still held (a dead worker's, or a handler that outlived `retryAfter`) is put back on the queue and @@ -127,6 +141,8 @@ not overwrite the new holder's reservation, but its failure still counts. `maxAttempts` and `jobs_failed`, as before. The holder's own outcome then completes the job; this can take until its handler ends, so such a message is dead-lettered later than a worker that cleared the other's reservation would have. + The take-over already counted one attempt (above), so when the stored count already + equals the one the late worker reports, only the back-off is recorded. A message put back **unchanged** (waiting for another handler) only reschedules the row, only while the reservation is still its own, and never shortens a back-off diff --git a/docs/Transport-RabbitMQ.md b/docs/Transport-RabbitMQ.md index 2a50379..1a69725 100644 --- a/docs/Transport-RabbitMQ.md +++ b/docs/Transport-RabbitMQ.md @@ -55,6 +55,25 @@ auto_delete=false`); the body is the canonical envelope JSON. | `release()` | **Republish** the updated envelope, wait for the broker's confirm if the channel is in confirm mode, then `basic_ack` the original. | | `deadLetter()` | Publish the annotated envelope to `.failed`, wait for the confirm likewise, then `basic_ack` the original. | +### A delivery that was never acked + +A message the broker delivers again because its first delivery was never acked (the +worker died inside the handler, or the channel closed) arrives with the AMQP +`redelivered` flag. The transport counts that unfinished delivery as one attempt: it +hands the worker the body with `attempts` raised by one, and the worker dead-letters +the message when that reaches `maxAttempts`. A retry, a release and a dead-letter +publish a **new** message, so only a genuinely unfinished delivery carries the flag. + +RabbitMQ keeps no delivery count on a classic queue (`x-delivery-count` exists on +quorum queues only, which this transport's queue declaration does not create), and +the body of an unacked message cannot be rewritten in place. The raised count is +therefore not stored: if the handler kills its process again, the redelivered body +still has the old `attempts` and is counted once more as `+1`, not `+2`. **A handler +that kills its process on every delivery is not bounded by `maxAttempts` on +RabbitMQ**; use [PDO](Transport-PDO.md) or [Redis](Transport-Redis.md) when you need +that bound, or find the message with the broker's own tools. A normal failure +stores the count, because it republishes. + ### Why retries republish RabbitMQ does not let you mutate a message body in place, and a plain diff --git a/docs/Transport-Redis.md b/docs/Transport-Redis.md index 87110c3..e9099c8 100644 --- a/docs/Transport-Redis.md +++ b/docs/Transport-Redis.md @@ -19,6 +19,7 @@ $transport = new RedisTransport( processingSuffix: ':processing', failedSuffix: ':failed', delayedSuffix: ':delayed', + startedSuffix: ':started', ); ``` @@ -32,6 +33,7 @@ For a queue named `orders`: | `orders:processing` | list | In-flight messages reserved by a worker. | | `orders:delayed` | sorted set | Messages waiting out a back-off delay, scored by their due Unix time. | | `orders:failed` | list | Dead-lettered messages. | +| `orders:started` | sorted set | The SHA-1 of every body a worker has taken and not yet finished, scored by the Unix time it was taken. Used to count a delivery whose handler died (see below). | ## How it works @@ -47,7 +49,36 @@ observe a stop signal instead of blocking forever on an empty queue. ### Ack -`ack()` removes the in-flight copy with `LREM orders:processing 1 `. +`ack()` removes the in-flight copy with `LREM orders:processing 1 ` and +its `orders:started` entry. + +### Counting a delivery that never finished + +A handler that kills its process (out of memory, `exit`, `SIGKILL`) never reports a +failure, and the receipt is the message body itself, so the body cannot say that it +was started. `reserve()` therefore does `ZADD orders:started `; +`ack()`, `release()` and `deadLetter()` remove that member. When `ZADD` finds the +member already there, the same body was started before and never finished (your +reaper moved it back from `orders:processing`): that delivery is counted by one +script that replaces the processing entry with the body whose `attempts` is raised by +one, and the worker dead-letters the message once the count reaches `maxAttempts` +(see [Retries & Dead-Letters](Retries-and-Dead-Letters.md#a-handler-that-kills-its-process)). +The count lives in the body, so it survives the next crash and your reaper, which +only has to move `orders:processing` entries back unchanged. The body format is not +touched; a worker on an older version takes no part and its finished messages leave a +member that is pruned after a week. + +Two limits follow. Two messages with the same body count as one; a producer from this +library mints a unique `meta.id` for every message, so only a producer that does not +can hit this. And a worker that dies between `BLMOVE` and the `ZADD` leaves no member, +so that one delivery is not counted. A client without the commands this uses +(`zadd`, `zrem`, `zremrangebyscore`, `linsert`; see +[phpredis](#using-phpredis-instead)), or a Redis user the ACL refuses them (`NOPERM`), +is not an error: the counting is switched off the first time a command is refused +and `reserve()` hands the message out as it did in 2.3. Counting never fails a +reservation, because the message is already on `orders:processing` by then. If your +ACL is the 2.3 list (`+blmove +rpush +lrem +zadd +zrangebyscore +zrem`), add +`+zremrangebyscore +linsert` (and `+eval` for the scripts) to get the counting. ### Retry with delay @@ -93,7 +124,8 @@ the reaper is faster than the handler. Two things are worth knowing when you wri the reaper: - **Keep its delay above your slowest handler.** Moving a message back while its - handler is still running makes a second worker run it concurrently. + handler is still running makes a second worker run it concurrently, and counts + that delivery as an attempt. - **If it rewrites the envelope** (to add `attempts`, say), the late worker's retry can no longer find the copy by its old body and is ignored; the reaper's own increment is then the only count. Moving the body back unchanged lets both @@ -130,7 +162,9 @@ The consume side is written against `Predis\ClientInterface`. If you use the - install `predis/predis` (pure PHP, no extension needed — the supported path), or - wrap phpredis in a thin adapter exposing the same `blmove` / `rpush` / `lrem` / - `zadd` / `zrangebyscore` / `zrem` methods. `eval` is optional: leave it out (let + `zadd` / `zrangebyscore` / `zrem` methods (plus `zremrangebyscore` and `linsert` + for the [delivery count](#counting-a-delivery-that-never-finished); without them the + count is switched off). `eval` is optional: leave it out (let the call throw `BadMethodCallException`) and the transport uses the [command-by-command path](#two-paths-two-guarantees). If the adapter does provide `eval`, it must accept Predis's argument order, `eval($script, $numKeys, ...$keysAndArgs)` diff --git a/src/Consumer/Dispatcher.php b/src/Consumer/Dispatcher.php index 2474ffa..c21a601 100644 --- a/src/Consumer/Dispatcher.php +++ b/src/Consumer/Dispatcher.php @@ -10,8 +10,10 @@ use InitPHP\Queue\Contracts\CompletionAwareIdempotencyStore; use InitPHP\Queue\Contracts\Handler; use InitPHP\Queue\Contracts\HandlerResolver; +use InitPHP\Queue\Contracts\OwnershipAwareIdempotencyStore; use InitPHP\Queue\Exceptions\ConfigurationException; use InitPHP\Queue\Message\ReceivedMessage; +use RuntimeException; use Throwable; /** @@ -31,7 +33,9 @@ * whose key is only claimed by a handler that has not finished is not dropped * (when the store is a {@see CompletionAwareIdempotencyStore}): it is put back * on the queue, so the message survives that handler failing or its worker - * dying. With no options (the default) the dispatcher behaves exactly as before. + * dying. A store that is an {@see OwnershipAwareIdempotencyStore} also releases a + * failed handler's claim only if the handler still owns it. With no options (the + * default) the dispatcher behaves exactly as before. */ final class Dispatcher { @@ -59,8 +63,15 @@ public function __construct( /** * Decide what should happen to `$message`. + * + * @param bool $exhausted True when unfinished deliveries of this message (its + * handler's process died, as counted by the transport) brought `attempts` + * up to the worker's `maxAttempts`: the handler is then not run again. With + * deduplication on, a key recorded as processed still drops the message and + * a key another handler holds still releases it; otherwise it is + * dead-lettered as `failed`. */ - public function dispatch(ReceivedMessage $message): Outcome + public function dispatch(ReceivedMessage $message, bool $exhausted = false): Outcome { $reason = EnvelopeValidator::check($message->envelope()); if ($reason !== null) { @@ -74,7 +85,41 @@ public function dispatch(ReceivedMessage $message): Outcome return $this->onUnknownUrn($message); } - return $this->runHandler($handler, $message); + return $exhausted ? $this->onExhausted($message) : $this->runHandler($handler, $message); + } + + /** + * A message that is out of attempts because deliveries of it never finished. + * Before it is quarantined the idempotency record decides, without claiming + * anything: a recorded key means the handler finished (only its ack was lost), so + * the message is dropped as a duplicate; a key that is still claimed means another + * handler is running or a dead one's lease has not lapsed, so the message waits. + * It comes back still out of attempts, and is quarantined once the claim is gone. + * A store that cannot tell a recorded key from a claimed one cannot say whether the + * handler finished, so the message is quarantined rather than discarded. + */ + private function onExhausted(ReceivedMessage $message): Outcome + { + $idempotency = $this->idempotency; + $key = $idempotency?->keyFor($message); + + if ($idempotency !== null && $key !== null) { + $store = $idempotency->store; + + if ($store instanceof CompletionAwareIdempotencyStore) { + if ($store->isCompleted($key)) { + return Outcome::drop('duplicate'); + } + if ($store->seen($key)) { + return Outcome::release('in_flight', $idempotency->inFlightDelaySeconds); + } + } + } + + return Outcome::deadLetter('failed', new RuntimeException(sprintf( + 'The handler never finished %d time(s): its worker died or its reservation lapsed.', + $message->attempts(), + ))); } /** @@ -90,17 +135,38 @@ private function runHandler(Handler $handler, ReceivedMessage $message): Outcome $idempotency = $this->idempotency; $key = $idempotency?->keyFor($message); - if ($idempotency !== null && $key !== null && ! $idempotency->store->claim($key, $idempotency->leaseSeconds)) { - return $this->onClaimLost($idempotency, $key); + $token = null; + + if ($idempotency !== null && $key !== null) { + $store = $idempotency->store; + + if ($store instanceof OwnershipAwareIdempotencyStore) { + $token = $store->claimOwned($key, $idempotency->leaseSeconds); + $claimed = $token !== null; + } else { + $claimed = $store->claim($key, $idempotency->leaseSeconds); + } + + if (! $claimed) { + return $this->onClaimLost($idempotency, $key); + } } try { $handler->handle($message); } catch (Throwable $e) { // Release the in-flight claim so the redelivery can re-run; leaving - // it set would suppress a legitimate retry. + // it set would suppress a legitimate retry. With an owner token only + // our own claim is released: a handler that outlived its lease must not + // delete the claim (or the completed record) of the worker that took over. if ($idempotency !== null && $key !== null) { - $idempotency->store->forget($key); + $store = $idempotency->store; + + if ($token !== null && $store instanceof OwnershipAwareIdempotencyStore) { + $store->forgetOwned($key, $token); + } else { + $store->forget($key); + } } return Outcome::retry($e, 'failed'); diff --git a/src/Consumer/InMemoryIdempotencyStore.php b/src/Consumer/InMemoryIdempotencyStore.php index 6263ca7..93a7460 100644 --- a/src/Consumer/InMemoryIdempotencyStore.php +++ b/src/Consumer/InMemoryIdempotencyStore.php @@ -5,6 +5,7 @@ namespace InitPHP\Queue\Consumer; use InitPHP\Queue\Contracts\CompletionAwareIdempotencyStore; +use InitPHP\Queue\Contracts\OwnershipAwareIdempotencyStore; /** * The bundled reference {@see \InitPHP\Queue\Contracts\IdempotencyStore}: an in-process array of seen @@ -20,14 +21,15 @@ * Expiry uses {@see hrtime()} (a monotonic clock) so it is immune to wall-clock * jumps; a null expiry means "remembered forever". */ -final class InMemoryIdempotencyStore implements CompletionAwareIdempotencyStore +final class InMemoryIdempotencyStore implements CompletionAwareIdempotencyStore, OwnershipAwareIdempotencyStore { /** * key => entry. `expiry` is nanoseconds on the monotonic clock, or null for * never; `completed` is true once the key was recorded with remember() and - * false while it is only an in-flight claim. + * false while it is only an in-flight claim; `token` identifies the claim + * (claimOwned()) and is null for a completed record or a plain claim(). * - * @var array + * @var array */ private array $entries = []; @@ -51,18 +53,23 @@ public function seen(string $key): bool public function claim(string $key, int $leaseSeconds = 0): bool { - if ($this->seen($key)) { - return false; - } + return $this->take($key, $leaseSeconds, null); + } - // Hold the claim under a short lease so a crash mid-handler frees it for - // the redelivery, rather than blocking the key forever. - $this->entries[$key] = [ - 'expiry' => $this->expiryFor($leaseSeconds > 0 ? $leaseSeconds : null), - 'completed' => false, - ]; + public function claimOwned(string $key, int $leaseSeconds = 0): ?string + { + $token = bin2hex(random_bytes(16)); - return true; + return $this->take($key, $leaseSeconds, $token) ? $token : null; + } + + public function forgetOwned(string $key, string $token): void + { + // A lapsed claim another worker took, or a completed record, carries a + // different (or no) token and stays. + if (($this->entries[$key]['token'] ?? null) === $token) { + unset($this->entries[$key]); + } } public function isCompleted(string $key): bool @@ -72,7 +79,7 @@ public function isCompleted(string $key): bool public function remember(string $key, ?int $ttl = null): void { - $this->entries[$key] = ['expiry' => $this->expiryFor($ttl), 'completed' => true]; + $this->entries[$key] = ['expiry' => $this->expiryFor($ttl), 'completed' => true, 'token' => null]; } public function forget(string $key): void @@ -80,6 +87,23 @@ public function forget(string $key): void unset($this->entries[$key]); } + private function take(string $key, int $leaseSeconds, ?string $token): bool + { + if ($this->seen($key)) { + return false; + } + + // Hold the claim under a short lease so a crash mid-handler frees it for + // the redelivery, rather than blocking the key forever. + $this->entries[$key] = [ + 'expiry' => $this->expiryFor($leaseSeconds > 0 ? $leaseSeconds : null), + 'completed' => false, + 'token' => $token, + ]; + + return true; + } + /** * Number of currently-live (unexpired) entries — for tests and diagnostics. */ diff --git a/src/Consumer/Worker.php b/src/Consumer/Worker.php index 31d326e..e09c9b5 100644 --- a/src/Consumer/Worker.php +++ b/src/Consumer/Worker.php @@ -160,7 +160,21 @@ public function processedCount(): int */ private function process(ReceivedMessage $message): bool { - $outcome = $this->dispatcher->dispatch($message); + // A message whose earlier delivery ended without an outcome has already had + // that delivery counted in `attempts` by the transport. A handler that + // kills its process (OOM, `exit`, SIGKILL) never reports a failure, so when + // that count reaches `maxAttempts` the dispatcher quarantines the message + // instead of running it again for ever (after checking the idempotency + // store: a message another handler finished, or still holds, is not failed). + // The verdict has to outlive that check: a message put back because its key is + // still claimed is no longer "abandoned" when it returns, but it is still out of + // attempts. Only the count can bring a live message to `maxAttempts` (a failure + // at that count is dead-lettered, never re-queued), so a message that arrives + // there without a `dead_letter` block is exhausted too. A replayed dead letter + // keeps its block and, as before, runs once more. + $exhausted = $message->attempts() >= $this->options->maxAttempts + && ($message->wasAbandoned() || ! array_key_exists('dead_letter', $message->envelope())); + $outcome = $this->dispatcher->dispatch($message, $exhausted); switch ($outcome->kind) { case OutcomeKind::Ack: diff --git a/src/Contracts/OwnershipAwareIdempotencyStore.php b/src/Contracts/OwnershipAwareIdempotencyStore.php new file mode 100644 index 0000000..2048798 --- /dev/null +++ b/src/Contracts/OwnershipAwareIdempotencyStore.php @@ -0,0 +1,48 @@ += PHP_INT_MAX) { + return null; + } + $envelope['attempts'] = $attempts + 1; + + try { + return EnvelopeCodec::encode($envelope); + } catch (Throwable) { + return null; + } + } +} diff --git a/src/Message/ReceivedMessage.php b/src/Message/ReceivedMessage.php index e45eec1..69bb806 100644 --- a/src/Message/ReceivedMessage.php +++ b/src/Message/ReceivedMessage.php @@ -25,12 +25,17 @@ final class ReceivedMessage implements InboundMessage * @param string $rawBody The exact JSON body as received. * @param array $envelope The decoded envelope (may be [] for a malformed body). * @param mixed $receipt Opaque ack handle understood only by the originating transport. + * @param bool $abandoned True when the transport is handing the message out again after a + * delivery that was never acknowledged, released or dead-lettered (the worker died or + * the reservation lapsed), and has already counted that delivery in the envelope's + * `attempts`. A transport that cannot tell leaves it false. */ public function __construct( private readonly string $queue, private readonly string $rawBody, private readonly array $envelope, private readonly mixed $receipt, + private readonly bool $abandoned = false, ) {} /** @@ -114,6 +119,16 @@ public function attempts(): int return is_int($attempts) ? $attempts : 0; } + /** + * Whether a previous delivery of this message ended without an outcome (the + * worker died mid-handler or its reservation lapsed) and the transport counted + * it in {@see attempts()}. + */ + public function wasAbandoned(): bool + { + return $this->abandoned; + } + /** * The opaque transport ack handle. Only the originating transport may * interpret it. diff --git a/src/Transport/Amqp/AmqpTransport.php b/src/Transport/Amqp/AmqpTransport.php index 0d854d7..41ce9a5 100644 --- a/src/Transport/Amqp/AmqpTransport.php +++ b/src/Transport/Amqp/AmqpTransport.php @@ -9,6 +9,7 @@ use BabelQueue\Transport\AmqpTransport as BabelAmqpTransport; use InitPHP\Queue\Contracts\ConsumerTransport; use InitPHP\Queue\Exceptions\QueueException; +use InitPHP\Queue\Message\AbandonedDelivery; use InitPHP\Queue\Message\ReceivedMessage; use PhpAmqpLib\Channel\AMQPChannel; use ReflectionException; @@ -24,6 +25,13 @@ * can route and trace without decoding the body. Consuming pulls one message at a * time with `basic_get`; `ack` is `basic_ack` on the delivery tag. * + * A message the broker delivers again because its first delivery was never acked + * (a worker that died mid-handler) is counted as one failed attempt. RabbitMQ keeps + * no delivery count on a classic queue, only a redelivered flag, and the body of the + * unacked message cannot be rewritten in place, so the count is not carried across + * further crashes: a handler that kills its process on every delivery is counted + * once, not once per crash. See docs/Transport-RabbitMQ.md. + * * Because RabbitMQ does not version a message body in place, a retry/dead-letter * republishes the updated envelope (so `attempts` and the `dead_letter` block * persist) and only then acks the original delivery. That order is deliberate: a @@ -72,7 +80,14 @@ public function reserve(string $queue, float $timeout = 5.0): ?ReceivedMessage $raw = $message->getBody(); - return new ReceivedMessage($queue, $raw, EnvelopeCodec::decode($raw), $message->getDeliveryTag()); + // The broker marks a message it delivers again after the first delivery was + // never acked (the consumer died, or the channel closed mid-handler). That + // delivery counts as an attempt. A retry, release or dead-letter publishes a + // new message, so only a genuinely unfinished delivery carries the flag. + $counted = $message->isRedelivered() === true ? AbandonedDelivery::countedBody($raw) : null; + $body = $counted ?? $raw; + + return new ReceivedMessage($queue, $body, EnvelopeCodec::decode($body), $message->getDeliveryTag(), $counted !== null); } public function ack(ReceivedMessage $message): void diff --git a/src/Transport/Pdo/PdoTransport.php b/src/Transport/Pdo/PdoTransport.php index 3529cdd..f85e29f 100644 --- a/src/Transport/Pdo/PdoTransport.php +++ b/src/Transport/Pdo/PdoTransport.php @@ -8,6 +8,7 @@ use BabelQueue\Contracts\Transport; use InitPHP\Queue\Contracts\ConsumerTransport; use InitPHP\Queue\Exceptions\ConfigurationException; +use InitPHP\Queue\Message\AbandonedDelivery; use InitPHP\Queue\Message\ReceivedMessage; use PDO; @@ -22,7 +23,12 @@ * count confirms the claim — so two workers never run the same job, and it works * identically on MySQL and SQLite without `SELECT … FOR UPDATE SKIP LOCKED`. A * reservation older than `$retryAfter` seconds is treated as abandoned and - * becomes reservable again, so a crashed worker never loses a message. + * becomes reservable again, so a crashed worker never loses a message. Taking + * over such a lapsed reservation counts as one failed attempt: `attempts` (and the + * envelope in `payload`) are raised by one in the same `UPDATE`, so a handler that + * kills its process every time still reaches `maxAttempts` and the dead-letter + * table. A message put back with `release()` has its reservation cleared and is + * not counted, so waiting for another handler's in-flight key costs no attempt. * * `release()` is conditional on the reservation this transport instance took. A * worker whose reservation lapsed and was taken over cannot overwrite the new @@ -99,13 +105,10 @@ public function reserve(string $queue, float $timeout = 5.0): ?ReceivedMessage $stale = $this->at(-$this->retryAfter); $select = $this->pdo->prepare( - "SELECT id, payload FROM {$this->table}" + "SELECT id, payload, reserved_at FROM {$this->table}" . ' WHERE queue = :queue AND available_at <= :now AND (reserved_at IS NULL OR reserved_at <= :stale)' . ' ORDER BY id ASC LIMIT 1', ); - $claim = $this->pdo->prepare( - "UPDATE {$this->table} SET reserved_at = :reserved WHERE id = :id AND (reserved_at IS NULL OR reserved_at <= :stale)", - ); // Re-select on a lost claim: another worker took this row, so try the next. for ($attempt = 0; $attempt < 16; ++$attempt) { @@ -115,18 +118,67 @@ public function reserve(string $queue, float $timeout = 5.0): ?ReceivedMessage return null; } - $claim->execute([':reserved' => $now, ':id' => $row['id'], ':stale' => $stale]); - if ($claim->rowCount() === 1) { - $this->reservations[(int) $row['id']] = $now; - $payload = (string) $row['payload']; + $id = (int) $row['id']; + $payload = (string) $row['payload']; + $previous = $row['reserved_at'] === null ? null : (string) $row['reserved_at']; + + if ($previous === null) { + $abandoned = false; + $claimed = $this->claimFree($id, $now); + } else { + // The row is still stamped as reserved but the reservation lapsed: the + // worker that held it never acked, released or dead-lettered it (it + // died, or its handler outlived `retryAfter`). That delivery counts as + // an attempt, recorded in the same UPDATE that takes the row so two + // workers cannot both count it. A message put back with release() + // clears the stamp, so waiting on an in-flight key never lands here. + $counted = AbandonedDelivery::countedBody($payload); + $abandoned = $counted !== null; + $claimed = $this->claimLapsed($id, $now, $previous, $counted); + $payload = $counted ?? $payload; + } + + if ($claimed) { + $this->reservations[$id] = $now; - return new ReceivedMessage($queue, $payload, EnvelopeCodec::decode($payload), (int) $row['id']); + return new ReceivedMessage($queue, $payload, EnvelopeCodec::decode($payload), $id, $abandoned); } } return null; } + private function claimFree(int $id, string $now): bool + { + $claim = $this->pdo->prepare( + "UPDATE {$this->table} SET reserved_at = :reserved WHERE id = :id AND reserved_at IS NULL", + ); + $claim->execute([':reserved' => $now, ':id' => $id]); + + return $claim->rowCount() === 1; + } + + /** + * Take a row whose reservation lapsed. The `WHERE` matches the exact stamp that + * was read, so only one of several workers racing for the row succeeds. + */ + private function claimLapsed(int $id, string $now, string $previous, ?string $payload): bool + { + $assign = $payload !== null ? ', attempts = :attempts, payload = :payload' : ''; + $params = [':reserved' => $now, ':id' => $id, ':previous' => $previous]; + if ($payload !== null) { + $params[':attempts'] = $this->attemptsOf(EnvelopeCodec::decode($payload)); + $params[':payload'] = $payload; + } + + $claim = $this->pdo->prepare( + "UPDATE {$this->table} SET reserved_at = :reserved{$assign} WHERE id = :id AND reserved_at = :previous", + ); + $claim->execute($params); + + return $claim->rowCount() === 1; + } + public function ack(ReceivedMessage $message): void { unset($this->reservations[(int) $message->receipt()]); @@ -190,14 +242,21 @@ public function release(ReceivedMessage $message, string $payload, int $delaySec // over). The failure still counts: record the attempt and its back-off // without touching the holder's reservation, so a handler that always runs // longer than `retryAfter` still reaches `maxAttempts` and the dead-letter - // table, as it did before. A delay is only ever extended, never shortened. + // table, as it did before. Taking the row over already counted one attempt + // (see reserve()), so the stored count may equal ours: it then stays, and + // only the back-off is applied. A delay is only ever extended, never + // shortened, and `attempts` never goes back. $this->pdo->prepare( - "UPDATE {$this->table} SET payload = :payload, attempts = :attempts," + "UPDATE {$this->table} SET" + . ' payload = CASE WHEN attempts < :attempts_a THEN :payload ELSE payload END,' + . ' attempts = CASE WHEN attempts < :attempts_b THEN :attempts_c ELSE attempts END,' . ' available_at = CASE WHEN available_at > :available_a THEN available_at ELSE :available_b END' - . ' WHERE id = :id AND attempts < :attempts_guard', + . ' WHERE id = :id AND attempts <= :attempts_guard', )->execute([ + ':attempts_a' => $attempts, + ':attempts_b' => $attempts, + ':attempts_c' => $attempts, ':payload' => $payload, - ':attempts' => $attempts, ':available_a' => $availableAt, ':available_b' => $availableAt, ':id' => $id, diff --git a/src/Transport/Redis/RedisTransport.php b/src/Transport/Redis/RedisTransport.php index ac90259..ec175e8 100644 --- a/src/Transport/Redis/RedisTransport.php +++ b/src/Transport/Redis/RedisTransport.php @@ -10,6 +10,7 @@ use BadMethodCallException; use Error; use InitPHP\Queue\Contracts\ConsumerTransport; +use InitPHP\Queue\Message\AbandonedDelivery; use InitPHP\Queue\Message\ReceivedMessage; use Predis\ClientInterface; use Predis\Response\ServerException; @@ -42,15 +43,29 @@ * transport falls back to issuing the same steps as separate commands, with the * same ownership rules but without atomicity. * + * A handler that kills its process (OOM, `exit`, SIGKILL) never reports a failure, + * and the receipt is the message body itself, so the body cannot carry the fact + * that it was started. `reserve()` therefore records each delivery in a + * `:started` sorted set keyed by the SHA-1 of the body, and `ack()`, + * `release()` and `deadLetter()` remove it. A body that comes back to `reserve()` + * with its entry still present was started and never finished (your reaper moved + * it from `:processing` back to the queue): that delivery is counted by + * raising `attempts` in the body, in the processing entry too, so the count survives + * the next crash and `maxAttempts` ends the message. Nothing about the body format + * changes and a worker on an older version simply does not take part; entries + * older than a week are pruned. A client that lacks the sorted-set commands this + * uses is not an error: the tracking is switched off and `reserve()` behaves as before. + * * Requires Redis 6.2+ (for `BLMOVE`; Lua scripting is built in). Optional * dependency: `predis/predis`. */ final class RedisTransport implements Transport, ConsumerTransport { /** - * KEYS: processing, queue, delayed. ARGV: receipt, payload, due time (0 = now). - * Takes the worker's own processing entry, or else the live copy (parked in - * the delayed set, or on the queue), and puts the new payload in its place. + * KEYS: processing, queue, delayed, started. ARGV: receipt, payload, due time + * (0 = now), started-set member. Takes the worker's own processing entry, or + * else the live copy (parked in the delayed set, or on the queue), and puts the + * new payload in its place; the delivery is no longer started. */ private const RELEASE_SCRIPT = <<<'LUA' -- queue:release @@ -59,6 +74,7 @@ final class RedisTransport implements Transport, ConsumerTransport return 0 end end + redis.call('ZREM', KEYS[4], ARGV[4]) if tonumber(ARGV[3]) > 0 then redis.call('ZADD', KEYS[3], ARGV[3], ARGV[2]) else @@ -68,7 +84,8 @@ final class RedisTransport implements Transport, ConsumerTransport LUA; /** - * KEYS: processing, failed, delayed, queue. ARGV: receipt, payload. + * KEYS: processing, failed, delayed, queue, started. ARGV: receipt, payload, + * started-set member. */ private const DEAD_LETTER_SCRIPT = <<<'LUA' -- queue:dead-letter @@ -77,10 +94,27 @@ final class RedisTransport implements Transport, ConsumerTransport return 0 end end + redis.call('ZREM', KEYS[5], ARGV[3]) redis.call('RPUSH', KEYS[2], ARGV[2]) return 1 LUA; + /** + * KEYS: processing, started. ARGV: old body, new body, old member, new member, + * now. Swaps the processing entry for the body with the counted attempt and moves + * the started-set entry with it. Returns 0 when the entry is no longer there. + */ + private const COUNT_SCRIPT = <<<'LUA' + -- queue:count-abandoned + if redis.call('LINSERT', KEYS[1], 'AFTER', ARGV[1], ARGV[2]) <= 0 then + return 0 + end + redis.call('LREM', KEYS[1], 1, ARGV[1]) + redis.call('ZREM', KEYS[2], ARGV[3]) + redis.call('ZADD', KEYS[2], ARGV[5], ARGV[4]) + return 1 + LUA; + /** * KEYS: delayed, queue. ARGV: now. Moves due members, each removed and * pushed in the same step, so none can be lost or duplicated. @@ -95,17 +129,29 @@ final class RedisTransport implements Transport, ConsumerTransport return #due LUA; + /** Seconds a started-set entry is kept before it is pruned (nobody reaped the message by then). */ + private const STARTED_TTL = 604800; + + /** The started set is pruned once per this many reservations. */ + private const PRUNE_EVERY = 100; + private readonly BabelRedisTransport $publisher; /** Whether the client can EVAL; cleared the first time it proves it cannot. */ private bool $scripting = true; + /** Whether the client has the sorted-set commands delivery tracking needs; cleared when it proves it has not. */ + private bool $tracking = true; + + private int $reservations = 0; + public function __construct( private readonly ClientInterface $client, private readonly string $defaultQueue = 'default', private readonly string $processingSuffix = ':processing', private readonly string $failedSuffix = ':failed', private readonly string $delayedSuffix = ':delayed', + private readonly string $startedSuffix = ':started', ) { $this->publisher = new BabelRedisTransport($client, $defaultQueue); } @@ -133,14 +179,15 @@ public function reserve(string $queue, float $timeout = 5.0): ?ReceivedMessage return null; } - $raw = (string) $reserved; + [$raw, $abandoned] = $this->markStarted($queue, (string) $reserved); - return new ReceivedMessage($queue, $raw, EnvelopeCodec::decode($raw), $raw); + return new ReceivedMessage($queue, $raw, EnvelopeCodec::decode($raw), $raw, $abandoned); } public function ack(ReceivedMessage $message): void { $this->client->lrem($message->queue() . $this->processingSuffix, 1, (string) $message->receipt()); + $this->clearStarted($message); } public function release(ReceivedMessage $message, string $payload, int $delaySeconds = 0): void @@ -151,7 +198,8 @@ public function release(ReceivedMessage $message, string $payload, int $delaySec $receipt = (string) $message->receipt(); $due = $delaySeconds > 0 ? time() + $delaySeconds : 0; - if ($this->evaluate(self::RELEASE_SCRIPT, [$processing, $queue, $delayed], [$receipt, $payload, (string) $due])) { + $args = [$receipt, $payload, (string) $due, sha1($receipt)]; + if ($this->evaluate(self::RELEASE_SCRIPT, [$processing, $queue, $delayed, $queue . $this->startedSuffix], $args) !== null) { return; } @@ -159,6 +207,7 @@ public function release(ReceivedMessage $message, string $payload, int $delaySec if (! $this->takeOwnership($processing, $delayed, $queue, $receipt)) { return; } + $this->clearStarted($message); if ($due > 0) { $this->client->zadd($delayed, [$payload => $due]); @@ -177,49 +226,147 @@ public function deadLetter(ReceivedMessage $message, string $payload): void $delayed = $queue . $this->delayedSuffix; $receipt = (string) $message->receipt(); - if ($this->evaluate(self::DEAD_LETTER_SCRIPT, [$processing, $failed, $delayed, $queue], [$receipt, $payload])) { + $keys = [$processing, $failed, $delayed, $queue, $queue . $this->startedSuffix]; + if ($this->evaluate(self::DEAD_LETTER_SCRIPT, $keys, [$receipt, $payload, sha1($receipt)]) !== null) { return; } if ($this->takeOwnership($processing, $delayed, $queue, $receipt)) { + $this->clearStarted($message); $this->client->rpush($failed, [$payload]); } } /** - * Run one of the scripts. Returns false (without having done anything) when the - * client cannot evaluate scripts, so the caller can take the command-by-command - * path; any other failure, such as a lost connection, is rethrown. + * Record that the delivery just taken is being started and, when the same body + * was already recorded as started and never finished, count that earlier + * delivery: the body (and its processing entry) is replaced by one with + * `attempts` raised by one. Returns the body to hand out and whether it was + * counted. A failure here must not stop consumption, so a client without the + * commands only turns the tracking off. + * + * @return array{0: string, 1: bool} + */ + private function markStarted(string $queue, string $raw): array + { + if (! $this->tracking) { + return [$raw, false]; + } + + $started = $queue . $this->startedSuffix; + $now = time(); + + try { + if (++$this->reservations % self::PRUNE_EVERY === 1) { + $this->client->zremrangebyscore($started, '-inf', (string) ($now - self::STARTED_TTL)); + } + + // ZADD answers 1 for a new member, 0 for one that was there: a body + // started before and never finished. + $unfinished = (int) $this->client->zadd($started, [sha1($raw) => $now]) === 0; + if (! $unfinished) { + return [$raw, false]; + } + + $counted = AbandonedDelivery::countedBody($raw); + if ($counted === null) { + return [$raw, false]; + } + + return $this->swapProcessingEntry($queue, $raw, $counted, $now) ? [$counted, true] : [$raw, false]; + } catch (Throwable $e) { + // The message is already on the processing list: failing here would + // strand it there. Counting is best effort, so hand the message out as it + // is. A client or Redis user that lacks one of the commands (NOPERM, no + // such method) turns the counting off, as 2.3 never needed them. + if ($this->isCommandUnavailable($e)) { + $this->tracking = false; + } + + return [$raw, false]; + } + } + + /** + * Replace the worker's processing entry `$raw` with `$counted` and move the + * started-set entry with it, so the count survives the next crash. False when the + * entry is gone (a reaper moved it back in the meantime). + */ + private function swapProcessingEntry(string $queue, string $raw, string $counted, int $now): bool + { + $processing = $queue . $this->processingSuffix; + $started = $queue . $this->startedSuffix; + $args = [$raw, $counted, sha1($raw), sha1($counted), (string) $now]; + + $swapped = $this->evaluate(self::COUNT_SCRIPT, [$processing, $started], $args); + if ($swapped !== null) { + return $swapped === 1; + } + + if ((int) $this->client->linsert($processing, 'AFTER', $raw, $counted) <= 0) { + return false; + } + $this->client->lrem($processing, 1, $raw); + $this->client->zrem($started, sha1($raw)); + $this->client->zadd($started, [sha1($counted) => $now]); + + return true; + } + + /** + * Forget the started-set entry of a delivery that has an outcome. Best effort: an + * entry that stays is pruned after a week and costs nothing else. + */ + private function clearStarted(ReceivedMessage $message): void + { + if (! $this->tracking) { + return; + } + + try { + $this->client->zrem($message->queue() . $this->startedSuffix, sha1((string) $message->receipt())); + } catch (Throwable $e) { + // The message already has its outcome; a leftover entry is only pruned later. + if ($this->isCommandUnavailable($e)) { + $this->tracking = false; + } + } + } + + /** + * Run one of the scripts and return its integer result. Returns null (without + * having done anything) when the client cannot evaluate scripts, so the caller + * can take the command-by-command path; any other failure, such as a lost + * connection, is rethrown. * * @param list $keys * @param list $args */ - private function evaluate(string $script, array $keys, array $args): bool + private function evaluate(string $script, array $keys, array $args): ?int { if (! $this->scripting) { - return false; + return null; } try { - $this->client->eval($script, count($keys), ...$keys, ...$args); - - return true; + return (int) $this->client->eval($script, count($keys), ...$keys, ...$args); } catch (Throwable $e) { - if (! $this->isScriptingUnavailable($e)) { + if (! $this->isCommandUnavailable($e)) { throw $e; } $this->scripting = false; - return false; + return null; } } /** - * Whether `$e` means "this client cannot EVAL" (no such method, a different - * signature, or a server that refuses the command) rather than a real failure. + * Whether `$e` means "this client cannot run that command" (no such method, a + * different signature, or a server that refuses it: `NOPERM`, unknown command) + * rather than a real failure. */ - private function isScriptingUnavailable(Throwable $e): bool + private function isCommandUnavailable(Throwable $e): bool { if ($e instanceof BadMethodCallException || $e instanceof Error) { return true; @@ -255,7 +402,7 @@ private function migrateDueDelayed(string $queue): void { $delayed = $queue . $this->delayedSuffix; - if ($this->evaluate(self::MIGRATE_SCRIPT, [$delayed, $queue], [(string) time()])) { + if ($this->evaluate(self::MIGRATE_SCRIPT, [$delayed, $queue], [(string) time()]) !== null) { return; } diff --git a/tests/Consumer/AbandonedDeliveryTest.php b/tests/Consumer/AbandonedDeliveryTest.php new file mode 100644 index 0000000..5d106a7 --- /dev/null +++ b/tests/Consumer/AbandonedDeliveryTest.php @@ -0,0 +1,603 @@ + 1], 'orders'); + $envelope['meta']['id'] = 'msg-1'; + $envelope['attempts'] = $attempts; + + return EnvelopeCodec::encode($envelope); + } + + private function pdo(): PDO + { + $pdo = new PDO('sqlite::memory:'); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + + return $pdo; + } + + private function rows(PDO $pdo, string $table): int + { + return (int) $pdo->query("SELECT COUNT(*) FROM {$table}")->fetchColumn(); + } + + public function test_pdo_a_message_whose_handler_keeps_dying_reaches_the_dead_letter_table(): void + { + $pdo = $this->pdo(); + $inner = new PdoTransport($pdo, 'jobs', null, 'default', 0); // retryAfter 0: a lapsed reservation is at once reclaimable + $inner->createSchema(); + $inner->publish($this->payload(), 'orders'); + + $transport = new OutcomeDroppingTransport($inner); + $handler = new RecordingHandler(); + $worker = new Worker( + $transport, + new Dispatcher((new HandlerMap())->register(self::URN, $handler)), + new WorkerOptions(maxAttempts: 3, sleepWhenEmpty: 0.0), + ); + + // Delivery 1 and the two after it: the handler runs, then the process dies. + foreach ([0, 1, 2] as $expectedAttempts) { + self::assertTrue($worker->runOnce('orders')); + self::assertSame($expectedAttempts, (int) $pdo->query('SELECT attempts FROM jobs')->fetchColumn()); + self::assertSame($expectedAttempts, EnvelopeCodec::decode((string) $pdo->query('SELECT payload FROM jobs')->fetchColumn())['attempts']); + } + self::assertCount(3, $handler->handled); + + // The reaper-equivalent hands it out a fourth time: three deliveries were lost. + $transport->dropOutcomes = false; + self::assertTrue($worker->runOnce('orders')); + + self::assertCount(3, $handler->handled, 'the handler is not run again'); + self::assertSame(0, $this->rows($pdo, 'jobs')); + $failed = $pdo->query('SELECT attempts, reason FROM jobs_failed')->fetchAll(PDO::FETCH_ASSOC); + self::assertCount(1, $failed); + self::assertSame(3, (int) $failed[0]['attempts']); + self::assertSame('failed', $failed[0]['reason']); + } + + public function test_pdo_the_counted_attempt_is_persisted_when_the_row_is_taken_over(): void + { + $pdo = $this->pdo(); + $transport = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $transport->createSchema(); + $transport->publish($this->payload(), 'orders'); + + $first = $transport->reserve('orders'); + self::assertNotNull($first); + self::assertFalse($first->wasAbandoned()); + self::assertSame(0, $first->attempts()); + + $second = $transport->reserve('orders'); // the first delivery never finished + self::assertNotNull($second); + self::assertTrue($second->wasAbandoned()); + self::assertSame(1, $second->attempts()); + self::assertSame(1, (int) $pdo->query('SELECT attempts FROM jobs')->fetchColumn(), 'stored with the take-over'); + self::assertSame(1, EnvelopeCodec::decode((string) $pdo->query('SELECT payload FROM jobs')->fetchColumn())['attempts']); + } + + public function test_pdo_a_failure_after_a_counted_delivery_counts_once_more_and_not_twice(): void + { + $pdo = $this->pdo(); + $transport = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $transport->createSchema(); + $transport->publish($this->payload(), 'orders'); + $transport->reserve('orders'); // lost + + $throwing = new class implements \InitPHP\Queue\Contracts\Handler { + public function handle(\BabelQueue\Contracts\InboundMessage $message): void + { + throw new \RuntimeException('boom'); + } + }; + $worker = new Worker( + $transport, + new Dispatcher((new HandlerMap())->register(self::URN, $throwing)), + new WorkerOptions(maxAttempts: 5, backoff: [0], sleepWhenEmpty: 0.0), + ); + + $worker->runOnce('orders'); // the take-over counts 1, this failure makes 2 + + self::assertSame(2, (int) $pdo->query('SELECT attempts FROM jobs')->fetchColumn()); + } + + public function test_pdo_a_released_message_is_not_counted_when_it_is_taken_again(): void + { + $pdo = $this->pdo(); + $transport = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $transport->createSchema(); + $transport->publish($this->payload(), 'orders'); + + $message = $transport->reserve('orders'); + self::assertNotNull($message); + $transport->release($message, $message->rawBody(), 0); + + $again = $transport->reserve('orders'); + self::assertNotNull($again); + self::assertFalse($again->wasAbandoned()); + self::assertSame(0, $again->attempts()); + } + + public function test_pdo_waiting_on_an_in_flight_key_uses_no_attempts_however_often_it_repeats(): void + { + $pdo = $this->pdo(); + $transport = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $transport->createSchema(); + $transport->publish($this->payload(), 'orders'); + + $store = new InMemoryIdempotencyStore(); + $store->claim('bq:idemp:msg-1', 300); // another worker is inside its handler + $handler = new RecordingHandler(); + $worker = new Worker( + $transport, + new Dispatcher( + (new HandlerMap())->register(self::URN, $handler), + idempotency: new IdempotencyOptions($store, inFlightDelaySeconds: 5), + ), + new WorkerOptions(maxAttempts: 2, sleepWhenEmpty: 0.0), + ); + + for ($wait = 0; $wait < 8; ++$wait) { // well past maxAttempts + $pdo->exec("UPDATE jobs SET available_at = '2000-01-01 00:00:00'"); // the delay has passed + self::assertTrue($worker->runOnce('orders')); + } + + self::assertSame([], $handler->handled); + self::assertSame(1, $this->rows($pdo, 'jobs'), 'the message is still queued'); + self::assertSame(0, $this->rows($pdo, 'jobs_failed'), 'waiting never dead-letters it'); + self::assertSame(0, (int) $pdo->query('SELECT attempts FROM jobs')->fetchColumn()); + } + + public function test_pdo_a_lost_delivery_followed_by_waiting_counts_exactly_one_attempt(): void + { + $pdo = $this->pdo(); + $transport = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $transport->createSchema(); + $transport->publish($this->payload(), 'orders'); + $transport->reserve('orders'); // the first worker died in the handler + + $store = new InMemoryIdempotencyStore(); + $store->claim('bq:idemp:msg-1', 300); // its claim has not lapsed yet + $worker = new Worker( + $transport, + new Dispatcher( + (new HandlerMap())->register(self::URN, new RecordingHandler()), + idempotency: new IdempotencyOptions($store, inFlightDelaySeconds: 5), + ), + new WorkerOptions(maxAttempts: 3, sleepWhenEmpty: 0.0), + ); + + for ($wait = 0; $wait < 6; ++$wait) { + $pdo->exec("UPDATE jobs SET available_at = '2000-01-01 00:00:00'"); + $worker->runOnce('orders'); + } + + self::assertSame(1, (int) $pdo->query('SELECT attempts FROM jobs')->fetchColumn()); + self::assertSame(0, $this->rows($pdo, 'jobs_failed')); + } + + public function test_pdo_two_workers_racing_for_a_lapsed_row_count_it_once(): void + { + $pdo = $this->pdo(); + $a = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $a->createSchema(); + $b = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $a->publish($this->payload(), 'orders'); + $a->reserve('orders'); // lost + + // Both read the lapsed stamp; the conditional UPDATE lets only one win. + $winner = $b->reserve('orders'); + + self::assertNotNull($winner); + self::assertSame(1, (int) $pdo->query('SELECT attempts FROM jobs')->fetchColumn()); + } + + public function test_pdo_a_row_from_before_this_version_is_counted_like_any_other(): void + { + // A 2.3 worker died holding a row: reserved, attempts 1 already recorded. + $pdo = $this->pdo(); + $transport = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $transport->createSchema(); + $transport->publish($this->payload(1), 'orders'); + $pdo->exec("UPDATE jobs SET reserved_at = '2000-01-01 00:00:00'"); + + $message = $transport->reserve('orders'); + + self::assertNotNull($message); + self::assertSame(2, $message->attempts()); + self::assertTrue($message->wasAbandoned()); + } + + public function test_redis_a_message_whose_handler_keeps_dying_reaches_the_failed_list(): void + { + $redis = new InMemoryRedis(); + $inner = new RedisTransport($redis, 'default'); + $inner->publish($this->payload(), 'orders'); + + $transport = new OutcomeDroppingTransport($inner); + $handler = new RecordingHandler(); + $worker = new Worker( + $transport, + new Dispatcher((new HandlerMap())->register(self::URN, $handler)), + new WorkerOptions(maxAttempts: 3, sleepWhenEmpty: 0.0, reserveTimeout: 0.0), + ); + + foreach ([0, 1, 2] as $expectedAttempts) { + self::assertTrue($worker->runOnce('orders')); + self::assertCount(1, $redis->list('orders:processing'), 'the handler died, the entry is left'); + self::assertSame($expectedAttempts, EnvelopeCodec::decode($redis->list('orders:processing')[0])['attempts'], 'the processing entry carries the count'); + $this->reap($redis, 'orders'); + } + self::assertCount(3, $handler->handled); + + $transport->dropOutcomes = false; + self::assertTrue($worker->runOnce('orders')); + + self::assertCount(3, $handler->handled, 'the handler is not run again'); + self::assertSame([], $redis->list('orders:processing')); + self::assertSame([], $redis->list('orders')); + self::assertCount(1, $redis->list('orders:failed')); + self::assertSame(3, EnvelopeCodec::decode($redis->list('orders:failed')[0])['attempts']); + self::assertSame(0, $redis->zcard('orders:started'), 'no delivery record is left behind'); + } + + public function test_redis_a_finished_message_leaves_nothing_to_count(): void + { + $redis = new InMemoryRedis(); + $transport = new RedisTransport($redis, 'default'); + $transport->publish($this->payload(), 'orders'); + + $message = $transport->reserve('orders', 1.0); + self::assertNotNull($message); + self::assertSame(1, $redis->zcard('orders:started')); + $transport->release($message, $message->rawBody(), 0); // put back verbatim, e.g. an in-flight wait + + $again = $transport->reserve('orders', 1.0); + self::assertNotNull($again); + self::assertFalse($again->wasAbandoned()); + self::assertSame(0, $again->attempts()); + + $transport->ack($again); + self::assertSame(0, $redis->zcard('orders:started')); + } + + public function test_redis_without_eval_counts_the_same_way(): void + { + $redis = new InMemoryRedis(scripting: false); + $transport = new RedisTransport($redis, 'default'); + $transport->publish($this->payload(), 'orders'); + + $transport->reserve('orders', 1.0); + $this->reap($redis, 'orders'); + $second = $transport->reserve('orders', 1.0); + + self::assertNotNull($second); + self::assertTrue($second->wasAbandoned()); + self::assertSame(1, $second->attempts()); + self::assertSame(1, EnvelopeCodec::decode($redis->list('orders:processing')[0])['attempts']); + self::assertSame(1, $redis->zcard('orders:started')); + } + + public function test_redis_a_client_without_the_sorted_set_commands_keeps_consuming(): void + { + $client = Mockery::mock(\Predis\ClientInterface::class); + $client->shouldReceive('eval')->andReturn(0); + $client->shouldReceive('zremrangebyscore')->andThrow(new \BadMethodCallException('no zremrangebyscore')); + $client->shouldReceive('blmove')->andReturn($this->payload()); + + $message = (new RedisTransport($client, 'default'))->reserve('orders', 1.0); + + self::assertNotNull($message); + self::assertFalse($message->wasAbandoned()); + self::assertSame(0, $message->attempts()); + } + + public function test_the_worker_quarantines_an_abandoned_message_that_is_out_of_attempts(): void + { + $message = new ReceivedMessage('orders', $this->payload(3), EnvelopeCodec::decode($this->payload(3)), 'r', true); + $transport = Mockery::mock(ConsumerTransport::class); + $transport->shouldReceive('reserve')->once()->andReturn($message); + $transport->shouldReceive('deadLetter')->once()->with($message, Mockery::on( + static fn(string $payload): bool => EnvelopeCodec::decode($payload)['dead_letter']['reason'] === 'failed' + && EnvelopeCodec::decode($payload)['attempts'] === 3, + )); + $handler = new RecordingHandler(); + $worker = new Worker( + $transport, + new Dispatcher((new HandlerMap())->register(self::URN, $handler)), + new WorkerOptions(maxAttempts: 3, sleepWhenEmpty: 0.0), + ); + + self::assertTrue($worker->runOnce('orders')); + self::assertSame([], $handler->handled); + } + + public function test_a_message_out_of_attempts_is_quarantined_even_when_it_returns_no_longer_marked_abandoned(): void + { + // It was put back (for example waiting on an in-flight key) after the count reached + // maxAttempts; the transport no longer knows it was abandoned, the count still says so. + $message = new ReceivedMessage('orders', $this->payload(3), EnvelopeCodec::decode($this->payload(3)), 'r'); + $transport = Mockery::mock(ConsumerTransport::class); + $transport->shouldReceive('reserve')->once()->andReturn($message); + $transport->shouldReceive('deadLetter')->once()->with($message, Mockery::type('string')); + $handler = new RecordingHandler(); + $worker = new Worker( + $transport, + new Dispatcher((new HandlerMap())->register(self::URN, $handler)), + new WorkerOptions(maxAttempts: 3, sleepWhenEmpty: 0.0), + ); + + $worker->runOnce('orders'); + + self::assertSame([], $handler->handled); + } + + public function test_a_replayed_dead_letter_with_its_block_still_runs_once_more(): void + { + $envelope = EnvelopeCodec::decode($this->payload(3)); + $envelope['dead_letter'] = ['reason' => 'failed']; + $body = EnvelopeCodec::encode($envelope); + $message = new ReceivedMessage('orders', $body, $envelope, 'r'); + $transport = Mockery::mock(ConsumerTransport::class); + $transport->shouldReceive('reserve')->once()->andReturn($message); + $transport->shouldReceive('ack')->once()->with($message); + $handler = new RecordingHandler(); + $worker = new Worker( + $transport, + new Dispatcher((new HandlerMap())->register(self::URN, $handler)), + new WorkerOptions(maxAttempts: 3, sleepWhenEmpty: 0.0), + ); + + $worker->runOnce('orders'); + + self::assertCount(1, $handler->handled); + } + + public function test_an_abandoned_message_with_attempts_left_runs_normally(): void + { + $message = new ReceivedMessage('orders', $this->payload(2), EnvelopeCodec::decode($this->payload(2)), 'r', true); + $transport = Mockery::mock(ConsumerTransport::class); + $transport->shouldReceive('reserve')->once()->andReturn($message); + $transport->shouldReceive('ack')->once()->with($message); + $handler = new RecordingHandler(); + $worker = new Worker( + $transport, + new Dispatcher((new HandlerMap())->register(self::URN, $handler)), + new WorkerOptions(maxAttempts: 3, sleepWhenEmpty: 0.0), + ); + + $worker->runOnce('orders'); + + self::assertCount(1, $handler->handled); + } + + public function test_an_exhausted_message_whose_key_was_recorded_is_dropped_not_failed(): void + { + // The handler succeeded and remembered the key, then the worker died before the ack. + $pdo = $this->pdo(); + $inner = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $inner->createSchema(); + $inner->publish($this->payload(), 'orders'); + + $store = new InMemoryIdempotencyStore(); + $transport = new OutcomeDroppingTransport($inner); + $handler = new RecordingHandler(); + $events = []; + $worker = new Worker( + $transport, + new Dispatcher((new HandlerMap())->register(self::URN, $handler), idempotency: new IdempotencyOptions($store)), + new WorkerOptions(maxAttempts: 1, sleepWhenEmpty: 0.0), + static function (string $level, string $event, array $context) use (&$events): void { + $events[] = $event . ':' . ($context['reason'] ?? ''); + }, + ); + + $worker->runOnce('orders'); // handler runs, key recorded, ack lost + self::assertCount(1, $handler->handled); + self::assertTrue($store->isCompleted('bq:idemp:msg-1')); + + $transport->dropOutcomes = false; + $worker->runOnce('orders'); // taken over: attempts 1 >= maxAttempts 1 + + self::assertCount(1, $handler->handled, 'the handler is not run again'); + self::assertSame(0, $this->rows($pdo, 'jobs'), 'the row is acked'); + self::assertSame(0, $this->rows($pdo, 'jobs_failed'), 'a message that was handled is not failed'); + self::assertContains('job.dropped:duplicate', $events); + } + + public function test_an_exhausted_message_whose_key_is_still_claimed_waits_instead_of_failing(): void + { + $pdo = $this->pdo(); + $transport = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $transport->createSchema(); + $transport->publish($this->payload(), 'orders'); + $transport->reserve('orders'); // the first delivery is still running (or lost) + + $store = new InMemoryIdempotencyStore(); + $store->claim('bq:idemp:msg-1', 300); // its claim has not lapsed + $handler = new RecordingHandler(); + $worker = new Worker( + $transport, + new Dispatcher((new HandlerMap())->register(self::URN, $handler), idempotency: new IdempotencyOptions($store)), + new WorkerOptions(maxAttempts: 1, sleepWhenEmpty: 0.0), + ); + + $worker->runOnce('orders'); // taken over: attempts 1 >= maxAttempts 1 + + self::assertSame([], $handler->handled); + self::assertSame(1, $this->rows($pdo, 'jobs'), 'the message is put back, not lost'); + self::assertSame(0, $this->rows($pdo, 'jobs_failed'), 'and not dead-lettered while its key is held'); + } + + public function test_pdo_a_handler_that_dies_every_time_ends_in_the_dead_letter_table_even_with_a_lease_longer_than_retry_after(): void + { + // The defaults that matter: the dead worker's claim (lease 300 s) outlives the + // transport's redelivery time, so every redelivery first finds the claim held. + $pdo = $this->pdo(); + $inner = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $inner->createSchema(); + $inner->publish($this->payload(), 'orders'); + + $store = new CrashableIdempotencyStore(); + $transport = new OutcomeDroppingTransport($inner); + $handled = 0; + $handlers = (new HandlerMap())->register(self::URN, static function () use (&$handled, $store, $transport): void { + ++$handled; + $store->dead = true; // the process dies inside the handler: + $transport->dropOutcomes = true; // no remember(), no forget(), no ack + }); + $worker = new Worker( + $transport, + new Dispatcher($handlers, idempotency: new IdempotencyOptions($store, leaseSeconds: 300, inFlightDelaySeconds: 5)), + new WorkerOptions(maxAttempts: 3, sleepWhenEmpty: 0.0), + ); + + for ($turn = 0; $turn < 30 && $this->rows($pdo, 'jobs') > 0; ++$turn) { + $before = $handled; + $pdo->exec("UPDATE jobs SET available_at = '2000-01-01 00:00:00'"); // any wait has passed + $worker->runOnce('orders'); + $store->dead = false; + $transport->dropOutcomes = false; + + if ($handled === $before) { + $store->lapse('bq:idemp:msg-1'); // the delivery only waited: time passes until the lease runs out + } + } + + self::assertSame(3, $handled, 'the handler ran once per attempt and no more'); + self::assertSame(0, $this->rows($pdo, 'jobs'), 'the crash loop ended'); + $failed = $pdo->query('SELECT attempts, reason FROM jobs_failed')->fetchAll(PDO::FETCH_ASSOC); + self::assertCount(1, $failed); + self::assertSame(3, (int) $failed[0]['attempts']); + self::assertSame('failed', $failed[0]['reason']); + } + + public function test_an_exhausted_message_on_a_store_that_cannot_tell_claimed_from_recorded_is_quarantined_not_discarded(): void + { + $store = new ClaimOnlyIdempotencyStore(); + $store->claim('bq:idemp:msg-1', 300); + $dispatcher = new Dispatcher( + (new HandlerMap())->register(self::URN, new RecordingHandler()), + idempotency: new IdempotencyOptions($store), + ); + $envelope = EnvelopeCodec::decode($this->payload(3)); + + $outcome = $dispatcher->dispatch(new ReceivedMessage('orders', $this->payload(3), $envelope, 1), true); + + self::assertSame(OutcomeKind::DeadLetter, $outcome->kind); + } + + public function test_an_exhausted_message_with_no_idempotency_record_is_still_dead_lettered(): void + { + $pdo = $this->pdo(); + $transport = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $transport->createSchema(); + $transport->publish($this->payload(), 'orders'); + $transport->reserve('orders'); // lost + + $handler = new RecordingHandler(); + $worker = new Worker( + $transport, + new Dispatcher( + (new HandlerMap())->register(self::URN, $handler), + idempotency: new IdempotencyOptions(new InMemoryIdempotencyStore()), + ), + new WorkerOptions(maxAttempts: 1, sleepWhenEmpty: 0.0), + ); + + $worker->runOnce('orders'); + + self::assertSame([], $handler->handled); + self::assertSame(0, $this->rows($pdo, 'jobs')); + self::assertSame(1, $this->rows($pdo, 'jobs_failed')); + } + + public function test_redis_a_user_without_permission_for_the_counting_commands_keeps_consuming(): void + { + // A 2.3 ACL: blmove, rpush, lrem, zadd, zrangebyscore, zrem; no EVAL, no ZREMRANGEBYSCORE. + $client = Mockery::mock(\Predis\ClientInterface::class); + $client->shouldReceive('eval')->once()->andThrow(new ServerException("NOPERM this user has no permissions to run the 'eval' command")); + $client->shouldReceive('zrangebyscore')->andReturn([]); + $client->shouldReceive('blmove')->andReturn($this->payload()); + $client->shouldReceive('zremrangebyscore')->once()->andThrow(new ServerException("NOPERM this user has no permissions to run the 'zremrangebyscore' command")); + $client->shouldReceive('zadd')->never(); + + $message = (new RedisTransport($client, 'default'))->reserve('orders', 1.0); + + self::assertNotNull($message, 'the message is not stranded on the processing list'); + self::assertFalse($message->wasAbandoned()); + self::assertSame(0, $message->attempts()); + } + + public function test_redis_a_refused_swap_hands_the_message_out_uncounted_instead_of_failing(): void + { + $client = Mockery::mock(\Predis\ClientInterface::class); + $client->shouldReceive('eval')->once()->andThrow(new ServerException("NOPERM this user has no permissions to run the 'eval' command")); + $client->shouldReceive('zrangebyscore')->andReturn([]); + $client->shouldReceive('blmove')->andReturn($this->payload()); + $client->shouldReceive('zremrangebyscore')->andReturn(0); + $client->shouldReceive('zadd')->once()->andReturn(0); // the body was started before: it must be counted + $client->shouldReceive('linsert')->once()->andThrow(new ServerException("NOPERM this user has no permissions to run the 'linsert' command")); + + $transport = new RedisTransport($client, 'default'); + $message = $transport->reserve('orders', 1.0); + + self::assertNotNull($message, 'the message is not left on the processing list for good'); + self::assertFalse($message->wasAbandoned()); + self::assertSame(0, $message->attempts()); + + // The counting is off from now on: no further sorted-set commands are tried. + $client->shouldReceive('zrem')->never(); + $client->shouldReceive('lrem')->once()->andReturn(1); + self::assertNotNull($transport->reserve('orders', 1.0)); + $transport->ack($message); + } + + /** What a user's reaper does: put every processing entry back on the queue. */ + private function reap(InMemoryRedis $redis, string $queue): void + { + foreach ($redis->list($queue . ':processing') as $body) { + $redis->lrem($queue . ':processing', 1, $body); + $redis->rpush($queue, [$body]); + } + } +} diff --git a/tests/Consumer/ClaimOwnershipTest.php b/tests/Consumer/ClaimOwnershipTest.php new file mode 100644 index 0000000..c24c760 --- /dev/null +++ b/tests/Consumer/ClaimOwnershipTest.php @@ -0,0 +1,182 @@ + 1], 'orders'); + $envelope['meta']['id'] = 'msg-1'; + + return new ReceivedMessage('orders', EnvelopeCodec::encode($envelope), $envelope, 1); + } + + /** + * Worker 1 runs the handler, its lease lapses (the key is freed), worker 2 + * takes the key over inside the same handler call and finishes or not, and then + * worker 1 throws. + * + * @param callable(InboundMessage, int): void $secondWorkerHandler what worker 2's handler does + */ + private function runOverrunningFirstWorker(IdempotencyStore $store, callable $secondWorkerHandler): OutcomeKind + { + $depth = 0; + $dispatcher = null; + $message = $this->message(); + + $handlers = (new HandlerMap())->register(self::URN, function (InboundMessage $m) use (&$depth, &$dispatcher, $store, $message, $secondWorkerHandler): void { + ++$depth; + + if ($depth === 1) { + $store->forget(self::KEY); // worker 1's lease lapses + $dispatcher->dispatch($message); // worker 2 takes the redelivery + + throw new RuntimeException('worker 1 fails after its lease lapsed'); + } + + $secondWorkerHandler($m, $depth); + }); + + $dispatcher = new Dispatcher($handlers, idempotency: new IdempotencyOptions($store, leaseSeconds: 300)); + + return $dispatcher->dispatch($message)->kind; + } + + public function test_a_late_failure_keeps_the_completed_record_of_the_worker_that_took_over(): void + { + $store = new InMemoryIdempotencyStore(); + + $kind = $this->runOverrunningFirstWorker($store, static function (): void {}); // worker 2 succeeds + + self::assertSame(OutcomeKind::Retry, $kind, 'worker 1 still reports its own failure'); + self::assertTrue($store->isCompleted(self::KEY), 'worker 2 completed the message and that record stays'); + } + + public function test_a_late_failure_keeps_the_claim_of_a_worker_that_is_still_running(): void + { + $store = new InMemoryIdempotencyStore(); + + $handlers = (new HandlerMap())->register(self::URN, static function () use ($store): void { + $store->forget(self::KEY); // worker 1's lease lapses + $token = $store->claimOwned(self::KEY, 300); // worker 2 claims the key and is still inside its handler + self::assertNotNull($token); + + throw new RuntimeException('worker 1 fails after its lease lapsed'); + }); + $dispatcher = new Dispatcher($handlers, idempotency: new IdempotencyOptions($store, leaseSeconds: 300)); + + $dispatcher->dispatch($this->message()); + + self::assertTrue($store->seen(self::KEY), "worker 2's claim is not released by worker 1's failure"); + self::assertFalse($store->isCompleted(self::KEY)); + } + + public function test_a_failure_still_releases_its_own_claim(): void + { + $store = new InMemoryIdempotencyStore(); + $handlers = (new HandlerMap())->register(self::URN, static function (): void { + throw new RuntimeException('boom'); + }); + $dispatcher = new Dispatcher($handlers, idempotency: new IdempotencyOptions($store)); + + $outcome = $dispatcher->dispatch($this->message()); + + self::assertSame(OutcomeKind::Retry, $outcome->kind); + self::assertFalse($store->seen(self::KEY), 'the redelivery can run the handler again'); + } + + public function test_a_store_without_ownership_keeps_the_unconditional_forget(): void + { + // The contract of 2.1 to 2.3: forget() is called as before, so the late + // failure still clears the key. Nothing changes for such a store. + $store = new ClaimOnlyIdempotencyStore(); + + $kind = $this->runOverrunningFirstWorker($store, static function (): void {}); // worker 2 succeeds + + self::assertSame(OutcomeKind::Retry, $kind); + self::assertFalse($store->seen(self::KEY), 'the old store loses the record, exactly as it did'); + } + + public function test_a_store_without_ownership_still_runs_the_whole_lifecycle(): void + { + $store = new ClaimOnlyIdempotencyStore(); + $calls = 0; + $handlers = (new HandlerMap())->register(self::URN, function () use (&$calls): void { + ++$calls; + }); + $dispatcher = new Dispatcher($handlers, idempotency: new IdempotencyOptions($store)); + + self::assertSame(OutcomeKind::Ack, $dispatcher->dispatch($this->message())->kind); + self::assertSame(OutcomeKind::Drop, $dispatcher->dispatch($this->message())->kind, 'the duplicate is dropped'); + self::assertSame(1, $calls); + } + + public function test_the_in_memory_store_releases_only_a_claim_it_still_owns(): void + { + $store = new InMemoryIdempotencyStore(); + self::assertInstanceOf(OwnershipAwareIdempotencyStore::class, $store); + + $first = $store->claimOwned('k', 300); + self::assertNotNull($first); + self::assertNull($store->claimOwned('k', 300), 'a held key cannot be claimed again'); + + $store->forgetOwned('k', 'not-the-token'); + self::assertTrue($store->seen('k'), 'a foreign token releases nothing'); + + $store->forgetOwned('k', $first); + self::assertFalse($store->seen('k')); + + $second = $store->claimOwned('k', 300); + self::assertNotNull($second); + self::assertNotSame($first, $second, 'every claim has its own token'); + $store->forgetOwned('k', $first); + self::assertTrue($store->seen('k'), 'a stale token cannot release the newer claim'); + } + + public function test_a_completed_record_is_not_released_by_a_token(): void + { + $store = new InMemoryIdempotencyStore(); + $token = $store->claimOwned('k', 300); + self::assertNotNull($token); + $store->remember('k', 60); + + $store->forgetOwned('k', $token); + + self::assertTrue($store->isCompleted('k')); + } + + public function test_plain_claim_and_forget_keep_working_on_an_ownership_store(): void + { + $store = new InMemoryIdempotencyStore(); + + self::assertTrue($store->claim('k', 300)); + self::assertFalse($store->claim('k', 300)); + $store->forget('k'); + self::assertFalse($store->seen('k')); + } +} diff --git a/tests/Consumer/InFlightRedeliveryTest.php b/tests/Consumer/InFlightRedeliveryTest.php index c9fb41f..e862957 100644 --- a/tests/Consumer/InFlightRedeliveryTest.php +++ b/tests/Consumer/InFlightRedeliveryTest.php @@ -359,15 +359,16 @@ public function test_a_holders_unchanged_release_does_not_shorten_a_recorded_bac self::assertNotNull($lapsed); $pdo->exec("UPDATE jobs SET reserved_at = '2999-01-01 00:00:00'"); // A's stamp differs from B's + // Taking the lapsed row over counted one attempt already; B's failure is the next. $envelope = $lapsed->envelope(); - $envelope['attempts'] = 1; + $envelope['attempts'] = $lapsed->attempts() + 1; $b->release($lapsed, EnvelopeCodec::encode($envelope), 60); $pdo->exec("UPDATE jobs SET reserved_at = '" . date('Y-m-d H:i:s') . "'"); // A's reservation again $a->release($held, $held->rawBody(), 5); $row = $pdo->query('SELECT attempts, available_at FROM jobs')->fetch(PDO::FETCH_ASSOC); - self::assertSame(1, (int) $row['attempts']); + self::assertSame(2, (int) $row['attempts']); self::assertGreaterThan(time() + 30, strtotime((string) $row['available_at']), 'the 60 s back-off was not cut to 5 s'); } diff --git a/tests/Consumer/WorkerFailurePauseTest.php b/tests/Consumer/WorkerFailurePauseTest.php index 1c7eb47..078b5aa 100644 --- a/tests/Consumer/WorkerFailurePauseTest.php +++ b/tests/Consumer/WorkerFailurePauseTest.php @@ -115,6 +115,7 @@ public function test_a_rabbitmq_nack_of_the_dead_letter_republish_does_not_spin_ $delivered = Mockery::mock(AMQPMessage::class); $delivered->shouldReceive('getBody')->andReturn($body); $delivered->shouldReceive('getDeliveryTag')->andReturn(7); + $delivered->shouldReceive('isRedelivered')->andReturn(false); $channel = Mockery::mock(AMQPChannel::class); $channel->shouldReceive('queue_declare'); diff --git a/tests/Integration/AmqpIntegrationTest.php b/tests/Integration/AmqpIntegrationTest.php index 4e4ffe0..03f91b3 100644 --- a/tests/Integration/AmqpIntegrationTest.php +++ b/tests/Integration/AmqpIntegrationTest.php @@ -150,4 +150,25 @@ public function test_a_message_waiting_on_an_in_flight_key_stays_on_the_queue(): self::assertCount(1, $handler->handled); self::assertNull($this->transport->reserve(self::QUEUE, 1.0)); } + + public function test_a_delivery_that_was_never_acked_is_counted_when_the_broker_redelivers_it(): void + { + $this->transport->publish( + EnvelopeCodec::encode(EnvelopeCodec::make('urn:babel:orders:created', ['order_id' => 1], self::QUEUE)), + self::QUEUE, + ); + + $first = $this->transport->reserve(self::QUEUE, 2.0); + self::assertNotNull($first); + self::assertFalse($first->wasAbandoned()); + self::assertSame(0, $first->attempts()); + + $this->channel->basic_recover(true); // the unacked delivery goes back to the queue + + $second = $this->transport->reserve(self::QUEUE, 2.0); + self::assertNotNull($second); + self::assertTrue($second->wasAbandoned()); + self::assertSame(1, $second->attempts()); + $this->transport->ack($second); + } } diff --git a/tests/Integration/PdoMysqlIntegrationTest.php b/tests/Integration/PdoMysqlIntegrationTest.php index 127dc1e..899667f 100644 --- a/tests/Integration/PdoMysqlIntegrationTest.php +++ b/tests/Integration/PdoMysqlIntegrationTest.php @@ -71,4 +71,27 @@ public function test_full_lifecycle_against_mysql(): void self::assertSame(0, $this->rowCount(self::TABLE)); self::assertSame(1, $this->rowCount(self::TABLE . '_failed')); } + + public function test_a_lapsed_reservation_is_counted_as_an_attempt(): void + { + $transport = new PdoTransport($this->pdo, self::TABLE, null, 'default', 0); // a reservation lapses at once + $transport->publish(EnvelopeCodec::encode(EnvelopeCodec::make('urn:babel:orders:created', ['order_id' => 5], 'orders')), 'orders'); + + $first = $transport->reserve('orders'); + self::assertNotNull($first); + self::assertFalse($first->wasAbandoned()); + + $second = $transport->reserve('orders'); // the first worker never reported an outcome + self::assertNotNull($second); + self::assertTrue($second->wasAbandoned()); + self::assertSame(1, $second->attempts()); + self::assertSame(1, (int) $this->pdo->query('SELECT attempts FROM ' . self::TABLE)->fetchColumn()); + self::assertSame(1, EnvelopeCodec::decode((string) $this->pdo->query('SELECT payload FROM ' . self::TABLE)->fetchColumn())['attempts']); + + $transport->release($second, $second->rawBody(), 0); // put back verbatim, as an in-flight wait does + $third = $transport->reserve('orders'); + self::assertNotNull($third); + self::assertFalse($third->wasAbandoned(), 'a released message is not counted'); + self::assertSame(1, $third->attempts()); + } } diff --git a/tests/Integration/RedisIntegrationTest.php b/tests/Integration/RedisIntegrationTest.php index e16c2a5..29b8247 100644 --- a/tests/Integration/RedisIntegrationTest.php +++ b/tests/Integration/RedisIntegrationTest.php @@ -44,6 +44,7 @@ protected function setUp(): void self::QUEUE . ':processing', self::QUEUE . ':failed', self::QUEUE . ':delayed', + self::QUEUE . ':started', ); $this->transport = new RedisTransport($this->client, 'default'); } @@ -191,4 +192,55 @@ public function test_a_message_waiting_on_an_in_flight_key_is_parked_not_lost(): self::assertSame(1, (int) $this->client->zcard(self::QUEUE . ':delayed')); self::assertSame(0, (int) $this->client->llen(self::QUEUE . ':processing')); } + + public function test_a_delivery_that_never_finished_is_counted_and_ends_at_max_attempts(): void + { + $this->transport->publish(EnvelopeCodec::encode(EnvelopeCodec::make('urn:babel:orders:created', ['n' => 1], self::QUEUE)), self::QUEUE); + + // Three deliveries whose handler died; the reaper puts the entry back each time. + foreach ([0, 1, 2] as $expected) { + $message = $this->transport->reserve(self::QUEUE, 1.0); + self::assertNotNull($message); + self::assertSame($expected, $message->attempts()); + self::assertSame($expected > 0, $message->wasAbandoned()); + self::assertSame( + $expected, + EnvelopeCodec::decode((string) $this->client->lindex(self::QUEUE . ':processing', 0))['attempts'], + 'the processing entry carries the count', + ); + + $this->client->lrem(self::QUEUE . ':processing', 1, (string) $message->receipt()); + $this->client->rpush(self::QUEUE, [(string) $message->receipt()]); + } + + $handler = new RecordingHandler(); + $worker = new Worker( + $this->transport, + new Dispatcher((new HandlerMap())->register('urn:babel:orders:created', $handler)), + new WorkerOptions(maxAttempts: 3, sleepWhenEmpty: 0.0, reserveTimeout: 1.0), + ); + $worker->runOnce(self::QUEUE); + + self::assertSame([], $handler->handled); + self::assertSame(0, (int) $this->client->llen(self::QUEUE . ':processing')); + self::assertSame(1, (int) $this->client->llen(self::QUEUE . ':failed')); + self::assertSame(0, (int) $this->client->zcard(self::QUEUE . ':started')); + } + + public function test_a_message_put_back_verbatim_is_not_counted_when_reserved_again(): void + { + $this->transport->publish(EnvelopeCodec::encode(EnvelopeCodec::make('urn:babel:orders:created', ['n' => 1], self::QUEUE)), self::QUEUE); + + $message = $this->transport->reserve(self::QUEUE, 1.0); + self::assertNotNull($message); + $this->transport->release($message, $message->rawBody(), 0); + + $again = $this->transport->reserve(self::QUEUE, 1.0); + self::assertNotNull($again); + self::assertFalse($again->wasAbandoned()); + self::assertSame(0, $again->attempts()); + + $this->transport->ack($again); + self::assertSame(0, (int) $this->client->zcard(self::QUEUE . ':started')); + } } diff --git a/tests/Support/CrashableIdempotencyStore.php b/tests/Support/CrashableIdempotencyStore.php new file mode 100644 index 0000000..2c9a79c --- /dev/null +++ b/tests/Support/CrashableIdempotencyStore.php @@ -0,0 +1,60 @@ +inner = new InMemoryIdempotencyStore(); + } + + public function seen(string $key): bool + { + return $this->inner->seen($key); + } + + public function claim(string $key, int $leaseSeconds = 0): bool + { + return $this->inner->claim($key, $leaseSeconds); + } + + public function isCompleted(string $key): bool + { + return $this->inner->isCompleted($key); + } + + public function remember(string $key, ?int $ttl = null): void + { + if (! $this->dead) { + $this->inner->remember($key, $ttl); + } + } + + public function forget(string $key): void + { + if (! $this->dead) { + $this->inner->forget($key); + } + } + + /** The lease of the dead worker's claim runs out. */ + public function lapse(string $key): void + { + $this->inner->forget($key); + } +} diff --git a/tests/Support/InMemoryRedis.php b/tests/Support/InMemoryRedis.php index 62c3320..7a3e8aa 100644 --- a/tests/Support/InMemoryRedis.php +++ b/tests/Support/InMemoryRedis.php @@ -11,8 +11,8 @@ /** * A tiny in-memory stand-in for a Predis client implementing just the list and * sorted-set commands {@see \InitPHP\Queue\Transport\Redis\RedisTransport} uses - * (`BLMOVE`, `RPUSH`, `LREM`, `ZADD`, `ZRANGEBYSCORE`, `ZREM`) plus an `eval()` - * that recognises the transport's three scripts by their leading marker comment + * (`BLMOVE`, `RPUSH`, `LREM`, `LINSERT`, `ZADD`, `ZRANGEBYSCORE`, `ZREMRANGEBYSCORE`, + * `ZREM`) plus an `eval()` that recognises the transport's four scripts by their leading marker comment * and applies the same steps atomically (the real scripts run against Redis in * the integration test). The remaining * {@see ClientInterface} methods are not exercised by the transport and throw. @@ -113,6 +113,33 @@ public function zrangebyscore(string $key, string $min, string $max): array return array_map(strval(...), array_keys($matching)); } + public function zremrangebyscore(string $key, string $min, string $max): int + { + $removed = 0; + foreach ($this->zrangebyscore($key, $min, $max) as $member) { + $removed += $this->zrem($key, $member); + } + + return $removed; + } + + /** + * @return int the new list length, or -1 when the pivot is not in the list + */ + public function linsert(string $key, string $whence, string $pivot, string $value): int + { + $list = $this->lists[$key] ?? []; + $at = array_search($pivot, $list, true); + if ($at === false) { + return -1; + } + + array_splice($list, $whence === 'BEFORE' ? $at : $at + 1, 0, [$value]); + $this->lists[$key] = $list; + + return count($list); + } + public function zrem(string $key, string $member): int { if (! isset($this->zsets[$key][$member])) { @@ -143,6 +170,7 @@ public function eval(string $script, int $numKeys, string ...$args): mixed if (! $this->takeOwnership($keys[0], $keys[2], $keys[1], $argv[0])) { return 0; } + $this->zrem($keys[3], $argv[3]); (float) $argv[2] > 0 ? $this->zadd($keys[2], [$argv[1] => (float) $argv[2]]) : $this->rpush($keys[1], [$argv[1]]); @@ -154,11 +182,23 @@ public function eval(string $script, int $numKeys, string ...$args): mixed if (! $this->takeOwnership($keys[0], $keys[2], $keys[3], $argv[0])) { return 0; } + $this->zrem($keys[4], $argv[2]); $this->rpush($keys[1], [$argv[1]]); return 1; } + if (str_contains($script, '-- queue:count-abandoned')) { + if ($this->linsert($keys[0], 'AFTER', $argv[0], $argv[1]) <= 0) { + return 0; + } + $this->lrem($keys[0], 1, $argv[0]); + $this->zrem($keys[1], $argv[2]); + $this->zadd($keys[1], [$argv[3] => (float) $argv[4]]); + + return 1; + } + if (str_contains($script, '-- queue:migrate')) { $due = array_slice($this->zrangebyscore($keys[0], '-inf', $argv[0]), 0, 1000); foreach ($due as $member) { diff --git a/tests/Support/OutcomeDroppingTransport.php b/tests/Support/OutcomeDroppingTransport.php new file mode 100644 index 0000000..829ccaf --- /dev/null +++ b/tests/Support/OutcomeDroppingTransport.php @@ -0,0 +1,46 @@ +inner->reserve($queue, $timeout); + } + + public function ack(ReceivedMessage $message): void + { + if (! $this->dropOutcomes) { + $this->inner->ack($message); + } + } + + public function release(ReceivedMessage $message, string $payload, int $delaySeconds = 0): void + { + if (! $this->dropOutcomes) { + $this->inner->release($message, $payload, $delaySeconds); + } + } + + public function deadLetter(ReceivedMessage $message, string $payload): void + { + if (! $this->dropOutcomes) { + $this->inner->deadLetter($message, $payload); + } + } +} diff --git a/tests/Transport/AmqpTransportTest.php b/tests/Transport/AmqpTransportTest.php index a91034c..7358abd 100644 --- a/tests/Transport/AmqpTransportTest.php +++ b/tests/Transport/AmqpTransportTest.php @@ -35,6 +35,7 @@ public function test_reserve_declares_the_queue_and_returns_the_message(): void $amqpMessage = Mockery::mock(AMQPMessage::class); $amqpMessage->shouldReceive('getBody')->andReturn($raw); $amqpMessage->shouldReceive('getDeliveryTag')->andReturn(42); + $amqpMessage->shouldReceive('isRedelivered')->andReturn(false); $channel = Mockery::mock(AMQPChannel::class); $channel->shouldReceive('queue_declare')->once()->with('orders', false, true, false, false); @@ -47,6 +48,46 @@ public function test_reserve_declares_the_queue_and_returns_the_message(): void self::assertSame(42, $message->receipt()); } + public function test_a_redelivered_message_counts_the_unfinished_delivery_as_an_attempt(): void + { + $raw = $this->envelope(); + + $amqpMessage = Mockery::mock(AMQPMessage::class); + $amqpMessage->shouldReceive('getBody')->andReturn($raw); + $amqpMessage->shouldReceive('getDeliveryTag')->andReturn(43); + $amqpMessage->shouldReceive('isRedelivered')->andReturn(true); + + $channel = Mockery::mock(AMQPChannel::class); + $channel->shouldReceive('queue_declare'); + $channel->shouldReceive('basic_get')->once()->andReturn($amqpMessage); + + $message = (new AmqpTransport($channel, 'default'))->reserve('orders'); + + self::assertNotNull($message); + self::assertTrue($message->wasAbandoned()); + self::assertSame(1, $message->attempts()); + self::assertSame(1, EnvelopeCodec::decode($message->rawBody())['attempts']); + self::assertSame(43, $message->receipt(), 'the delivery tag still identifies the broker message'); + } + + public function test_a_first_delivery_is_not_counted(): void + { + $amqpMessage = Mockery::mock(AMQPMessage::class); + $amqpMessage->shouldReceive('getBody')->andReturn($this->envelope()); + $amqpMessage->shouldReceive('getDeliveryTag')->andReturn(44); + $amqpMessage->shouldReceive('isRedelivered')->andReturn(false); + + $channel = Mockery::mock(AMQPChannel::class); + $channel->shouldReceive('queue_declare'); + $channel->shouldReceive('basic_get')->once()->andReturn($amqpMessage); + + $message = (new AmqpTransport($channel, 'default'))->reserve('orders'); + + self::assertNotNull($message); + self::assertFalse($message->wasAbandoned()); + self::assertSame(0, $message->attempts()); + } + public function test_reserve_returns_null_when_no_message_is_waiting(): void { $channel = Mockery::mock(AMQPChannel::class); diff --git a/tests/Transport/RedisTransportTest.php b/tests/Transport/RedisTransportTest.php index 9294c60..73855b7 100644 --- a/tests/Transport/RedisTransportTest.php +++ b/tests/Transport/RedisTransportTest.php @@ -272,6 +272,7 @@ public function test_a_client_that_refuses_eval_falls_back_and_keeps_working(): $client->shouldReceive('eval')->once()->andThrow(new ServerException('NOPERM this user has no permissions to run the \'eval\' command')); $client->shouldReceive('lrem')->with('orders:processing', 1, 'raw')->once()->andReturn(1); $client->shouldReceive('rpush')->with('orders', ['payload'])->once(); + $client->shouldReceive('zrem')->andReturn(0); $transport = new RedisTransport($client, 'default'); $transport->release(new ReceivedMessage('orders', 'raw', [], 'raw'), 'payload', 0);