Backoff.php
1.8 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
79
80
81
82
83
84
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Utils;
class Backoff
{
/**
* Max backoff.
*/
private const CAP = 60 * 1000; // 1 minute
/**
* @var int
*/
private $firstMs;
/**
* Backoff interval.
* @var int
*/
private $currentMs;
/**
* @param int the first backoff in milliseconds
*/
public function __construct(int $firstMs = 0)
{
if ($firstMs < 0) {
throw new \InvalidArgumentException(
'first backoff interval must be greater or equal than 0'
);
}
if ($firstMs > Backoff::CAP) {
throw new \InvalidArgumentException(
sprintf(
'first backoff interval must be less or equal than %d milliseconds',
self::CAP
)
);
}
$this->firstMs = $firstMs;
$this->currentMs = $firstMs;
}
/**
* Sleep until the next execution.
*/
public function sleep(): void
{
if ($this->currentMs === 0) {
return;
}
usleep($this->currentMs * 1000);
// update backoff using Decorrelated Jitter
// see: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
$this->currentMs = rand($this->firstMs, $this->currentMs * 3);
if ($this->currentMs > self::CAP) {
$this->currentMs = self::CAP;
}
}
/**
* Get the next backoff for logging, etc.
* @return int next backoff
*/
public function nextBackoff(): int
{
return $this->currentMs;
}
}