-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathRequestResolver.php
More file actions
281 lines (238 loc) · 7.6 KB
/
Copy pathRequestResolver.php
File metadata and controls
281 lines (238 loc) · 7.6 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
<?php
namespace GT\Fetch;
use CurlHandle;
use Gt\Async\Loop;
use GT\Curl\CurlException;
use GT\Curl\CurlInterface;
use GT\Curl\CurlMultiInterface;
use Gt\Http\Header\Parser;
use Gt\Http\Response;
use Gt\Promise\Deferred;
use Psr\Http\Message\UriInterface;
class RequestResolver {
/** @var array<CurlMultiInterface|null> */
private array $curlMultiList;
/** @var array<CurlInterface|null> */
private array $curlList;
/** @var array<Deferred|null> */
private array $deferredList;
/** @var array<Response|null> */
private array $responseList;
/** @var array<string|null> */
private array $headerList;
/** @var array<string|null> */
private array $integrityList;
/** @var array<int|null> */
private array $maxRedirectsList;
/** @var array<object|null> */
private array $signalList;
public function __construct(
private readonly Loop $loop,
private readonly string $curlClass,
private readonly string $curlMultiClass,
) {
$this->curlMultiList = [];
$this->curlList = [];
$this->deferredList = [];
$this->responseList = [];
$this->headerList = [];
$this->integrityList = [];
$this->maxRedirectsList = [];
$this->signalList = [];
}
/**
* Adds a new job to resolve. An HTTP request will be made to the
* provided UriInterface via curl_multi, using the provided options
* array. The Deferred object will be used to pass back the resolved
* BodyResponse, or rejected Throwable.
* The optional $integrity value will match the response's body with the
* provided hash as Subresource Identity (SRI).
* The optional Controller $signal is used internally by curl to provide
* an abort signal.
* @param array<int, mixed> $curlOptArray
*/
public function add(
UriInterface $uri,
array $curlOptArray,
Deferred $deferred,
?string $integrity = null,
?Controller $signal = null,
):void {
/** @var CurlInterface $curl */
$curl = new $this->curlClass($uri);
// curlopt1: Set the default curlopt values here:
$curl->setOpt(CURLOPT_USERAGENT, Http::USER_AGENT);
// curlopt2: Then override any curlopt values that are provided:
foreach($curlOptArray as $option => $value) {
$curl->setOpt($option, $value);
}
// curlopt3: Finally, hard-code these curlopt settings:
$curl->setOpt(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$curl->setOpt(CURLOPT_RETURNTRANSFER, false);
$curl->setOpt(CURLOPT_HEADER, false);
$curl->setOpt(CURLOPT_HEADERFUNCTION, $this->writeHeader(...));
$curl->setOpt(CURLOPT_WRITEFUNCTION, $this->writeBody(...));
$curl->setOpt(CURLOPT_PROGRESSFUNCTION, $this->progress(...));
$curl->setOpt(CURLOPT_NOPROGRESS, false);
/** @var CurlMultiInterface $curlMulti */
$curlMulti = new $this->curlMultiClass();
$curlMulti->add($curl);
$this->loop->addDeferredToTimer($deferred);
$bodyResponse = new Response();
$bodyResponse->startDeferredResponse($curl);
array_push($this->curlList, $curl);
array_push($this->curlMultiList, $curlMulti);
array_push($this->deferredList, $deferred);
array_push($this->integrityList, $integrity);
array_push(
$this->maxRedirectsList,
$curlOptArray[CURLOPT_MAXREDIRS] ?? null
);
array_push($this->responseList, $bodyResponse);
array_push($this->headerList, "");
array_push($this->signalList, $signal);
}
public function tick():void {
$totalActive = 0;
foreach($this->curlMultiList as $i => $curlMulti) {
$this->processCurlMulti($curlMulti, $i, $totalActive);
}
if($totalActive === 0) {
$this->loop->halt();
}
}
private function processCurlMulti(
CurlMultiInterface $curlMulti,
int $index,
int &$totalActive,
):void {
$active = 0;
$this->executeCurlMultiLoop($curlMulti, $active);
if($active === 0) {
$this->handleCompletedCurlMulti($index);
}
else {
$totalActive += $active;
}
}
private function executeCurlMultiLoop(
CurlMultiInterface $curlMulti,
int &$active,
):void {
do {
$status = $curlMulti->exec($active);
}
while($status === CURLM_CALL_MULTI_PERFORM);
if($status !== CURLM_OK) {
$this->handleCurlMultiError($curlMulti);
}
}
private function handleCurlMultiError(CurlMultiInterface $curlMulti):void {
$errNo = curl_multi_errno($curlMulti->getHandle());
$errString = curl_multi_strerror($errNo);
throw new CurlException($errString);
}
private function handleCompletedCurlMulti(int $index):void {
$response = $this->responseList[$index] ?? null;
if($response) {
$response->endDeferredResponse($this->integrityList[$index]);
if($this->deferredList[$index]) {
$this->deferredList[$index]->resolve($response);
}
$this->cleanupCompletedRequestData($index);
}
}
private function cleanupCompletedRequestData(int $index):void {
$this->responseList[$index] = null;
$this->deferredList[$index] = null;
}
private function writeHeader(
CurlHandle|CurlInterface $ch,
string $rawHeader,
):int {
$i = $this->getIndex($ch);
$headerLine = trim($rawHeader);
if($this->isStartOfNewHeaderBlock($i, $headerLine)) {
$this->headerList[$i] = "";
$this->responseList[$i] = new Response();
$this->responseList[$i]->startDeferredResponse($this->curlList[$i]);
}
// If $headerLine is empty, it represents the last line before the body starts.
// HTTP headers always end on an empty line.
// See https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html
if($headerLine === "") {
$parser = new Parser($this->headerList[$i]);
$this->responseList[$i] = $this->responseList[$i]->withProtocolVersion(
$parser->getProtocolVersion()
);
$this->responseList[$i] = $this->responseList[$i]->withStatus(
$parser->getStatusCode()
);
foreach($parser->getKeyValues() as $key => $value) {
if(empty($key)) {
continue;
}
$this->responseList[$i] = $this->responseList[$i]->withAddedHeader(
$key,
$value
);
}
}
if(str_starts_with(strtolower($headerLine), "location: ")) {
if($this->maxRedirectsList[$i] === 0) {
throw new FetchException("Redirect is disallowed");
}
}
$this->headerList[$i] .= $rawHeader;
// To indicate that this function has successfully run, cURL expects it to
// return the number of bytes read. If this does not match the same number
// that cURL sees, cURL will drop the connection.
return strlen($rawHeader);
}
private function isStartOfNewHeaderBlock(int $index, string $headerLine):bool {
return str_starts_with(strtolower($headerLine), "http/")
&& trim($this->headerList[$index]) !== "";
}
private function writeBody(CurlHandle|CurlInterface $ch, string $content):int {
$i = $this->getIndex($ch);
$body = $this->responseList[$i]->getBody();
$body->write($content);
if($this->deferredList[$i]) {
$this->deferredList[$i]->resolve($this->responseList[$i]);
$this->deferredList[$i] = null;
}
// To indicate that this function has successfully run, cURL expects it to
// return the number of bytes read. If this does not match the same number
// that cURL sees, cURL will drop the connection.
return strlen($content);
}
/**
* @SuppressWarnings("UnusedFormalParameter")
* @noinspection PhpUnusedParameterInspection
*/
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter
private function progress(
CurlHandle|CurlInterface $ch,
int $expectedDownloadedBytes,
int $downloadedBytes,
int $expectedUploadedBytes,
int $uploadedBytes
):int {
$index = $this->getIndex($ch);
return (int)$this->signalList[$index]?->aborted;
}
private function getIndex(CurlHandle|CurlInterface $chIncoming):int {
$i = -1;
$match = false;
foreach($this->curlList as $i => $curl) {
if($chIncoming === $curl->getHandle()) {
$match = true;
break;
}
}
if(!$match) {
throw new FetchException("There is no curl handle");
}
return $i;
}
}