From 58158f1732a307eab4faa285fc1e8a8642c62a03 Mon Sep 17 00:00:00 2001 From: Alexandr Lyubimov <32051543+avlyubimov@users.noreply.github.com> Date: Mon, 9 Nov 2026 14:53:14 +0500 Subject: [PATCH 1/2] Fix recovery of expired message reservations --- CHANGELOG.md | 1 + README.md | 21 ++++ src/QueueProvider.php | 18 ++- tests/Integration/ReservationRecoveryTest.php | 115 ++++++++++++++++++ tests/Unit/QueueProviderTest.php | 40 ++++++ 5 files changed, 190 insertions(+), 5 deletions(-) create mode 100644 tests/Integration/ReservationRecoveryTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a8fbfe..aad0f11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,4 +2,5 @@ ## 1.0.0 under development +- Fix recovery of expired message reservations. - Initial release. diff --git a/README.md b/README.md index 112af4f..ec2ccc7 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,27 @@ composer require yiisoft/queue-redis ## General usage +### Reservation timeout + +Reserved messages that are not acknowledged with `delete()` become eligible for +redelivery after 300 seconds by default. A subsequent `reserve()` call moves +expired reservations back to the waiting list. This allows another consumer to +process a message when its previous consumer exits before acknowledging it. + +Configure the timeout in seconds through `QueueProvider`: + +```php +use Yiisoft\Queue\Redis\QueueProvider; + +// $redis is a connected ext-redis client. +$provider = new QueueProvider($redis, 'emails', reservationTimeout: 600); +``` + +The reservation timeout must be positive and should exceed the longest expected +message processing time. It is independent of the timeout passed to `reserve()`, +which controls how long to wait for an available message. Handlers should be +idempotent because a message may be delivered more than once. + ## Testing ### Unit testing diff --git a/src/QueueProvider.php b/src/QueueProvider.php index 65de2dc..f020a2c 100644 --- a/src/QueueProvider.php +++ b/src/QueueProvider.php @@ -4,6 +4,7 @@ namespace Yiisoft\Queue\Redis; +use InvalidArgumentException; use RedisException; use Yiisoft\Queue\Message\DelayEnvelope; use Yiisoft\Queue\Redis\Exception\NotConnectedRedisException; @@ -26,12 +27,20 @@ class QueueProvider implements QueueProviderInterface private const DEFAULT_CHANNEL_NAME = 'yii-queue'; /** + * @param int $reservationTimeout Seconds before an unacknowledged message can be reserved again. + * + * @throws InvalidArgumentException * @throws RedisException */ public function __construct( private Redis $redis, //redis connection, private string $channelName = self::DEFAULT_CHANNEL_NAME, - ) {} + private int $reservationTimeout = 300, + ) { + if ($reservationTimeout < 1) { + throw new InvalidArgumentException('Reservation timeout must be a positive integer.'); + } + } /** * @param array $meta @@ -71,8 +80,7 @@ public function existInWaiting(int $id): bool public function existInReserved(int $id): bool { $this->checkConnection(); - $exist = $this->redis->hexists("$this->channelName.attempts", (string) $id); - return is_bool($exist) ? $exist : false; + return $this->redis->zscore("$this->channelName.reserved", (string) $id) !== false; } /** @@ -104,7 +112,7 @@ public function reserve(int $timeout = 0): ?Reserve if (!is_string($payload)) { return null; } - $this->redis->zRem("$this->channelName.reserved", time(), $id); + $this->redis->zadd("$this->channelName.reserved", time() + $this->reservationTimeout, $id); $this->redis->hincrby("$this->channelName.attempts", $id, 1); return new Reserve((int) $id, $payload); } @@ -152,7 +160,7 @@ public function withChannelName(string $channelName): QueueProviderInterface return $this; } - return new self($this->redis, $channelName); + return new self($this->redis, $channelName, $this->reservationTimeout); } public function getChannelName(): string diff --git a/tests/Integration/ReservationRecoveryTest.php b/tests/Integration/ReservationRecoveryTest.php new file mode 100644 index 0000000..f85a48a --- /dev/null +++ b/tests/Integration/ReservationRecoveryTest.php @@ -0,0 +1,115 @@ +redis = new Redis(); + $this->redis->connect('redis'); + $this->channel = 'reservation-test-' . bin2hex(random_bytes(8)); + $this->provider = new QueueProvider($this->redis, $this->channel, 30); + } + + protected function tearDown(): void + { + foreach (['messages', 'waiting', 'reserved', 'attempts', 'delayed', 'message_id', 'moving_lock'] as $suffix) { + $this->redis->del($this->channel . '.' . $suffix); + } + $this->redis->close(); + parent::tearDown(); + } + + public function testReserveRecordsAnExpirationDeadline(): void + { + $id = $this->provider->pushMessage('payload'); + $before = time(); + + $message = $this->provider->reserve(1); + + self::assertNotNull($message); + self::assertSame($id, $message->id); + $deadline = $this->redis->zScore($this->channel . '.reserved', (string) $id); + self::assertNotFalse($deadline); + self::assertGreaterThanOrEqual($before + 30, $deadline); + self::assertLessThanOrEqual(time() + 30, $deadline); + } + + public function testUnacknowledgedMessageIsRecoveredAfterTheConsumerDisconnects(): void + { + $id = $this->provider->pushMessage('payload'); + $connection = new Redis(); + $connection->connect('redis'); + $consumer = new QueueProvider($connection, $this->channel, 1); + $first = $consumer->reserve(1); + self::assertNotNull($first); + self::assertSame($id, $first->id); + $connection->close(); + + sleep(2); + + $recovered = $this->provider->reserve(1); + self::assertNotNull($recovered); + self::assertSame($id, $recovered->id); + self::assertSame('payload', $recovered->payload); + self::assertSame('2', $this->redis->hGet($this->channel . '.attempts', (string) $id)); + } + + public function testAnUnexpiredReservationIsNotDeliveredAgain(): void + { + $provider = new QueueProvider($this->redis, $this->channel, 30); + $id = $provider->pushMessage('payload'); + self::assertNotNull($provider->reserve(1)); + + self::assertNull($provider->reserve(1)); + self::assertTrue($provider->existInReserved($id)); + self::assertSame('payload', $this->redis->hGet($this->channel . '.messages', (string) $id)); + } + + public function testAnExpiredReservationCanReturnToWaiting(): void + { + $firstId = $this->provider->pushMessage('first'); + $secondId = $this->provider->pushMessage('second'); + self::assertNotNull($this->provider->reserve(1)); + self::assertNotNull($this->provider->reserve(1)); + $expired = time() - 1; + $this->redis->zAdd($this->channel . '.reserved', $expired, (string) $firstId, $expired, (string) $secondId); + + $recovered = $this->provider->reserve(1); + + self::assertNotNull($recovered); + $waitingId = $recovered->id === $firstId ? $secondId : $firstId; + self::assertTrue($this->provider->existInWaiting($waitingId)); + self::assertFalse($this->provider->existInReserved($waitingId)); + self::assertTrue($this->provider->existInReserved($recovered->id)); + } + + public function testAcknowledgementRemovesTheReservation(): void + { + $id = $this->provider->pushMessage('payload'); + self::assertNotNull($this->provider->reserve(1)); + + $this->provider->delete((string) $id); + + self::assertFalse($this->provider->existInReserved($id)); + self::assertFalse($this->provider->existInWaiting($id)); + self::assertNull($this->provider->reserve(1)); + } +} diff --git a/tests/Unit/QueueProviderTest.php b/tests/Unit/QueueProviderTest.php index 7fd0bc8..533b34c 100644 --- a/tests/Unit/QueueProviderTest.php +++ b/tests/Unit/QueueProviderTest.php @@ -4,6 +4,7 @@ namespace Yiisoft\Queue\Redis\Tests\Unit; +use InvalidArgumentException; use PHPUnit\Framework\TestCase; use Yiisoft\Queue\Redis\Exception\NotConnectedRedisException; use Yiisoft\Queue\Redis\QueueProvider; @@ -14,6 +15,45 @@ class QueueProviderTest extends TestCase { + /** + * @dataProvider invalidReservationTimeoutProvider + */ + public function testReservationTimeoutMustBePositive(int $timeout): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Reservation timeout must be a positive integer.'); + + new QueueProvider($this->createMock(Redis::class), 'test', $timeout); + } + + /** @return array */ + public static function invalidReservationTimeoutProvider(): array + { + return ['zero' => [0], 'negative' => [-1]]; + } + + public function testChangingTheChannelPreservesTheReservationTimeout(): void + { + $redis = $this->createMock(Redis::class); + $redis->method('isConnected')->willReturn(true); + $redis->method('set')->willReturn(false); + $redis->method('brpop')->with('other.waiting', 1)->willReturn(['other.waiting', '1']); + $redis->method('hget')->with('other.messages', '1')->willReturn('payload'); + $before = time(); + $redis->expects(self::once())->method('zadd')->willReturnCallback( + static function (string $key, float|int $deadline, string $id) use ($before): int { + self::assertSame('other.reserved', $key); + self::assertSame('1', $id); + self::assertGreaterThanOrEqual($before + 42, $deadline); + self::assertLessThanOrEqual(time() + 42, $deadline); + return 1; + }, + ); + $provider = new QueueProvider($redis, 'test', 42); + + self::assertNotNull($provider->withChannelName('other')->reserve(1)); + } + public function test__construct() { $redis = $this->createMock(Redis::class); From 4cd31c7b081b09b4e491c01ea43b6a48443749a9 Mon Sep 17 00:00:00 2001 From: "sanchello95.24" Date: Fri, 20 Nov 2026 13:29:52 +0500 Subject: [PATCH 2/2] Fix concurrent expiry recovery and mover lock ownership --- src/QueueProvider.php | 37 +++++- tests/Integration/ReservationRecoveryTest.php | 105 ++++++++++++++++++ tests/Unit/QueueProviderTest.php | 5 +- 3 files changed, 137 insertions(+), 10 deletions(-) diff --git a/src/QueueProvider.php b/src/QueueProvider.php index f020a2c..e7b54c8 100644 --- a/src/QueueProvider.php +++ b/src/QueueProvider.php @@ -11,11 +11,13 @@ use Redis; use RuntimeException; +use function bin2hex; use function is_array; use function is_bool; use function is_float; use function is_int; use function is_string; +use function random_bytes; class QueueProvider implements QueueProviderInterface { @@ -90,13 +92,24 @@ public function reserve(int $timeout = 0): ?Reserve { $this->checkConnection(); // Moves delayed and reserved jobs into waiting list with lock for one second - try { - if ($this->redis->set("$this->channelName.moving_lock", 'true', ['NX', 'EX', 1])) { + $lockKey = "$this->channelName.moving_lock"; + $lockToken = bin2hex(random_bytes(16)); + if ($this->redis->set($lockKey, $lockToken, ['NX', 'EX', 1])) { + try { $this->moveExpired("$this->channelName.delayed"); $this->moveExpired("$this->channelName.reserved"); + } finally { + $this->redis->eval( + <<<'LUA' + if redis.call('GET', KEYS[1]) == ARGV[1] then + return redis.call('DEL', KEYS[1]) + end + return 0 + LUA, + [$lockKey, $lockToken], + 1, + ); } - } finally { - $this->redis->del("$this->channelName.moving_lock"); } $result = $this->redis->brpop("$this->channelName.waiting", $timeout); @@ -176,10 +189,22 @@ private function moveExpired(string $from): void $now = time(); $expired = $this->redis->zrevrangebyscore($from, (string) $now, '-inf'); if (is_array($expired)) { - $this->redis->zremrangebyscore($from, '-inf', (string) $now); /** @var string $id */ foreach ($expired as $id) { - $this->redis->rpush("$this->channelName.waiting", $id); + // A concurrent mover may have already recovered and reserved this ID. + $this->redis->eval( + <<<'LUA' + local score = redis.call('ZSCORE', KEYS[1], ARGV[1]) + if score and tonumber(score) <= tonumber(ARGV[2]) then + if redis.call('ZREM', KEYS[1], ARGV[1]) == 1 then + return redis.call('RPUSH', KEYS[2], ARGV[1]) + end + end + return 0 + LUA, + [$from, "$this->channelName.waiting", $id, $now], + 2, + ); } } } diff --git a/tests/Integration/ReservationRecoveryTest.php b/tests/Integration/ReservationRecoveryTest.php index f85a48a..6984ee9 100644 --- a/tests/Integration/ReservationRecoveryTest.php +++ b/tests/Integration/ReservationRecoveryTest.php @@ -6,6 +6,7 @@ use PHPUnit\Framework\TestCase; use Redis; +use RedisException; use Yiisoft\Queue\Redis\QueueProvider; use function bin2hex; @@ -112,4 +113,108 @@ public function testAcknowledgementRemovesTheReservation(): void self::assertFalse($this->provider->existInWaiting($id)); self::assertNull($this->provider->reserve(1)); } + + public function testAConsumerThatDoesNotAcquireTheMoverLockCannotReleaseIt(): void + { + $lock = $this->channel . '.moving_lock'; + $this->redis->set($lock, 'another-owner', ['EX' => 30]); + + self::assertNull($this->provider->reserve(1)); + + self::assertSame('another-owner', $this->redis->get($lock)); + } + + public function testAnExpiredLockOwnerCannotReleaseItsSuccessorsLock(): void + { + $lock = $this->channel . '.moving_lock'; + $redis = $this->createPartialMock(Redis::class, ['zrevrangebyscore']); + $redis->connect('redis'); + $redis->method('zrevrangebyscore')->willReturnCallback( + function (string $key, string $max, string $min) use ($lock): array { + self::assertNotFalse($this->redis->get($lock)); + // Simulate the first lock expiring and a second mover acquiring it. + $this->redis->set($lock, 'successor', ['EX' => 30]); + throw new RedisException('Interrupted expiry recovery.'); + }, + ); + $provider = new QueueProvider($redis, $this->channel); + + try { + $provider->reserve(1); + self::fail('Expiry recovery should have been interrupted.'); + } catch (RedisException $exception) { + self::assertSame('Interrupted expiry recovery.', $exception->getMessage()); + } finally { + $redis->close(); + } + + self::assertSame('successor', $this->redis->get($lock)); + } + + public function testTheMoverReleasesItsOwnLockAfterAnException(): void + { + $redis = $this->createPartialMock(Redis::class, ['zrevrangebyscore']); + $redis->connect('redis'); + $redis->method('zrevrangebyscore')->willThrowException(new RedisException('Interrupted expiry recovery.')); + + try { + (new QueueProvider($redis, $this->channel))->reserve(1); + self::fail('Expiry recovery should have been interrupted.'); + } catch (RedisException $exception) { + self::assertSame('Interrupted expiry recovery.', $exception->getMessage()); + } finally { + $redis->close(); + } + + self::assertFalse($this->redis->get($this->channel . '.moving_lock')); + } + + /** + * @dataProvider expiredSetProvider + */ + public function testAStaleMoverCannotRequeueAFreshReservation(string $suffix): void + { + $id = $this->provider->pushMessage('payload'); + self::assertNotNull($this->provider->reserve(1)); + $this->redis->zRem($this->channel . '.reserved', (string) $id); + $this->redis->zAdd($this->channel . '.' . $suffix, time() - 1, (string) $id); + + $redis = $this->createPartialMock(Redis::class, ['zrevrangebyscore']); + $redis->connect('redis'); + $interleaved = false; + $redis->method('zrevrangebyscore')->willReturnCallback( + function (string $key, string $max, string $min) use ($suffix, $id, &$interleaved): array { + $expired = $this->redis->zRevRangeByScore($key, $max, $min); + self::assertIsArray($expired); + if ($key === $this->channel . '.' . $suffix && !$interleaved) { + $interleaved = true; + self::assertSame([(string) $id], $expired); + // Pause this mover after selection. Its lock expires, then another + // consumer recovers the message and takes a fresh reservation. + $this->redis->del($this->channel . '.moving_lock'); + $recovered = $this->provider->reserve(1); + self::assertNotNull($recovered); + self::assertSame($id, $recovered->id); + } + return $expired; + }, + ); + + try { + self::assertNull((new QueueProvider($redis, $this->channel))->reserve(1)); + } finally { + $redis->close(); + } + + self::assertTrue($interleaved); + self::assertTrue($this->provider->existInReserved($id)); + self::assertSame('2', $this->redis->hGet($this->channel . '.attempts', (string) $id)); + self::assertSame([], $this->redis->lRange($this->channel . '.waiting', 0, -1)); + } + + /** @return array */ + public static function expiredSetProvider(): array + { + return ['reserved' => ['reserved'], 'delayed' => ['delayed']]; + } } diff --git a/tests/Unit/QueueProviderTest.php b/tests/Unit/QueueProviderTest.php index 533b34c..d3942cd 100644 --- a/tests/Unit/QueueProviderTest.php +++ b/tests/Unit/QueueProviderTest.php @@ -93,10 +93,7 @@ public function testRedisException(): void $mock->method('isConnected')->willReturn(true); $mock->method('hget')->willReturn(null); $mock->method('incr')->willReturn(false); - $mock->method('zrevrangebyscore')->willReturn(['1', '2']); - $mock->method('zremrangebyscore')->willReturn(0); - $mock->method('set')->willReturn(true); - $mock->expects($this->exactly(8))->method('rpush')->willReturn(1); + $mock->method('set')->willReturn(false); $provider = new QueueProvider($mock); $this->assertNull($provider->reserve()); $this->assertNull($provider->reserve());