-
Notifications
You must be signed in to change notification settings - Fork 4
/
RetryHandler.php
307 lines (285 loc) · 11.2 KB
/
RetryHandler.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
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
<?php
/**
* Copyright (c) Microsoft Corporation. All Rights Reserved.
* Licensed under the MIT License. See License in the project root
* for license information.
*/
namespace Microsoft\Kiota\Http\Middleware;
use DateTime;
use DateTimeInterface;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Promise\Create;
use GuzzleHttp\Promise\PromiseInterface;
use Microsoft\Kiota\Http\Middleware\Options\ObservabilityOption;
use Microsoft\Kiota\Http\Middleware\Options\RetryOption;
use OpenTelemetry\API\Trace\SpanInterface;
use OpenTelemetry\API\Trace\StatusCode;
use OpenTelemetry\API\Trace\TracerInterface;
use OpenTelemetry\Context\Context;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use RuntimeException;
use function pow;
/**
* Class RetryHandler
*
* Middleware that retries requests based on {@link RetryOption} while respecting the Retry-After header
*
* @package Microsoft\Kiota\Http\Middleware
* @copyright 2021 Microsoft Corporation
* @license https://opensource.org/licenses/MIT MIT License
* @link https://developer.microsoft.com/graph
*/
class RetryHandler
{
public const HANDLER_NAME = 'kiotaRetryHandler';
private const RETRY_AFTER_HEADER = "Retry-After";
private const RETRY_ATTEMPT_HEADER = "Retry-Attempt";
/**
* @var TracerInterface
*/
private TracerInterface $tracer;
/**
* @var RetryOption configuration options for the middleware
*/
private RetryOption $retryOption;
/**
* @var callable(RequestInterface, array<string,mixed>): PromiseInterface $nextHandler
*/
private $nextHandler;
/**
* @param RetryOption|null $retryOption
* @param callable $nextHandler
*/
public function __construct(callable $nextHandler, ?RetryOption $retryOption = null)
{
$this->retryOption = ($retryOption) ?: new RetryOption();
$this->tracer = ObservabilityOption::getTracer();
$this->nextHandler = $nextHandler;
}
private const RETRY_HANDLER_INVOKED = "retryHandlerInvoked";
private const RETRY_HANDLER_ENABLED_KEY = 'com.microsoft.kiota.handler.retry.enable';
/**
* @param RequestInterface $request
* @param array<string, mixed> $options
* @return PromiseInterface
*/
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
$span = $this->tracer->spanBuilder(self::RETRY_HANDLER_INVOKED)->startSpan();
$span->addEvent(self::RETRY_HANDLER_INVOKED);
$scope = $span->activate();
try {
$span->setAttribute(self::RETRY_HANDLER_ENABLED_KEY, true);
// Request-level options override global options
if (array_key_exists(RetryOption::class, $options) && $options[RetryOption::class] instanceof RetryOption) {
$this->retryOption = $options[RetryOption::class];
}
$fn = $this->nextHandler;
return $fn($request, $options)->then(
$this->onFulfilled($request, $options, $span),
$this->onRejected($request, $options, $span)
);
} finally {
$scope->detach();
$span->end();
}
}
/**
* Handles retry for a successful request
*
* @param RequestInterface $request
* @param array<string, mixed> $options
* @param SpanInterface $span
* @return callable
*/
private function onFulfilled(RequestInterface $request, array $options, SpanInterface $span): callable
{
return function (?ResponseInterface $response) use ($request, $options, $span) {
$fullFilledSpan = $this->tracer->spanBuilder('onFullFilled')
->addLink($span->getContext())
->setParent(Context::getCurrent())
->startSpan();
try {
if (!$response) {
return $response;
}
$retries = $this->getRetries($request);
$span->setAttribute('retryCount', $retries);
$delaySecs = $this->calculateDelay($retries, $response);
$span->setAttribute('delaySeconds', $delaySecs);
$fullFilledSpan->setStatus(StatusCode::STATUS_OK, 'RetryFullFilled');
if (!$this->shouldRetry($request, $retries, $delaySecs, $response, $span)
|| $this->exceedRetriesTimeLimit($delaySecs)) {
return $response;
}
$options['delay'] = $delaySecs * 1000; // Guzzle sleeps the thread before executing request
$request = $request->withHeader(self::RETRY_ATTEMPT_HEADER, (string)($retries + 1));
$request->getBody()->rewind();
return $this($request, $options);
} finally {
$fullFilledSpan->end();
}
};
}
/**
* Handles retry if {@link BadResponseException} is thrown by Guzzle
* BadResponseException is thrown for 4xx and 5xx responses if configured on Guzzle client
*
* @param RequestInterface $request
* @param array<string,mixed> $options
* @param SpanInterface $span
* @return callable
*/
private function onRejected(RequestInterface $request, array $options, SpanInterface $span): callable
{
return function ($reason) use ($request, $options, $span) {
$rejectedSpan = $this->tracer->spanBuilder('onRejected')
->addLink($span->getContext())
->setParent(Context::getCurrent())
->startSpan();
$scope = $rejectedSpan->activate();
try {
$rejectedSpan->setStatus(StatusCode::STATUS_ERROR, 'RejectedRetry');
$rejectedSpan->recordException($reason);
// No retry for network-related/other exceptions
if (!is_a($reason, BadResponseException::class)) {
return Create::rejectionFor($reason);
}
$retries = $this->getRetries($request);
$rejectedSpan->setAttribute('http.retry_count', $retries);
$delaySecs = $this->calculateDelay($retries, $reason->getResponse());
$rejectedSpan->setAttribute('delaySeconds', $delaySecs);
if (!$this->shouldRetry($request, $retries, $delaySecs, $reason->getResponse(), $span)
|| $this->exceedRetriesTimeLimit($delaySecs)) {
Create::rejectionFor($reason);
}
$options['delay'] = $delaySecs * 1000; // Guzzle sleeps the thread before executing request
$request = $request->withHeader(self::RETRY_ATTEMPT_HEADER, (string)($retries + 1));
$request->getBody()->rewind();
return $this($request, $options);
} finally {
$scope->detach();
$rejectedSpan->end();
}
};
}
/**
* Returns true if request should be retried
*
* @param RequestInterface $request
* @param int $retries
* @param int $delaySecs
* @param ResponseInterface|null $response
* @param SpanInterface $span
* @return bool
*/
private function shouldRetry(RequestInterface $request, int $retries, int $delaySecs, ?ResponseInterface $response, SpanInterface $span): bool
{
$shouldRetryValue = ((($retries < $this->retryOption->getMaxRetries())
&& $this->isPayloadRewindable($request)
&& ($response && $this->retryOption->getShouldRetry()($delaySecs, $retries, $response))
&& $this->isRetryStatusCode($response->getStatusCode())) || !$response
);
$span->setAttribute('shouldRetry', $shouldRetryValue);
return $shouldRetryValue;
}
/**
* Get number of retries from the $request Retry-Attempt header
*
* @param RequestInterface $request
* @return int
*/
private function getRetries(RequestInterface $request): int
{
if ($request->hasHeader(self::RETRY_ATTEMPT_HEADER)) {
return intval($request->getHeader(self::RETRY_ATTEMPT_HEADER)[0]);
}
return 0;
}
/**
* Determine delay in seconds based on $retryOptions, total number of retries and Retry-After header value
*
* @param int $retries
* @param ResponseInterface|null $response
* @return int seconds to delay
*/
private function calculateDelay(int $retries, ?ResponseInterface $response): int
{
$retryAfterSeconds = 0;
if ($response && $response->hasHeader(self::RETRY_AFTER_HEADER)) {
$retryAfterSeconds = $this->parseRetryAfterToSeconds($response->getHeader(self::RETRY_AFTER_HEADER)[0]);
}
// First retry attempt
if ($retries == 0) {
return ($this->retryOption->getDelay() > $retryAfterSeconds) ? $this->retryOption->getDelay() : $retryAfterSeconds;
}
$retries++;
$expoDelay = self::exponentialDelay($retries, $this->retryOption->getDelay());
return ($expoDelay > $retryAfterSeconds) ? $expoDelay : $retryAfterSeconds;
}
/**
* Returns true if $delaySeconds exceeds {@link RetryOption} retriesTimeLimit
*
* @param int $delaySecs
* @return bool
*/
private function exceedRetriesTimeLimit(int $delaySecs): bool
{
if (!$this->retryOption->getRetriesTimeLimit()) {
return false;
}
// Add intervals to 01 Jan 1970 00:00:00
$retriesLimitSecs = date_create("@0")->add($this->retryOption->getRetriesTimeLimit())->getTimestamp();
$processingSecs = date_create("@0")->getTimestamp() + $delaySecs;
return ($processingSecs > $retriesLimitSecs);
}
/**
* Returns true if Http Status Code warrants a retry
*
* @param int $httpStatusCode
* @return bool
*/
private function isRetryStatusCode(int $httpStatusCode): bool
{
return ($httpStatusCode == 429 || $httpStatusCode == 503 || $httpStatusCode == 504);
}
/**
* Returns true if request payload is a rewindable stream
*
* @param RequestInterface $request
* @return bool
*/
private function isPayloadRewindable(RequestInterface $request): bool
{
return $request->getBody()->isSeekable();
}
/**
* Parses Http Retry-After values of type <http-date> of <delay-seconds>
*
* @param string $retryAfterValue Retry-After value formatted as <http-date> or <delay-seconds>
* @return int number of seconds
*/
private function parseRetryAfterToSeconds(string $retryAfterValue): int
{
if (is_numeric($retryAfterValue)) {
return intval($retryAfterValue);
}
$retryAfterDateTime = DateTime::createFromFormat(DateTimeInterface::RFC7231, $retryAfterValue);
if (!$retryAfterDateTime) {
throw new RuntimeException("Unable to parse Retry-After header value $retryAfterValue");
}
return $retryAfterDateTime->getTimestamp() - (new DateTime())->getTimestamp();
}
/**
* Exponential backoff delay
*
* @param int $retries
* @param int $delaySecs
* @return int
*/
public static function exponentialDelay(int $retries, int $delaySecs): int
{
return (int) pow(2, $retries - 1) * $delaySecs;
}
}