1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Spiral\Queue; |
6
|
|
|
|
7
|
|
|
use Spiral\Queue\Exception\InvalidArgumentException; |
8
|
|
|
use Spiral\Queue\Exception\JobException; |
9
|
|
|
use Spiral\Queue\Exception\RetryableExceptionInterface; |
10
|
|
|
|
11
|
|
|
final class RetryPolicy implements RetryPolicyInterface |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var positive-int|0 |
|
|
|
|
15
|
|
|
*/ |
16
|
|
|
private int $maxAttempts; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var positive-int|0 |
|
|
|
|
20
|
|
|
*/ |
21
|
|
|
private int $delay; |
22
|
|
|
|
23
|
|
|
private float $multiplier; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param positive-int|0 $maxAttempts |
|
|
|
|
27
|
|
|
* @param positive-int|0 $delay |
28
|
|
|
* |
29
|
|
|
* @throws InvalidArgumentException |
30
|
|
|
*/ |
31
|
16 |
|
public function __construct(int $maxAttempts, int $delay, float $multiplier = 1) |
32
|
|
|
{ |
33
|
16 |
|
if ($maxAttempts < 0) { |
34
|
1 |
|
throw new InvalidArgumentException( |
35
|
1 |
|
\sprintf('Maximum attempts must be greater than or equal to zero: `%s` given.', $maxAttempts) |
36
|
1 |
|
); |
37
|
|
|
} |
38
|
15 |
|
$this->maxAttempts = $maxAttempts; |
39
|
|
|
|
40
|
15 |
|
if ($delay < 0) { |
41
|
1 |
|
throw new InvalidArgumentException( |
42
|
1 |
|
\sprintf('Delay must be greater than or equal to zero: `%s` given.', $delay) |
43
|
1 |
|
); |
44
|
|
|
} |
45
|
14 |
|
$this->delay = $delay; |
46
|
|
|
|
47
|
14 |
|
if ($multiplier < 1) { |
48
|
1 |
|
throw new InvalidArgumentException( |
49
|
1 |
|
\sprintf('Multiplier must be greater than zero: `%s` given.', $multiplier) |
50
|
1 |
|
); |
51
|
|
|
} |
52
|
13 |
|
$this->multiplier = $multiplier; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param positive-int|0 $attempts |
|
|
|
|
57
|
|
|
* |
58
|
|
|
* @return positive-int |
|
|
|
|
59
|
|
|
*/ |
60
|
6 |
|
public function getDelay(int $attempts = 0): int |
61
|
|
|
{ |
62
|
6 |
|
return (int) \ceil($this->delay * $this->multiplier ** $attempts); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param positive-int|0 $attempts |
|
|
|
|
67
|
|
|
*/ |
68
|
11 |
|
public function isRetryable(\Throwable $exception, int $attempts = 0): bool |
69
|
|
|
{ |
70
|
11 |
|
if ($exception instanceof JobException && $exception->getPrevious() !== null) { |
71
|
1 |
|
$exception = $exception->getPrevious(); |
72
|
|
|
} |
73
|
|
|
|
74
|
11 |
|
if (!$exception instanceof RetryableExceptionInterface || $this->maxAttempts === 0) { |
75
|
3 |
|
return false; |
76
|
|
|
} |
77
|
|
|
|
78
|
8 |
|
return $exception->isRetryable() && $attempts < $this->maxAttempts; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|