Skip to content

Commit

Permalink
fix: end tracing when receiving last chunk
Browse files Browse the repository at this point in the history
  • Loading branch information
cyve committed Dec 29, 2023
1 parent ff4d2b1 commit 4d4feea
Showing 1 changed file with 21 additions and 12 deletions.
33 changes: 21 additions & 12 deletions src/Http/TracedResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Component\HttpClient\Exception\ServerException;
use Symfony\Component\HttpClient\Response\StreamableInterface;
use Symfony\Component\HttpClient\Response\StreamWrapper;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

Expand Down Expand Up @@ -91,22 +92,21 @@ public function getInfo(string $type = null): mixed
return $this->response->getInfo($type);
}

/**
* Do not end tracing when calling toStream(). It will end when self::stream() will receive the last chunk.
*/
public function toStream(bool $throw = true)
{
try {
if ($throw) {
// Ensure headers arrived
$this->response->getHeaders();
}

if ($this->response instanceof StreamableInterface) {
return $this->stream = $this->response->toStream(false);
}
if ($throw) {
// Ensure headers arrived
$this->response->getHeaders();
}

return $this->stream = StreamWrapper::createResource($this->response);
} finally {
$this->endTracing();
if ($this->response instanceof StreamableInterface) {
return $this->stream = $this->response->toStream(false);
}

return $this->stream = StreamWrapper::createResource($this->response);
}

/**
Expand All @@ -129,6 +129,14 @@ public static function stream(HttpClientInterface $client, iterable $responses,
}

foreach ($client->stream($wrappedResponses, $timeout) as $r => $chunk) {
try {
if ($chunk->isLast() || $chunk->isTimeout()) {
$traceableMap[$r]->endTracing();
}
} catch (TransportExceptionInterface) {
$traceableMap[$r]->endTracing();
}

yield $traceableMap[$r] => $chunk;
}
}
Expand All @@ -150,6 +158,7 @@ protected function endTracing(): void
if (\in_array('response.body', $info['user_data']['span_attributes'] ?? [])) {
if (empty($this->content) && \is_resource($this->stream)) {
$this->content = stream_get_contents($this->stream) ?: null;
rewind($this->stream);
}
$this->span->setAttribute('response.body', $this->content);
}
Expand Down

0 comments on commit 4d4feea

Please sign in to comment.