-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathExponentialBackoff.php
103 lines (88 loc) · 2.41 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
<?php
namespace SchulzeFelix\AdWords;
/**
* Exponential backoff implementation.
*/
class ExponentialBackoff
{
const MAX_DELAY_MICROSECONDS = 120000000;
/**
* @var int
*/
private $retries;
/**
* @var callable
*/
private $retryFunction;
/**
* @var callable
*/
private $delayFunction;
/**
* @param int $retries [optional] Number of retries for a failed request.
* @param callable $retryFunction [optional] returns bool for whether or not to retry
*/
public function __construct($retries = null, callable $retryFunction = null)
{
$this->retries = $retries !== null ? (int) $retries : 3;
$this->retryFunction = $retryFunction;
$this->delayFunction = function ($delay) {
usleep($delay);
};
}
/**
* Executes the retry process.
*
* @param callable $function
* @param array $arguments [optional]
* @return mixed
* @throws \Exception The last exception caught while retrying.
*/
public function execute(callable $function, array $arguments = [])
{
$delayFunction = $this->delayFunction;
$retryAttempt = 0;
$exception = null;
while (true) {
try {
return call_user_func_array($function, $arguments);
} catch (\Exception $exception) {
if ($this->retryFunction) {
if (! call_user_func($this->retryFunction, $exception)) {
throw $exception;
}
}
if (in_array($exception->getCode(), [0, 400, 403])) {
break;
}
if ($retryAttempt >= $this->retries) {
break;
}
$delayFunction($this->calculateDelay($retryAttempt));
$retryAttempt++;
}
}
throw $exception;
}
/**
* @param callable $delayFunction
* @return void
*/
public function setDelayFunction(callable $delayFunction)
{
$this->delayFunction = $delayFunction;
}
/**
* Calculates exponential delay.
*
* @param int $attempt
* @return int
*/
private function calculateDelay($attempt)
{
return min(
mt_rand(0, 1000000) + (pow(2, $attempt) * 1000000),
self::MAX_DELAY_MICROSECONDS
);
}
}