Debian Codegraph @

lib/3rdParty/composer/symfony/http-client/Response/AsyncResponse.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 Symfony\Component\HttpClient\Chunk\ErrorChunk;
15 use Symfony\Component\HttpClient\Chunk\LastChunk;
16 use Symfony\Component\HttpClient\Exception\TransportException;
17 use Symfony\Contracts\HttpClient\ChunkInterface;
18 use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
19 use Symfony\Contracts\HttpClient\Exception\HttpExceptionInterface;
20 use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
21 use Symfony\Contracts\HttpClient\HttpClientInterface;
22 use Symfony\Contracts\HttpClient\ResponseInterface;
23
24 /**
25 * Provides a single extension point to process a response's content stream.
26 *
27 * @author Nicolas Grekas <[email protected]>
28 */
29 class AsyncResponse implements ResponseInterface, StreamableInterface
30 {
31 use CommonResponseTrait;
32
33 private const FIRST_CHUNK_YIELDED = 1;
34 private const LAST_CHUNK_YIELDED = 2;
35
36 private ?HttpClientInterface $client;
37 private ResponseInterface $response;
38 private array $info = ['canceled' => false];
39 /** @var callable|null */
40 private $passthru;
41 private ?\Iterator $stream = null;
42 private ?int $yieldedState = null;
43 private bool $hasThrown = false;
44
45 /**
46 * @param ?callable(ChunkInterface, AsyncContext): ?\Iterator $passthru
47 */
48 public function __construct(HttpClientInterface $client, string $method, string $url, array $options, ?callable $passthru = null)
49 {
50 $this->client = $client;
51 $this->shouldBuffer = $options['buffer'] ?? true;
52
53 if (null !== $onProgress = $options['on_progress'] ?? null) {
54 $thisInfo = &$this->info;
55 $options['on_progress'] = static function (int $dlNow, int $dlSize, array $info) use (&$thisInfo, $onProgress) {
56 $onProgress($dlNow, $dlSize, $thisInfo + $info);
57 };
58 }
59 $this->response = $client->request($method, $url, ['buffer' => false] + $options);
60 $this->passthru = $passthru;
61 $this->initializer = static function (self $response, ?float $timeout = null) {
62 if (null === $response->shouldBuffer) {
63 return false;
64 }
65
66 while (true) {
67 foreach (self::stream([$response], $timeout) as $chunk) {
68 if ($chunk->isTimeout() && ($response->passthru || $response = self::findInnerPassthru($response))) {
69 // Timeouts thrown during initialization are transport errors
70 foreach (self::passthru($response->client, $response, new ErrorChunk($response->offset, new TransportException($chunk->getError()))) as $chunk) {
71 if ($chunk->isFirst()) {
72 return false;
73 }
74 }
75
76 continue 2;
77 }
78
79 if ($chunk->isFirst()) {
80 return false;
81 }
82 }
83
84 return false;
85 }
86 };
87 if (\array_key_exists('user_data', $options)) {
88 $this->info['user_data'] = $options['user_data'];
89 }
90 if (\array_key_exists('max_duration', $options)) {
91 $this->info['max_duration'] = $options['max_duration'];
92 }
93 }
94
95 public function getStatusCode(): int
96 {
97 if ($this->initializer) {
98 self::initialize($this);
99 }
100
101 return $this->response->getStatusCode();
102 }
103
104 public function getHeaders(bool $throw = true): array
105 {
106 if ($this->initializer) {
107 self::initialize($this);
108 }
109
110 $headers = $this->response->getHeaders(false);
111
112 if ($throw) {
113 $this->checkStatusCode();
114 }
115
116 return $headers;
117 }
118
119 public function getInfo(?string $type = null): mixed
120 {
121 if ('debug' === ($type ?? 'debug')) {
122 $debug = implode('', array_column($this->info['previous_info'] ?? [], 'debug'));
123 $debug .= $this->response->getInfo('debug');
124
125 if ('debug' === $type) {
126 return $debug;
127 }
128 }
129
130 if (null !== $type) {
131 return $this->info[$type] ?? $this->response->getInfo($type);
132 }
133
134 return array_merge($this->info + $this->response->getInfo(), ['debug' => $debug]);
135 }
136
137 /**
138 * @return resource
139 */
140 public function toStream(bool $throw = true)
141 {
142 if ($throw) {
143 // Ensure headers arrived
144 $this->getHeaders(true);
145 }
146
147 $handle = function () {
148 $stream = $this->response instanceof StreamableInterface ? $this->response->toStream(false) : StreamWrapper::createResource($this->response);
149
150 return stream_get_meta_data($stream)['wrapper_data']->stream_cast(\STREAM_CAST_FOR_SELECT);
151 };
152
153 $stream = StreamWrapper::createResource($this);
154 stream_get_meta_data($stream)['wrapper_data']
155 ->bindHandles($handle, $this->content);
156
157 return $stream;
158 }
159
160 public function cancel(): void
161 {
162 if ($this->info['canceled']) {
163 return;
164 }
165
166 $this->info['canceled'] = true;
167 $this->info['error'] = 'Response has been canceled.';
168 $this->close();
169 $client = $this->client;
170 $this->client = null;
171
172 if (!$this->passthru) {
173 return;
174 }
175
176 try {
177 foreach (self::passthru($client, $this, new LastChunk()) as $chunk) {
178 // no-op
179 }
180
181 $this->passthru = null;
182 } catch (ExceptionInterface) {
183 // ignore any errors when canceling
184 }
185 }
186
187 public function __destruct()
188 {
189 $httpException = null;
190
191 if ($this->initializer && null === $this->getInfo('error') && !$this->hasThrown) {
192 try {
193 self::initialize($this, -0.0);
194 $this->getHeaders(true);
195 } catch (HttpExceptionInterface $httpException) {
196 // no-op
197 }
198 }
199
200 if ($this->passthru && null === $this->getInfo('error')) {
201 $this->info['canceled'] = true;
202
203 try {
204 foreach (self::passthru($this->client, $this, new LastChunk()) as $chunk) {
205 // no-op
206 }
207 } catch (ExceptionInterface) {
208 // ignore any errors when destructing
209 }
210 }
211
212 if (null !== $httpException) {
213 throw $httpException;
214 }
215 }
216
217 /**
218 * @internal
219 */
220 public static function stream(iterable $responses, ?float $timeout = null, ?string $class = null): \Generator
221 {
222 while ($responses) {
223 $wrappedResponses = [];
224 $asyncMap = new \SplObjectStorage();
225 $client = null;
226
227 foreach ($responses as $r) {
228 if (!$r instanceof self) {
229 throw new \TypeError(\sprintf('"%s::stream()" expects parameter 1 to be an iterable of AsyncResponse objects, "%s" given.', $class ?? static::class, get_debug_type($r)));
230 }
231
232 if (null !== $e = $r->info['error'] ?? null) {
233 yield $r => $chunk = new ErrorChunk($r->offset, new TransportException($e));
234 $chunk->didThrow() ?: $chunk->getContent();
235 continue;
236 }
237
238 if (null === $client) {
239 $client = $r->client;
240 } elseif ($r->client !== $client) {
241 throw new TransportException('Cannot stream AsyncResponse objects with many clients.');
242 }
243
244 $asyncMap[$r->response] = $r;
245 $wrappedResponses[] = $r->response;
246
247 if ($r->stream) {
248 yield from self::passthruStream($response = $r->response, $r, $asyncMap, new LastChunk());
249
250 if (!isset($asyncMap[$response])) {
251 array_pop($wrappedResponses);
252 }
253
254 if ($r->response !== $response && !isset($asyncMap[$r->response])) {
255 $asyncMap[$r->response] = $r;
256 $wrappedResponses[] = $r->response;
257 }
258 }
259 }
260
261 if (!$client || !$wrappedResponses) {
262 return;
263 }
264
265 $chunk = null;
266 foreach ($client->stream($wrappedResponses, $timeout) as $response => $chunk) {
267 $r = $asyncMap[$response];
268
269 if (null === $chunk->getError()) {
270 if ($chunk->isFirst()) {
271 // Ensure no exception is thrown on destruct for the wrapped response
272 $r->response->getStatusCode();
273 } elseif (0 === $r->offset && null === $r->content && $chunk->isLast()) {
274 $r->content = fopen('php://memory', 'w+');
275 }
276 }
277
278 $innerR = null;
279 if (!$r->passthru && !$innerR = null !== $chunk->getError() ? self::findInnerPassthru($r) : null) {
280 $r->stream = (static fn () => yield $chunk)();
281 yield from self::passthruStream($response, $r, $asyncMap);
282
283 continue;
284 }
285
286 if (null !== $chunk->getError()) {
287 // no-op
288 } elseif ($chunk->isFirst()) {
289 $r->yieldedState = self::FIRST_CHUNK_YIELDED;
290 } elseif (self::FIRST_CHUNK_YIELDED !== $r->yieldedState && null === $chunk->getInformationalStatus()) {
291 throw new \LogicException(\sprintf('Instance of "%s" is already consumed and cannot be managed by "%s". A decorated client should not call any of the response\'s methods in its "request()" method.', get_debug_type($response), $class ?? static::class));
292 }
293
294 $innerR ??= $r;
295 foreach (self::passthru($innerR->client, $innerR, $chunk, $asyncMap) as $chunk) {
296 yield $r => $chunk;
297 }
298
299 if ($innerR->response !== $response && isset($asyncMap[$response])) {
300 break;
301 }
302 }
303
304 if (null === $chunk) {
305 throw new \LogicException(\sprintf('"%s" is not compliant with HttpClientInterface: its "stream()" method didn\'t yield any chunks when it should have.', get_debug_type($client)));
306 }
307 if (null === $chunk->getError() && $chunk->isLast()) {
308 $r->yieldedState = self::LAST_CHUNK_YIELDED;
309 }
310 if (null === $chunk->getError() && self::LAST_CHUNK_YIELDED !== $r->yieldedState && $r->response === $response && null !== $r->client) {
311 throw new \LogicException('A chunk passthru must yield an "isLast()" chunk before ending a stream.');
312 }
313
314 $responses = [];
315 foreach ($asyncMap as $response) {
316 $r = $asyncMap[$response];
317
318 if (null !== $r->client) {
319 $responses[] = $r;
320 }
321 }
322 }
323 }
324
325 /**
326 * @param \SplObjectStorage<ResponseInterface, AsyncResponse>|null $asyncMap
327 */
328 private static function passthru(HttpClientInterface $client, self $r, ChunkInterface $chunk, ?\SplObjectStorage $asyncMap = null): \Generator
329 {
330 $r->stream = null;
331 $response = $r->response;
332 $context = new AsyncContext($r->passthru, $client, $r->response, $r->info, $r->content, $r->offset);
333 if (null === $stream = ($r->passthru)($chunk, $context)) {
334 if ($r->response === $response && (null !== $chunk->getError() || $chunk->isLast())) {
335 throw new \LogicException('A chunk passthru cannot swallow the last chunk.');
336 }
337
338 return;
339 }
340
341 if (!$stream instanceof \Iterator) {
342 throw new \LogicException(\sprintf('A chunk passthru must return an "Iterator", "%s" returned.', get_debug_type($stream)));
343 }
344 $r->stream = $stream;
345
346 yield from self::passthruStream($response, $r, $asyncMap);
347 }
348
349 private static function findInnerPassthru(self $response): ?self
350 {
351 $innerResponse = $response->response ?? null;
352
353 while ($innerResponse instanceof self) {
354 if ($innerResponse->passthru) {
355 return $innerResponse;
356 }
357
358 $innerResponse = $innerResponse->response ?? null;
359 }
360
361 return null;
362 }
363
364 /**
365 * @param \SplObjectStorage<ResponseInterface, AsyncResponse>|null $asyncMap
366 */
367 private static function passthruStream(ResponseInterface $response, self $r, ?\SplObjectStorage $asyncMap, ?ChunkInterface $chunk = null): \Generator
368 {
369 while (true) {
370 try {
371 if (null !== $chunk && $r->stream) {
372 $r->stream->next();
373 }
374
375 if (!$r->stream || !$r->stream->valid() || !$r->stream) {
376 $r->stream = null;
377 break;
378 }
379 } catch (\Throwable $e) {
380 unset($asyncMap[$response]);
381 $r->stream = null;
382 $r->info['error'] = $e->getMessage();
383 $r->response->cancel();
384
385 yield $r => $chunk = new ErrorChunk($r->offset, $e);
386 $chunk->didThrow() ?: $chunk->getContent();
387 break;
388 }
389
390 $chunk = $r->stream->current();
391
392 if (!$chunk instanceof ChunkInterface) {
393 throw new \LogicException(\sprintf('A chunk passthru must yield instances of "%s", "%s" yielded.', ChunkInterface::class, get_debug_type($chunk)));
394 }
395
396 if (null !== $chunk->getError()) {
397 // no-op
398 } elseif ($chunk->isFirst()) {
399 $e = $r->openBuffer();
400
401 yield $r => $chunk;
402
403 if ($r->initializer && null === $r->getInfo('error')) {
404 // Ensure the HTTP status code is always checked
405 $r->getHeaders(true);
406 }
407
408 if (null === $e) {
409 continue;
410 }
411
412 $r->response->cancel();
413 $chunk = new ErrorChunk($r->offset, $e);
414 } elseif ('' !== $content = $chunk->getContent()) {
415 if (null !== $r->shouldBuffer) {
416 throw new \LogicException('A chunk passthru must yield an "isFirst()" chunk before any content chunk.');
417 }
418
419 if (null !== $r->content && \strlen($content) !== fwrite($r->content, $content)) {
420 $chunk = new ErrorChunk($r->offset, new TransportException(\sprintf('Failed writing %d bytes to the response buffer.', \strlen($content))));
421 $r->info['error'] = $chunk->getError();
422 $r->response->cancel();
423 }
424 }
425
426 if (null !== $chunk->getError() || $chunk->isLast()) {
427 $stream = $r->stream;
428 $r->stream = null;
429 unset($asyncMap[$response]);
430 }
431
432 if (null === $chunk->getError()) {
433 $r->offset += \strlen($content);
434
435 yield $r => $chunk;
436
437 if (!$chunk->isLast()) {
438 continue;
439 }
440
441 $stream->next();
442
443 if ($stream->valid()) {
444 throw new \LogicException('A chunk passthru cannot yield after an "isLast()" chunk.');
445 }
446
447 $r->passthru = null;
448 } else {
449 if ($chunk instanceof ErrorChunk) {
450 $chunk->didThrow(false);
451 } else {
452 try {
453 $chunk = new ErrorChunk($chunk->getOffset(), !$chunk->isTimeout() ?: $chunk->getError());
454 } catch (TransportExceptionInterface $e) {
455 $chunk = new ErrorChunk($chunk->getOffset(), $e);
456 }
457 }
458
459 $r->hasThrown = true;
460
461 yield $r => $chunk;
462 $chunk->didThrow() ?: $chunk->getContent();
463 }
464
465 break;
466 }
467 }
468
469 private function openBuffer(): ?\Throwable
470 {
471 if (null === $shouldBuffer = $this->shouldBuffer) {
472 throw new \LogicException('A chunk passthru cannot yield more than one "isFirst()" chunk.');
473 }
474
475 $e = $this->shouldBuffer = null;
476
477 if ($shouldBuffer instanceof \Closure) {
478 try {
479 $shouldBuffer = $shouldBuffer($this->getHeaders(false));
480
481 if (null !== $e = $this->response->getInfo('error')) {
482 throw new TransportException($e);
483 }
484 } catch (\Throwable $e) {
485 $this->info['error'] = $e->getMessage();
486 $this->response->cancel();
487 }
488 }
489
490 if (true === $shouldBuffer) {
491 $this->content = fopen('php://temp', 'w+');
492 } elseif (\is_resource($shouldBuffer)) {
493 $this->content = $shouldBuffer;
494 }
495
496 return $e;
497 }
498
499 private function close(): void
500 {
501 $this->response->cancel();
502 }
503 }