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