Debian Codegraph @

lib/3rdParty/composer/symfony/http-client/Response/AmpResponseV4.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\HttpClient\Response;
13
14 use Amp\ByteStream\StreamException;
15 use Amp\CancellationTokenSource;
16 use Amp\Coroutine;
17 use Amp\Deferred;
18 use Amp\Http\Client\HttpException;
19 use Amp\Http\Client\Request;
20 use Amp\Http\Client\Response;
21 use Amp\Loop;
22 use Amp\Promise;
23 use Amp\Success;
24 use Psr\Log\LoggerInterface;
25 use Symfony\Component\HttpClient\Chunk\FirstChunk;
26 use Symfony\Component\HttpClient\Chunk\InformationalChunk;
27 use Symfony\Component\HttpClient\Exception\InvalidArgumentException;
28 use Symfony\Component\HttpClient\Exception\TransportException;
29 use Symfony\Component\HttpClient\HttpClientTrait;
30 use Symfony\Component\HttpClient\Internal\AmpBodyV4;
31 use Symfony\Component\HttpClient\Internal\AmpClientStateV4;
32 use Symfony\Component\HttpClient\Internal\Canary;
33 use Symfony\Component\HttpClient\Internal\ClientState;
34 use Symfony\Contracts\HttpClient\ResponseInterface;
35
36 /**
37 * @author Nicolas Grekas <[email protected]>
38 *
39 * @internal
40 */
41 final class AmpResponseV4 implements ResponseInterface, StreamableInterface
42 {
43 use CommonResponseTrait;
44 use TransportResponseTrait;
45
46 private static string $nextId = 'a';
47
48 private ?array $options;
49 private \Closure $onProgress;
50
51 private static ?string $delay = null;
52
53 /**
54 * @internal
55 */
56 public function __construct(
57 private AmpClientStateV4 $multi,
58 Request $request,
59 array $options,
60 ?LoggerInterface $logger,
61 ) {
62 $this->options = &$options;
63 $this->logger = $logger;
64 $this->timeout = $options['timeout'];
65 $this->shouldBuffer = $options['buffer'];
66
67 if ($this->inflate = \extension_loaded('zlib') && !$request->hasHeader('accept-encoding')) {
68 $request->setHeader('Accept-Encoding', 'gzip');
69 }
70
71 $this->initializer = static fn (self $response) => null !== $response->options;
72
73 $info = &$this->info;
74 $headers = &$this->headers;
75 $canceller = new CancellationTokenSource();
76 $handle = &$this->handle;
77
78 $info['url'] = (string) $request->getUri();
79 $info['http_method'] = $request->getMethod();
80 $info['start_time'] = null;
81 $info['redirect_url'] = null;
82 $info['original_url'] = $info['url'];
83 $info['redirect_time'] = 0.0;
84 $info['redirect_count'] = 0;
85 $info['size_upload'] = 0.0;
86 $info['size_download'] = 0.0;
87 $info['upload_content_length'] = -1.0;
88 $info['download_content_length'] = -1.0;
89 $info['user_data'] = $options['user_data'];
90 $info['max_duration'] = $options['max_duration'];
91 $info['debug'] = '';
92
93 $onProgress = $options['on_progress'] ?? static function () {};
94 $onProgress = $this->onProgress = static function () use (&$info, $onProgress) {
95 $info['total_time'] = microtime(true) - $info['start_time'];
96 $onProgress((int) $info['size_download'], ((int) (1 + $info['download_content_length']) ?: 1) - 1, (array) $info);
97 };
98
99 $pauseDeferred = new Deferred();
100 $pause = new Success();
101
102 $throttleWatcher = null;
103
104 $this->id = $id = self::$nextId;
105 self::$nextId = str_increment(self::$nextId);
106 Loop::defer(static function () use ($request, $multi, $id, &$info, &$headers, $canceller, &$options, $onProgress, &$handle, $logger, &$pause) {
107 return new Coroutine(self::generateResponse($request, $multi, $id, $info, $headers, $canceller, $options, $onProgress, $handle, $logger, $pause));
108 });
109
110 $info['pause_handler'] = static function (float $duration) use (&$throttleWatcher, &$pauseDeferred, &$pause) {
111 if (null !== $throttleWatcher) {
112 Loop::cancel($throttleWatcher);
113 }
114
115 $pause = $pauseDeferred->promise();
116
117 if ($duration <= 0) {
118 $deferred = $pauseDeferred;
119 $pauseDeferred = new Deferred();
120 $deferred->resolve();
121 } else {
122 $throttleWatcher = Loop::delay(ceil(1000 * $duration), static function () use (&$pauseDeferred) {
123 $deferred = $pauseDeferred;
124 $pauseDeferred = new Deferred();
125 $deferred->resolve();
126 });
127 }
128 };
129
130 $multi->lastTimeout = null;
131 $multi->openHandles[$id] = $id;
132 ++$multi->responseCount;
133
134 $this->canary = new Canary(static function () use ($canceller, $multi, $id) {
135 $canceller->cancel();
136 unset($multi->openHandles[$id], $multi->handlesActivity[$id]);
137 });
138 }
139
140 public function getInfo(?string $type = null): mixed
141 {
142 return null !== $type ? $this->info[$type] ?? null : $this->info;
143 }
144
145 public function __serialize(): array
146 {
147 throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
148 }
149
150 public function __unserialize(array $data): void
151 {
152 throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
153 }
154
155 public function __destruct()
156 {
157 try {
158 $this->doDestruct();
159 } finally {
160 // Clear the DNS cache when all requests completed
161 if (0 >= --$this->multi->responseCount) {
162 $this->multi->responseCount = 0;
163 $this->multi->dnsCache = [];
164 }
165 }
166 }
167
168 private static function schedule(self $response, array &$runningResponses): void
169 {
170 if (isset($runningResponses[0])) {
171 $runningResponses[0][1][$response->id] = $response;
172 } else {
173 $runningResponses[0] = [$response->multi, [$response->id => $response]];
174 }
175
176 if (!isset($response->multi->openHandles[$response->id])) {
177 $response->multi->handlesActivity[$response->id][] = null;
178 $response->multi->handlesActivity[$response->id][] = null !== $response->info['error'] ? new TransportException($response->info['error']) : null;
179 }
180 }
181
182 /**
183 * @param AmpClientStateV4 $multi
184 */
185 private static function perform(ClientState $multi, ?array $responses = null): void
186 {
187 foreach ($responses ?? [] as $response) {
188 try {
189 if ($response->info['start_time']) {
190 $response->info['total_time'] = microtime(true) - $response->info['start_time'];
191 ($response->onProgress)();
192 }
193 } catch (\Throwable $e) {
194 $multi->handlesActivity[$response->id][] = null;
195 $multi->handlesActivity[$response->id][] = $e;
196 }
197 }
198 }
199
200 /**
201 * @param AmpClientStateV4 $multi
202 */
203 private static function select(ClientState $multi, float $timeout): int
204 {
205 $timeout += hrtime(true) / 1E9;
206 self::$delay = Loop::defer(static function () use ($timeout) {
207 if (0 < $timeout -= hrtime(true) / 1E9) {
208 self::$delay = Loop::delay(ceil(1000 * $timeout), Loop::stop(...));
209 } else {
210 Loop::stop();
211 }
212 });
213
214 Loop::run();
215
216 return null === self::$delay ? 1 : 0;
217 }
218
219 private static function generateResponse(Request $request, AmpClientStateV4 $multi, string $id, array &$info, array &$headers, CancellationTokenSource $canceller, array &$options, \Closure $onProgress, &$handle, ?LoggerInterface $logger, Promise &$pause): \Generator
220 {
221 $request->setInformationalResponseHandler(static function (Response $response) use ($multi, $id, &$info, &$headers) {
222 self::addResponseHeaders($response, $info, $headers);
223 $multi->handlesActivity[$id][] = new InformationalChunk($response->getStatus(), $response->getHeaders());
224 self::stopLoop();
225 });
226
227 try {
228 /** @var Response $response */
229 if (null === $response = yield from self::getPushedResponse($request, $multi, $info, $headers, $options, $logger)) {
230 $logger?->info(\sprintf('Request: "%s %s"', $info['http_method'], $info['url']));
231
232 $response = yield from self::followRedirects($request, $multi, $info, $headers, $canceller, $options, $onProgress, $handle, $logger, $pause);
233 }
234
235 $options = null;
236
237 $multi->handlesActivity[$id][] = new FirstChunk();
238
239 if ('HEAD' === $response->getRequest()->getMethod() || \in_array($info['http_code'], [204, 304], true)) {
240 $multi->handlesActivity[$id][] = null;
241 $multi->handlesActivity[$id][] = null;
242 self::stopLoop();
243
244 return;
245 }
246
247 if ($response->hasHeader('content-length')) {
248 $info['download_content_length'] = (float) $response->getHeader('content-length');
249 }
250
251 $body = $response->getBody();
252
253 while (true) {
254 self::stopLoop();
255
256 yield $pause;
257
258 if (null === $data = yield $body->read()) {
259 break;
260 }
261
262 $info['size_download'] += \strlen($data);
263 $multi->handlesActivity[$id][] = $data;
264 }
265
266 $multi->handlesActivity[$id][] = null;
267 $multi->handlesActivity[$id][] = null;
268 } catch (\Throwable $e) {
269 $multi->handlesActivity[$id][] = null;
270 $multi->handlesActivity[$id][] = $e;
271 } finally {
272 $info['download_content_length'] = $info['size_download'];
273 }
274
275 self::stopLoop();
276 }
277
278 private static function followRedirects(Request $originRequest, AmpClientStateV4 $multi, array &$info, array &$headers, CancellationTokenSource $canceller, array $options, \Closure $onProgress, &$handle, ?LoggerInterface $logger, Promise &$pause): \Generator
279 {
280 yield $pause;
281
282 $originRequest->setBody(new AmpBodyV4($options['body'], $info, $onProgress));
283 $response = yield $multi->request($options, $originRequest, $canceller->getToken(), $info, $onProgress, $handle);
284 $previousUrl = null;
285
286 while (true) {
287 self::addResponseHeaders($response, $info, $headers);
288 $status = $response->getStatus();
289
290 if (!\in_array($status, [301, 302, 303, 307, 308], true) || null === $location = $response->getHeader('location')) {
291 return $response;
292 }
293
294 $urlResolver = new class {
295 use HttpClientTrait {
296 parseUrl as public;
297 resolveUrl as public;
298 }
299 };
300
301 try {
302 $previousUrl ??= $urlResolver::parseUrl($info['url']);
303 $location = $urlResolver::parseUrl($location);
304 $location = $urlResolver::resolveUrl($location, $previousUrl);
305 $info['redirect_url'] = implode('', $location);
306 } catch (InvalidArgumentException) {
307 return $response;
308 }
309
310 if (0 >= $options['max_redirects'] || $info['redirect_count'] >= $options['max_redirects']) {
311 return $response;
312 }
313
314 $logger?->info(\sprintf('Redirecting: "%s %s"', $status, $info['url']));
315
316 try {
317 // Discard body of redirects
318 while (null !== yield $response->getBody()->read()) {
319 }
320 } catch (HttpException|StreamException) {
321 // Ignore streaming errors on previous responses
322 }
323
324 ++$info['redirect_count'];
325 $info['url'] = $info['redirect_url'];
326 $info['redirect_url'] = null;
327 $previousUrl = $location;
328
329 $request = new Request($info['url'], $info['http_method']);
330 $request->setProtocolVersions($originRequest->getProtocolVersions());
331 $request->setTcpConnectTimeout($originRequest->getTcpConnectTimeout());
332 $request->setTlsHandshakeTimeout($originRequest->getTlsHandshakeTimeout());
333 $request->setTransferTimeout($originRequest->getTransferTimeout());
334 $request->setBodySizeLimit(0);
335 if (method_exists($request, 'setInactivityTimeout')) {
336 $request->setInactivityTimeout(0);
337 }
338
339 if (303 === $status || \in_array($status, [301, 302], true) && 'POST' === $response->getRequest()->getMethod()) {
340 // Do like curl and browsers: turn POST to GET on 301, 302 and 303
341 $originRequest->removeHeader('transfer-encoding');
342 $originRequest->removeHeader('content-length');
343 $originRequest->removeHeader('content-type');
344
345 $info['http_method'] = 'HEAD' === $response->getRequest()->getMethod() ? 'HEAD' : 'GET';
346 $request->setMethod($info['http_method']);
347 } else {
348 $request->setBody(AmpBodyV4::rewind($response->getRequest()->getBody()));
349 }
350
351 foreach ($originRequest->getRawHeaders() as [$name, $value]) {
352 $request->addHeader($name, $value);
353 }
354
355 if ($request->getUri()->getAuthority() !== $originRequest->getUri()->getAuthority()) {
356 $request->removeHeader('authorization');
357 $request->removeHeader('cookie');
358 $request->removeHeader('host');
359 }
360
361 yield $pause;
362
363 $response = yield $multi->request($options, $request, $canceller->getToken(), $info, $onProgress, $handle);
364 $info['redirect_time'] = microtime(true) - $info['start_time'];
365 }
366 }
367
368 private static function addResponseHeaders(Response $response, array &$info, array &$headers): void
369 {
370 $info['http_code'] = $response->getStatus();
371
372 if ($headers) {
373 $info['debug'] .= "< \r\n";
374 $headers = [];
375 }
376
377 $h = \sprintf('HTTP/%s %s %s', $response->getProtocolVersion(), $response->getStatus(), $response->getReason());
378 $info['debug'] .= "< {$h}\r\n";
379 $info['response_headers'][] = $h;
380
381 foreach ($response->getRawHeaders() as [$name, $value]) {
382 $headers[strtolower($name)][] = $value;
383 $h = $name.': '.$value;
384 $info['debug'] .= "< {$h}\r\n";
385 $info['response_headers'][] = $h;
386 }
387
388 $info['debug'] .= "< \r\n";
389 }
390
391 /**
392 * Accepts pushed responses only if their headers related to authentication match the request.
393 */
394 private static function getPushedResponse(Request $request, AmpClientStateV4 $multi, array &$info, array &$headers, array $options, ?LoggerInterface $logger): \Generator
395 {
396 if ('' !== $options['body']) {
397 return null;
398 }
399
400 $authority = $request->getUri()->getAuthority();
401
402 foreach ($multi->pushedResponses[$authority] ?? [] as $i => [$pushedUrl, $pushDeferred, $pushedRequest, $pushedResponse, $parentOptions]) {
403 if ($info['url'] !== $pushedUrl || $info['http_method'] !== $pushedRequest->getMethod()) {
404 continue;
405 }
406
407 foreach ($parentOptions as $k => $v) {
408 if ($options[$k] !== $v) {
409 continue 2;
410 }
411 }
412
413 foreach (['authorization', 'cookie', 'range', 'proxy-authorization'] as $k) {
414 if ($pushedRequest->getHeaderArray($k) !== $request->getHeaderArray($k)) {
415 continue 2;
416 }
417 }
418
419 $response = yield $pushedResponse;
420
421 foreach ($response->getHeaderArray('vary') as $vary) {
422 foreach (preg_split('/\s*+,\s*+/', $vary) as $v) {
423 if ('*' === $v || ($pushedRequest->getHeaderArray($v) !== $request->getHeaderArray($v) && 'accept-encoding' !== strtolower($v))) {
424 $logger?->debug(\sprintf('Skipping pushed response: "%s"', $info['url']));
425 continue 3;
426 }
427 }
428 }
429
430 $info += [
431 'connect_time' => 0.0,
432 'pretransfer_time' => 0.0,
433 'starttransfer_time' => 0.0,
434 'total_time' => 0.0,
435 'namelookup_time' => 0.0,
436 'primary_ip' => '',
437 'primary_port' => 0,
438 'start_time' => microtime(true),
439 ];
440
441 $pushDeferred->resolve();
442 $logger?->debug(\sprintf('Accepting pushed response: "%s %s"', $info['http_method'], $info['url']));
443 self::addResponseHeaders($response, $info, $headers);
444 unset($multi->pushedResponses[$authority][$i]);
445
446 if (!$multi->pushedResponses[$authority]) {
447 unset($multi->pushedResponses[$authority]);
448 }
449
450 return $response;
451 }
452 }
453
454 private static function stopLoop(): void
455 {
456 if (null !== self::$delay) {
457 Loop::cancel(self::$delay);
458 self::$delay = null;
459 }
460
461 Loop::defer(Loop::stop(...));
462 }
463 }