1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Queue\Middleware; |
6
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use Yiisoft\Queue\Message\MessageInterface; |
9
|
|
|
use Yiisoft\Queue\Message\FailureEnvelope; |
10
|
|
|
use Yiisoft\Queue\QueueInterface; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Failure strategy which resends the given message to a queue. |
14
|
|
|
*/ |
15
|
|
|
final class SendAgainMiddleware implements MiddlewareInterface |
16
|
|
|
{ |
17
|
|
|
public const META_KEY_RESEND = 'failure-strategy-resend-attempts'; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @param string $id A unique id to differentiate two and more objects of this class |
21
|
|
|
* @param int $maxAttempts Maximum attempts count for this strategy with the given $id before it will give up |
22
|
|
|
*/ |
23
|
5 |
|
public function __construct( |
24
|
|
|
private string $id, |
25
|
|
|
private int $maxAttempts, |
26
|
|
|
private QueueInterface $queue |
27
|
|
|
) { |
28
|
5 |
|
if ($maxAttempts < 1) { |
29
|
|
|
throw new InvalidArgumentException("maxAttempts parameter must be a positive integer, $this->maxAttempts given."); |
30
|
|
|
} |
31
|
|
|
} |
32
|
|
|
|
33
|
5 |
|
public function process(Request $request, MessageHandlerInterface $handler): Request |
34
|
|
|
{ |
35
|
5 |
|
$message = $request->getMessage(); |
36
|
5 |
|
if ($this->suites($message)) { |
37
|
3 |
|
$envelope = new FailureEnvelope($message, $this->createMeta($message)); |
38
|
3 |
|
$envelope = $this->queue->push($envelope); |
39
|
|
|
|
40
|
3 |
|
$request = $request->withMessage($envelope); |
41
|
3 |
|
return $request->withQueue($this->queue); |
42
|
|
|
} |
43
|
|
|
|
44
|
3 |
|
return $handler->handle($request); |
45
|
|
|
} |
46
|
|
|
|
47
|
5 |
|
private function suites(MessageInterface $message): bool |
48
|
|
|
{ |
49
|
5 |
|
return $this->getAttempts($message) < $this->maxAttempts; |
50
|
|
|
} |
51
|
|
|
|
52
|
3 |
|
private function createMeta(MessageInterface $message): array |
53
|
|
|
{ |
54
|
3 |
|
$metadata = $message->getMetadata(); |
55
|
3 |
|
$metadata[$this->getMetaKey()] = $this->getAttempts($message) + 1; |
56
|
|
|
|
57
|
3 |
|
return $metadata; |
58
|
|
|
} |
59
|
|
|
|
60
|
5 |
|
private function getAttempts(MessageInterface $message): int |
61
|
|
|
{ |
62
|
5 |
|
$result = $message->getMetadata()[$this->getMetaKey()] ?? 0; |
63
|
5 |
|
if ($result < 0) { |
64
|
2 |
|
$result = 0; |
65
|
|
|
} |
66
|
|
|
|
67
|
5 |
|
return (int) $result; |
68
|
|
|
} |
69
|
|
|
|
70
|
5 |
|
private function getMetaKey(): string |
71
|
|
|
{ |
72
|
5 |
|
return self::META_KEY_RESEND . "-$this->id"; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|