-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExponentialBackoff.php
108 lines (98 loc) · 2.53 KB
/
ExponentialBackoff.php
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
namespace Avtonom\ExponentialBackoffBundle;
use Yriveiro\Backoff\BackoffInterface;
use Yriveiro\Backoff\Backoff;
class ExponentialBackoff implements BackoffInterface
{
/**
* @var BackoffInterface
*/
protected $backoff;
protected $delay;
/**
* @param $cap
* @param $maxAttempts
*/
public function __construct($cap, $maxAttempts)
{
$options = Backoff::getDefaultOptions();
$options['cap'] = $cap;
$this->delay = $cap;
$options['maxAttempts'] = $maxAttempts;
$this->backoff = new Backoff($options);
}
/**
* Returns an array of Configuration.
*
* cap: Max duration allowed (in microseconds). If backoff duration
* is greater than cap, cap is returned.
* maxAttempts: Number of attemps before thrown an Yriveiro\Backoff\BackoffException.
*
* @return mixed
*/
public static function getDefaultOptions()
{
return Backoff::getDefaultOptions();
}
/**
*
* Exponential backoff algorithm.
*
* c = attempt
*
* E(c) = (2**c - 1)
*
* @param int $attempt Attempt number.
*
* @return float Time to sleep in microseconds before a new retry. The value
* is in microseconds to use with usleep, sleep function only
* works with seconds
*
* @throws InvalidArgumentException.
* @throws BackoffException
*/
public function exponential($attempt)
{
return $this->backoff->exponential($attempt);
}
/**
* This method adds a half jitter value to exponential backoff value.
*
* @param int $attempt Attempt number.
*
* @return int
*/
public function equalJitter($attempt)
{
return $this->backoff->equalJitter($attempt);
}
/**
* This method adds a jitter value to exponential backoff value.
*
* @param int $attempt Attempt number.
*
* @return int
*/
public function fullJitter($attempt)
{
return $this->backoff->fullJitter($attempt);
}
/**
* @param $attempt
* @return int|number
*/
public function delay($attempt)
{
$delay = $attempt > 1 ? (pow(2, $attempt - 1) * $this->delay) : $this->delay;
return $delay;
}
/**
* @param $attempt
* @return int|number
*/
public function halfDelay($attempt)
{
$delay = $attempt > 0 ? (pow(2, $attempt - 2) * $this->delay) : $this->delay;
return $delay;
}
}