-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseClient.php
More file actions
283 lines (240 loc) · 8.69 KB
/
BaseClient.php
File metadata and controls
283 lines (240 loc) · 8.69 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
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
<?php
declare(strict_types=1);
namespace Increase\Core;
use Increase\Core\Contracts\BasePage;
use Increase\Core\Contracts\BaseResponse;
use Increase\Core\Contracts\BaseStream;
use Increase\Core\Conversion\Contracts\Converter;
use Increase\Core\Conversion\Contracts\ConverterSource;
use Increase\Core\Exceptions\APIConnectionException;
use Increase\Core\Exceptions\APIStatusException;
use Increase\Core\Implementation\RawResponse;
use Increase\RequestOptions;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* @phpstan-import-type RequestOpts from \Increase\RequestOptions
*
* @phpstan-type NormalizedRequest = array{
* method: string,
* path: string,
* query: array<string,mixed>,
* headers: array<string,string|null|list<string>>,
* body: mixed,
* }
*/
abstract class BaseClient
{
protected UriInterface $baseUrl;
/**
* @internal
*
* @param array<string,string|int|list<string|int>|null> $headers
*/
public function __construct(
protected array $headers,
string $baseUrl,
protected ?string $idempotencyHeader = null,
protected RequestOptions $options = new RequestOptions,
) {
assert(!is_null($this->options->uriFactory));
$this->baseUrl = $this->options->uriFactory->createUri($baseUrl);
}
/**
* @param string|list<mixed> $path
* @param array<string,mixed> $query
* @param array<string,mixed> $headers
* @param string|int|list<string|int>|null $unwrap
* @param class-string<BasePage<mixed>>|null $page
* @param class-string<BaseStream<mixed>>|null $stream
* @param RequestOptions|array<string,mixed>|null $options
*
* @return BaseResponse<mixed>
*/
public function request(
string $method,
string|array $path,
array $query = [],
array $headers = [],
mixed $body = null,
string|int|array|null $unwrap = null,
string|Converter|ConverterSource|null $convert = null,
?string $page = null,
?string $stream = null,
RequestOptions|array|null $options = [],
): BaseResponse {
[$req, $opts] = $this->buildRequest(
method: $method,
// @phpstan-ignore argument.type
path: $path,
query: $query,
// @phpstan-ignore argument.type
headers: $headers,
body: $body,
// @phpstan-ignore argument.type
opts: $options,
);
['method' => $method, 'path' => $uri, 'headers' => $headers, 'body' => $data] = $req;
assert(!is_null($opts->requestFactory));
$request = $opts->requestFactory->createRequest($method, uri: $uri);
$request = Util::withSetHeaders($request, headers: $headers);
$request = $this->transformRequest($request);
// @phpstan-ignore-next-line argument.type
$rsp = $this->sendRequest($opts, req: $request, data: $data, redirectCount: 0, retryCount: 0);
// @phpstan-ignore-next-line argument.type
return new RawResponse(client: $this, request: $request, response: $rsp, options: $opts, requestInfo: $req, unwrap: $unwrap, stream: $stream, page: $page, convert: $convert ?? 'null');
}
/**
* @internal
*/
protected function generateIdempotencyKey(): string
{
$hex = bin2hex(random_bytes(32));
return "stainless-php-retry-{$hex}";
}
/**
* @internal
*
* @param string|list<string> $path
* @param array<string,mixed> $query
* @param array<string,string|int|list<string|int>|null> $headers
* @param RequestOpts|null $opts
*
* @return array{NormalizedRequest, RequestOptions}
*/
protected function buildRequest(
string $method,
string|array $path,
array $query,
array $headers,
mixed $body,
RequestOptions|array|null $opts,
): array {
$options = RequestOptions::parse($this->options, $opts);
$parsedPath = Util::parsePath($path);
/** @var array<string,mixed> $mergedQuery */
$mergedQuery = array_merge_recursive(
$query,
$options->extraQueryParams ?? []
);
$uri = Util::joinUri($this->baseUrl, path: $parsedPath, query: $mergedQuery)->__toString();
$idempotencyHeaders = $this->idempotencyHeader && !array_key_exists($this->idempotencyHeader, array: $headers)
? [$this->idempotencyHeader => $this->generateIdempotencyKey()]
: [];
/** @var array<string,string|list<string>|null> $mergedHeaders */
$mergedHeaders = [
...$this->headers,
...$headers,
...($options->extraHeaders ?? []),
...$idempotencyHeaders,
];
$req = ['method' => strtoupper($method), 'path' => $uri, 'query' => $mergedQuery, 'headers' => $mergedHeaders, 'body' => $body];
return [$req, $options];
}
protected function transformRequest(
RequestInterface $request
): RequestInterface {
return $request;
}
/**
* @internal
*/
protected function followRedirect(
ResponseInterface $rsp,
RequestInterface $req
): RequestInterface {
$location = $rsp->getHeaderLine('Location');
if (!$location) {
throw new APIConnectionException($req, message: 'Redirection without Location header');
}
$uri = Util::joinUri($req->getUri(), path: $location);
return $req->withUri($uri);
}
/**
* @internal
*/
protected function shouldRetry(
RequestOptions $opts,
int $retryCount,
?ResponseInterface $rsp
): bool {
if ($retryCount >= $opts->maxRetries) {
return false;
}
$code = $rsp?->getStatusCode();
if (408 == $code || 409 == $code || 429 == $code || $code >= 500) {
return true;
}
return false;
}
/**
* @internal
*/
protected function retryDelay(
RequestOptions $opts,
int $retryCount,
?ResponseInterface $rsp
): float {
if (!empty($header = $rsp?->getHeaderLine('retry-after'))) {
if (is_numeric($header)) {
return floatval($header);
}
try {
$date = new \DateTimeImmutable($header);
$span = time() - $date->getTimestamp();
return max(0.0, $span);
} catch (\DateMalformedStringException) {
}
}
$scale = $retryCount ** 2;
$jitter = 1 - (0.25 * mt_rand() / mt_getrandmax());
$naive = $opts->initialRetryDelay * $scale * $jitter;
return max(0.0, min($naive, $opts->maxRetryDelay));
}
/**
* @internal
*
* @param bool|int|float|string|resource|\Traversable<mixed,>|array<string,mixed>|null $data
*/
protected function sendRequest(
RequestOptions $opts,
RequestInterface $req,
mixed $data,
int $retryCount,
int $redirectCount,
): ResponseInterface {
assert(null !== $opts->streamFactory && null !== $opts->transporter);
/** @var RequestInterface */
$req = $req->withHeader('X-Stainless-Retry-Count', strval($retryCount));
$req = Util::withSetBody($opts->streamFactory, req: $req, body: $data);
$rsp = null;
$err = null;
try {
$rsp = $opts->transporter->sendRequest($req);
} catch (ClientExceptionInterface $e) {
$err = $e;
}
$code = $rsp?->getStatusCode();
if ($code >= 300 && $code < 400) {
assert(!is_null($rsp));
if ($redirectCount >= 20) {
throw new APIConnectionException($req, message: 'Maximum redirects exceeded');
}
$req = $this->followRedirect($rsp, req: $req);
return $this->sendRequest($opts, req: $req, data: $data, retryCount: $retryCount, redirectCount: ++$redirectCount);
}
if ($code >= 400 || is_null($rsp)) {
if (!$this->shouldRetry($opts, retryCount: $retryCount, rsp: $rsp)) {
$exn = is_null($rsp) ? new APIConnectionException($req, previous: $err) : APIStatusException::from(request: $req, response: $rsp);
throw $exn;
}
$seconds = $this->retryDelay($opts, retryCount: $retryCount, rsp: $rsp);
$floor = floor($seconds);
time_nanosleep((int) $floor, nanoseconds: (int) ($seconds - $floor) * 10 ** 9);
return $this->sendRequest($opts, req: $req, data: $data, retryCount: ++$retryCount, redirectCount: $redirectCount);
}
return $rsp;
}
}