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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@

## 1.0.0 under development

- Fix recovery of expired message reservations.
- Initial release.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
55 changes: 44 additions & 11 deletions src/QueueProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,20 @@

namespace Yiisoft\Queue\Redis;

use InvalidArgumentException;
use RedisException;
use Yiisoft\Queue\Message\DelayEnvelope;
use Yiisoft\Queue\Redis\Exception\NotConnectedRedisException;
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
{
Expand All @@ -26,12 +29,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<string, array|bool|float|int|string|null> $meta
Expand Down Expand Up @@ -71,8 +82,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;
}

/**
Expand All @@ -82,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);
Expand All @@ -104,7 +125,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);
}
Expand Down Expand Up @@ -152,7 +173,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
Expand All @@ -168,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,
);
}
}
}
Expand Down
220 changes: 220 additions & 0 deletions tests/Integration/ReservationRecoveryTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Queue\Redis\Tests\Integration;

use PHPUnit\Framework\TestCase;
use Redis;
use RedisException;
use Yiisoft\Queue\Redis\QueueProvider;

use function bin2hex;
use function random_bytes;
use function sleep;
use function time;

final class ReservationRecoveryTest extends TestCase
{
private Redis $redis;
private string $channel;
private QueueProvider $provider;

protected function setUp(): void
{
parent::setUp();
$this->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));
}

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<string, array{string}> */
public static function expiredSetProvider(): array
{
return ['reserved' => ['reserved'], 'delayed' => ['delayed']];
}
}
Loading
Loading