class-backoff.php
2.47 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
<?php
namespace Smush\Core\Api;
class Backoff {
private $max_attempts = 5;
private $wait = 1;
private $use_jitter = true;
private $decider;
public function __construct() {
$this->set_decider( $this->get_default_decider() );
}
public function run( $callback ) {
$attempt = 0;
$try = true;
$result = null;
$max_attempts = $this->get_max_attempts();
while ( $try ) {
$this->wait( $attempt );
$result = call_user_func( $callback );
$attempt ++;
if ( $attempt >= $max_attempts ) {
$try = false;
} else {
$try = call_user_func( $this->get_decider(), $result );
}
}
return $result;
}
private function wait( $attempt ) {
if ( $attempt == 0 ) {
return;
}
usleep( $this->get_wait_time( $attempt ) * 1000 );
}
/**
* @return mixed
*/
private function get_max_attempts() {
return $this->max_attempts;
}
/**
* @param mixed $max_attempts
*
* @return Backoff
*/
public function set_max_attempts( $max_attempts ) {
$this->max_attempts = max( (int) $max_attempts, 0 );
return $this;
}
/**
* @return mixed
*/
private function get_wait_time( $attempt ) {
$wait_time = $attempt == 1
? $this->wait
: pow( 2, $attempt ) * $this->wait;
return $this->jitter( (int) $wait_time );
}
/**
* @return mixed
*/
private function get_initial_wait() {
return $this->wait;
}
/**
* @param mixed $wait
*
* @return Backoff
*/
public function set_wait( $wait ) {
$this->wait = $wait;
return $this;
}
/**
* @return mixed
*/
private function get_decider() {
return $this->decider;
}
/**
* @param mixed $decider
*
* @return Backoff
*/
public function set_decider( $decider ) {
$this->decider = $decider;
return $this;
}
private function get_default_decider() {
return function ( $result ) {
return is_wp_error( $result );
};
}
private function set_jitter( $useJitter ) {
$this->use_jitter = $useJitter;
}
public function enable_jitter() {
$this->set_jitter( true );
return $this;
}
public function disable_jitter() {
$this->set_jitter( false );
return $this;
}
private function jitter_enabled() {
return $this->use_jitter;
}
private function jitter( $wait_time ) {
if ( ! $this->jitter_enabled() ) {
return $wait_time;
}
$jitter_percentage = mt_rand( 1, 20 );
$add_or_subtract = array_rand( array(
- 1 => - 1,
+ 1 => + 1,
) );
$jitter = ( $wait_time * $jitter_percentage / 100 ) * $add_or_subtract;
return $wait_time + $jitter;
}
}