EventSourceHttpClient.php 5.6 KB

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