EventSourceHttpClient.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpClient;
  11. use Symfony\Component\HttpClient\Chunk\ServerSentEvent;
  12. use Symfony\Component\HttpClient\Exception\EventSourceException;
  13. use Symfony\Component\HttpClient\Response\AsyncContext;
  14. use Symfony\Component\HttpClient\Response\AsyncResponse;
  15. use Symfony\Contracts\HttpClient\ChunkInterface;
  16. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  17. use Symfony\Contracts\HttpClient\HttpClientInterface;
  18. use Symfony\Contracts\HttpClient\ResponseInterface;
  19. use Symfony\Contracts\Service\ResetInterface;
  20. /**
  21. * @author Antoine Bluchet <soyuka@gmail.com>
  22. * @author Nicolas Grekas <p@tchwork.com>
  23. */
  24. final class EventSourceHttpClient implements HttpClientInterface, ResetInterface
  25. {
  26. use AsyncDecoratorTrait, HttpClientTrait {
  27. AsyncDecoratorTrait::withOptions insteadof HttpClientTrait;
  28. }
  29. /**
  30. * @var float
  31. */
  32. private $reconnectionTime;
  33. /**
  34. * @param \Symfony\Contracts\HttpClient\HttpClientInterface|null $client
  35. * @param float $reconnectionTime
  36. */
  37. public function __construct($client = null, $reconnectionTime = 10.0)
  38. {
  39. $this->client = $client ?? HttpClient::create();
  40. $this->reconnectionTime = $reconnectionTime;
  41. }
  42. /**
  43. * @param string $url
  44. * @param mixed[] $options
  45. */
  46. public function connect($url, $options = [])
  47. {
  48. return $this->request('GET', $url, self::mergeDefaultOptions($options, [
  49. 'buffer' => false,
  50. 'headers' => [
  51. 'Accept' => 'text/event-stream',
  52. 'Cache-Control' => 'no-cache',
  53. ],
  54. ], true));
  55. }
  56. /**
  57. * @param string $method
  58. * @param string $url
  59. * @param mixed[] $options
  60. */
  61. public function request($method, $url, $options = [])
  62. {
  63. $state = new class() {
  64. /**
  65. * @var string|null
  66. */
  67. public $buffer;
  68. /**
  69. * @var string|null
  70. */
  71. public $lastEventId;
  72. /**
  73. * @var float
  74. */
  75. public $reconnectionTime;
  76. /**
  77. * @var float|null
  78. */
  79. public $lastError;
  80. };
  81. $state->reconnectionTime = $this->reconnectionTime;
  82. if ($accept = self::normalizeHeaders($options['headers'] ?? [])['accept'] ?? []) {
  83. $state->buffer = \in_array($accept, [['Accept: text/event-stream'], ['accept: text/event-stream']], true) ? '' : null;
  84. if (null !== $state->buffer) {
  85. $options['extra']['trace_content'] = false;
  86. }
  87. }
  88. return new AsyncResponse($this->client, $method, $url, $options, static function (ChunkInterface $chunk, AsyncContext $context) use ($state, $method, $url, $options) {
  89. if (null !== $state->buffer) {
  90. $context->setInfo('reconnection_time', $state->reconnectionTime);
  91. $isTimeout = false;
  92. }
  93. $lastError = $state->lastError;
  94. $state->lastError = null;
  95. try {
  96. $isTimeout = $chunk->isTimeout();
  97. if (null !== $chunk->getInformationalStatus() || $context->getInfo('canceled')) {
  98. yield $chunk;
  99. return;
  100. }
  101. } catch (TransportExceptionInterface $exception) {
  102. $state->lastError = $lastError ?? microtime(true);
  103. if (null === $state->buffer || ($isTimeout && microtime(true) - $state->lastError < $state->reconnectionTime)) {
  104. yield $chunk;
  105. } else {
  106. $options['headers']['Last-Event-ID'] = $state->lastEventId;
  107. $state->buffer = '';
  108. $state->lastError = microtime(true);
  109. $context->getResponse()->cancel();
  110. $context->replaceRequest($method, $url, $options);
  111. if ($isTimeout) {
  112. yield $chunk;
  113. } else {
  114. $context->pause($state->reconnectionTime);
  115. }
  116. }
  117. return;
  118. }
  119. if ($chunk->isFirst()) {
  120. if (preg_match('/^text\/event-stream(;|$)/i', $context->getHeaders()['content-type'][0] ?? '')) {
  121. $state->buffer = '';
  122. } elseif (null !== $lastError || (null !== $state->buffer && 200 === $context->getStatusCode())) {
  123. throw new EventSourceException(sprintf('Response content-type is "%s" while "text/event-stream" was expected for "%s".', $context->getHeaders()['content-type'][0] ?? '', $context->getInfo('url')));
  124. } else {
  125. $context->passthru();
  126. }
  127. if (null === $lastError) {
  128. yield $chunk;
  129. }
  130. return;
  131. }
  132. $rx = '/((?:\r\n|[\r\n]){2,})/';
  133. $content = $state->buffer.$chunk->getContent();
  134. if ($chunk->isLast()) {
  135. $rx = substr_replace($rx, '|$', -2, 0);
  136. }
  137. $events = preg_split($rx, $content, -1, \PREG_SPLIT_DELIM_CAPTURE);
  138. $state->buffer = array_pop($events);
  139. for ($i = 0; isset($events[$i]); $i += 2) {
  140. $event = new ServerSentEvent($events[$i].$events[1 + $i]);
  141. if ('' !== $event->getId()) {
  142. $context->setInfo('last_event_id', $state->lastEventId = $event->getId());
  143. }
  144. if ($event->getRetry()) {
  145. $context->setInfo('reconnection_time', $state->reconnectionTime = $event->getRetry());
  146. }
  147. yield $event;
  148. }
  149. if (preg_match('/^(?::[^\r\n]*+(?:\r\n|[\r\n]))+$/m', $state->buffer)) {
  150. $content = $state->buffer;
  151. $state->buffer = '';
  152. yield $context->createChunk($content);
  153. }
  154. if ($chunk->isLast()) {
  155. yield $chunk;
  156. }
  157. });
  158. }
  159. }