EventSourceHttpClient.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. private $reconnectionTime;
  30. public function __construct(HttpClientInterface $client = null, float $reconnectionTime = 10.0)
  31. {
  32. $this->client = $client ?? HttpClient::create();
  33. $this->reconnectionTime = $reconnectionTime;
  34. }
  35. public function connect(string $url, array $options = []): ResponseInterface
  36. {
  37. return $this->request('GET', $url, self::mergeDefaultOptions($options, [
  38. 'buffer' => false,
  39. 'headers' => [
  40. 'Accept' => 'text/event-stream',
  41. 'Cache-Control' => 'no-cache',
  42. ],
  43. ], true));
  44. }
  45. public function request(string $method, string $url, array $options = []): ResponseInterface
  46. {
  47. $state = new class() {
  48. public $buffer = null;
  49. public $lastEventId = null;
  50. public $reconnectionTime;
  51. public $lastError = null;
  52. };
  53. $state->reconnectionTime = $this->reconnectionTime;
  54. if ($accept = self::normalizeHeaders($options['headers'] ?? [])['accept'] ?? []) {
  55. $state->buffer = \in_array($accept, [['Accept: text/event-stream'], ['accept: text/event-stream']], true) ? '' : null;
  56. if (null !== $state->buffer) {
  57. $options['extra']['trace_content'] = false;
  58. }
  59. }
  60. return new AsyncResponse($this->client, $method, $url, $options, static function (ChunkInterface $chunk, AsyncContext $context) use ($state, $method, $url, $options) {
  61. if (null !== $state->buffer) {
  62. $context->setInfo('reconnection_time', $state->reconnectionTime);
  63. $isTimeout = false;
  64. }
  65. $lastError = $state->lastError;
  66. $state->lastError = null;
  67. try {
  68. $isTimeout = $chunk->isTimeout();
  69. if (null !== $chunk->getInformationalStatus() || $context->getInfo('canceled')) {
  70. yield $chunk;
  71. return;
  72. }
  73. } catch (TransportExceptionInterface $e) {
  74. $state->lastError = $lastError ?? microtime(true);
  75. if (null === $state->buffer || ($isTimeout && microtime(true) - $state->lastError < $state->reconnectionTime)) {
  76. yield $chunk;
  77. } else {
  78. $options['headers']['Last-Event-ID'] = $state->lastEventId;
  79. $state->buffer = '';
  80. $state->lastError = microtime(true);
  81. $context->getResponse()->cancel();
  82. $context->replaceRequest($method, $url, $options);
  83. if ($isTimeout) {
  84. yield $chunk;
  85. } else {
  86. $context->pause($state->reconnectionTime);
  87. }
  88. }
  89. return;
  90. }
  91. if ($chunk->isFirst()) {
  92. if (preg_match('/^text\/event-stream(;|$)/i', $context->getHeaders()['content-type'][0] ?? '')) {
  93. $state->buffer = '';
  94. } elseif (null !== $lastError || (null !== $state->buffer && 200 === $context->getStatusCode())) {
  95. 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')));
  96. } else {
  97. $context->passthru();
  98. }
  99. if (null === $lastError) {
  100. yield $chunk;
  101. }
  102. return;
  103. }
  104. $rx = '/((?:\r\n|[\r\n]){2,})/';
  105. $content = $state->buffer.$chunk->getContent();
  106. if ($chunk->isLast()) {
  107. $rx = substr_replace($rx, '|$', -2, 0);
  108. }
  109. $events = preg_split($rx, $content, -1, \PREG_SPLIT_DELIM_CAPTURE);
  110. $state->buffer = array_pop($events);
  111. for ($i = 0; isset($events[$i]); $i += 2) {
  112. $event = new ServerSentEvent($events[$i].$events[1 + $i]);
  113. if ('' !== $event->getId()) {
  114. $context->setInfo('last_event_id', $state->lastEventId = $event->getId());
  115. }
  116. if ($event->getRetry()) {
  117. $context->setInfo('reconnection_time', $state->reconnectionTime = $event->getRetry());
  118. }
  119. yield $event;
  120. }
  121. if (preg_match('/^(?::[^\r\n]*+(?:\r\n|[\r\n]))+$/m', $state->buffer)) {
  122. $content = $state->buffer;
  123. $state->buffer = '';
  124. yield $context->createChunk($content);
  125. }
  126. if ($chunk->isLast()) {
  127. yield $chunk;
  128. }
  129. });
  130. }
  131. }