-
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathSendAgainMiddleware.php
More file actions
78 lines (65 loc) · 2.65 KB
/
Copy pathSendAgainMiddleware.php
File metadata and controls
78 lines (65 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
declare(strict_types=1);
namespace Yiisoft\Queue\Middleware\FailureHandling\Implementation;
use InvalidArgumentException;
use Yiisoft\Queue\Message\MessageInterface;
use Yiisoft\Queue\Middleware\FailureHandling\FailureEnvelope;
use Yiisoft\Queue\Middleware\FailureHandling\FailureHandlingRequest;
use Yiisoft\Queue\Middleware\FailureHandling\FailureHandlerInterface;
use Yiisoft\Queue\Middleware\FailureHandling\FailureMiddlewareInterface;
use Yiisoft\Queue\QueueInterface;
/**
* Failure strategy which resends the given message to a queue.
*/
final class SendAgainMiddleware implements FailureMiddlewareInterface
{
public const META_KEY_RESEND = 'failure-strategy-resend-attempts';
/**
* @param string $id A unique id to differentiate two and more instances of this class
* @param int $maxAttempts Maximum attempts count for this strategy with the given $id before it will give up
* @param QueueInterface|null $targetQueue Messages will be sent to this queue if set.
* They will be resent to an original queue otherwise.
*/
public function __construct(
private readonly string $id,
private readonly int $maxAttempts,
private readonly ?QueueInterface $targetQueue = null,
) {
if ($maxAttempts < 1) {
throw new InvalidArgumentException("maxAttempts parameter must be a positive integer, $this->maxAttempts given.");
}
}
public function processFailure(
FailureHandlingRequest $request,
FailureHandlerInterface $handler,
): FailureHandlingRequest {
$message = $request->getMessage();
if ($this->suits($message)) {
$envelope = new FailureEnvelope($message, $this->createMeta($message));
$envelope = ($this->targetQueue ?? $request->getQueue())->push($envelope);
return $request->withMessage($envelope)
->withQueue($this->targetQueue ?? $request->getQueue());
}
return $handler->handleFailure($request);
}
private function suits(MessageInterface $message): bool
{
return $this->getAttempts($message) < $this->maxAttempts;
}
private function createMeta(MessageInterface $message): array
{
return [$this->getMetaKey() => $this->getAttempts($message) + 1];
}
private function getAttempts(MessageInterface $message): int
{
$result = FailureEnvelope::fromMessage($message)->getFailureMetaValue($this->getMetaKey(), 0);
if ($result < 0) {
$result = 0;
}
return (int) $result;
}
private function getMetaKey(): string
{
return self::META_KEY_RESEND . "-$this->id";
}
}