-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[HttpClient] add EventSourceHttpClient to consume Server-Sent Events #36692
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Component\HttpClient\Chunk; | ||
|
||
use Symfony\Contracts\HttpClient\ChunkInterface; | ||
|
||
/** | ||
* @author Antoine Bluchet <soyuka@gmail.com> | ||
* @author Nicolas Grekas <p@tchwork.com> | ||
*/ | ||
final class ServerSentEvent extends DataChunk implements ChunkInterface | ||
{ | ||
private $data = ''; | ||
private $id = ''; | ||
private $type = 'message'; | ||
private $retry = 0; | ||
|
||
public function __construct(string $content) | ||
{ | ||
parent::__construct(-1, $content); | ||
|
||
// remove BOM | ||
if (0 === strpos($content, "\xEF\xBB\xBF")) { | ||
$content = substr($content, 3); | ||
} | ||
|
||
foreach (preg_split("/(?:\r\n|[\r\n])/", $content) as $line) { | ||
if (0 === $i = strpos($line, ':')) { | ||
continue; | ||
} | ||
|
||
$i = false === $i ? \strlen($line) : $i; | ||
$field = substr($line, 0, $i); | ||
$i += 1 + (' ' === ($line[1 + $i] ?? '')); | ||
|
||
switch ($field) { | ||
case 'id': $this->id = substr($line, $i); break; | ||
case 'event': $this->type = substr($line, $i); break; | ||
case 'data': $this->data .= ('' === $this->data ? '' : "\n").substr($line, $i); break; | ||
case 'retry': | ||
$retry = substr($line, $i); | ||
|
||
if ('' !== $retry && \strlen($retry) === strspn($retry, '0123456789')) { | ||
$this->retry = $retry / 1000.0; | ||
} | ||
break; | ||
} | ||
} | ||
} | ||
|
||
public function getId(): string | ||
{ | ||
return $this->id; | ||
} | ||
|
||
public function getType(): string | ||
{ | ||
return $this->type; | ||
} | ||
|
||
public function getData(): string | ||
{ | ||
return $this->data; | ||
} | ||
|
||
public function getRetry(): float | ||
{ | ||
return $this->retry; | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,153 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Component\HttpClient; | ||
|
||
use Symfony\Component\HttpClient\Chunk\ServerSentEvent; | ||
use Symfony\Component\HttpClient\Exception\EventSourceException; | ||
use Symfony\Component\HttpClient\Response\AsyncContext; | ||
use Symfony\Component\HttpClient\Response\AsyncResponse; | ||
use Symfony\Contracts\HttpClient\ChunkInterface; | ||
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; | ||
use Symfony\Contracts\HttpClient\HttpClientInterface; | ||
use Symfony\Contracts\HttpClient\ResponseInterface; | ||
|
||
/** | ||
* @author Antoine Bluchet <soyuka@gmail.com> | ||
* @author Nicolas Grekas <p@tchwork.com> | ||
*/ | ||
final class EventSourceHttpClient implements HttpClientInterface | ||
soyuka marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
use AsyncDecoratorTrait; | ||
use HttpClientTrait; | ||
|
||
private $reconnectionTime; | ||
|
||
public function __construct(HttpClientInterface $client = null, float $reconnectionTime = 10.0) | ||
{ | ||
$this->client = $client ?? HttpClient::create(); | ||
$this->reconnectionTime = $reconnectionTime; | ||
} | ||
|
||
public function connect(string $url, array $options = []): ResponseInterface | ||
{ | ||
return $this->request('GET', $url, self::mergeDefaultOptions($options, [ | ||
'buffer' => false, | ||
'headers' => [ | ||
'Accept' => 'text/event-stream', | ||
'Cache-Control' => 'no-cache', | ||
], | ||
], true)); | ||
} | ||
|
||
public function request(string $method, string $url, array $options = []): ResponseInterface | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm wondering whether it make sense for an EventSource implementation to still be a full HttpClient as well. Shouldn't it use a client inside it (a special one) instead ? Also, will code using There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Yes it does, full power to the end-user. As the API exposed here is rather low-level, having a full HttpClient makes things easier. Also, wrapping a special client inside a new class would add a rather useless class to this component in my opinion. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Also, having this implement |
||
{ | ||
$state = new class() { | ||
public $buffer = null; | ||
public $lastEventId = null; | ||
public $reconnectionTime; | ||
public $lastError = null; | ||
}; | ||
$state->reconnectionTime = $this->reconnectionTime; | ||
|
||
if ($accept = self::normalizeHeaders($options['headers'] ?? [])['accept'] ?? []) { | ||
$state->buffer = \in_array($accept, [['Accept: text/event-stream'], ['accept: text/event-stream']], true) ? '' : null; | ||
} | ||
|
||
return new AsyncResponse($this->client, $method, $url, $options, static function (ChunkInterface $chunk, AsyncContext $context) use ($state, $method, $url, $options) { | ||
if (null !== $state->buffer) { | ||
$context->setInfo('reconnection_time', $state->reconnectionTime); | ||
$isTimeout = false; | ||
} | ||
$lastError = $state->lastError; | ||
$state->lastError = null; | ||
|
||
try { | ||
$isTimeout = $chunk->isTimeout(); | ||
nicolas-grekas marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
if (null !== $chunk->getInformationalStatus()) { | ||
yield $chunk; | ||
|
||
return; | ||
} | ||
} catch (TransportExceptionInterface $e) { | ||
$state->lastError = $lastError ?? microtime(true); | ||
|
||
if (null === $state->buffer || ($isTimeout && microtime(true) - $state->lastError < $state->reconnectionTime)) { | ||
yield $chunk; | ||
} else { | ||
$options['headers']['Last-Event-ID'] = $state->lastEventId; | ||
$state->buffer = ''; | ||
$state->lastError = microtime(true); | ||
$context->getResponse()->cancel(); | ||
$context->replaceRequest($method, $url, $options); | ||
if ($isTimeout) { | ||
yield $chunk; | ||
} else { | ||
$context->pause($state->reconnectionTime); | ||
} | ||
} | ||
|
||
return; | ||
} | ||
|
||
if ($chunk->isFirst()) { | ||
if (preg_match('/^text\/event-stream(;|$)/i', $context->getHeaders()['content-type'][0] ?? '')) { | ||
$state->buffer = ''; | ||
} elseif (null !== $lastError || (null !== $state->buffer && 200 === $context->getStatusCode())) { | ||
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'))); | ||
nicolas-grekas marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} else { | ||
$context->passthru(); | ||
} | ||
|
||
if (null === $lastError) { | ||
yield $chunk; | ||
} | ||
|
||
return; | ||
} | ||
|
||
$rx = '/((?:\r\n|[\r\n]){2,})/'; | ||
$content = $state->buffer.$chunk->getContent(); | ||
|
||
if ($chunk->isLast()) { | ||
$rx = substr_replace($rx, '|$', -2, 0); | ||
nicolas-grekas marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
$events = preg_split($rx, $content, -1, PREG_SPLIT_DELIM_CAPTURE); | ||
$state->buffer = array_pop($events); | ||
|
||
for ($i = 0; isset($events[$i]); $i += 2) { | ||
$event = new ServerSentEvent($events[$i].$events[1 + $i]); | ||
|
||
if ('' !== $event->getId()) { | ||
$context->setInfo('last_event_id', $state->lastEventId = $event->getId()); | ||
} | ||
|
||
if ($event->getRetry()) { | ||
$context->setInfo('reconnection_time', $state->reconnectionTime = $event->getRetry()); | ||
} | ||
|
||
yield $event; | ||
} | ||
|
||
if (preg_match('/^(?::[^\r\n]*+(?:\r\n|[\r\n]))+$/m', $state->buffer)) { | ||
$content = $state->buffer; | ||
$state->buffer = ''; | ||
|
||
yield $context->createChunk($content); | ||
} | ||
|
||
if ($chunk->isLast()) { | ||
yield $chunk; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. is it possible for the last chunk to have a non-empty content ? If yes, shouldn't we recreate a new last chunk instead, excluding the content we processed for new chunks ? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. also, is it possible to reach the last chunk with some remaining buffered content in the state ? and what happens in that case ? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'd say that it's not really a problem and if the last chunk is partial content it won't be transformed as a There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The last chunk is always empty so that's OK. About the remaining data in the buffer, L122 above ensures it's always emptied when the last chunk arrives. |
||
} | ||
}); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Component\HttpClient\Exception; | ||
|
||
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface; | ||
|
||
/** | ||
* @author Nicolas Grekas <p@tchwork.com> | ||
*/ | ||
final class EventSourceException extends \RuntimeException implements DecodingExceptionInterface | ||
{ | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Component\HttpClient\Tests\Chunk; | ||
|
||
use PHPUnit\Framework\TestCase; | ||
use Symfony\Component\HttpClient\Chunk\ServerSentEvent; | ||
|
||
/** | ||
* @author Antoine Bluchet <soyuka@gmail.com> | ||
*/ | ||
class ServerSentEventTest extends TestCase | ||
{ | ||
public function testParse() | ||
{ | ||
$rawData = <<<STR | ||
data: test | ||
data:test | ||
id: 12 | ||
event: testEvent | ||
|
||
STR; | ||
|
||
$sse = new ServerSentEvent($rawData); | ||
$this->assertSame("test\ntest", $sse->getData()); | ||
$this->assertSame('12', $sse->getId()); | ||
$this->assertSame('testEvent', $sse->getType()); | ||
} | ||
|
||
public function testParseValid() | ||
{ | ||
$rawData = <<<STR | ||
event: testEvent | ||
data | ||
|
||
STR; | ||
|
||
$sse = new ServerSentEvent($rawData); | ||
$this->assertSame('', $sse->getData()); | ||
$this->assertSame('', $sse->getId()); | ||
$this->assertSame('testEvent', $sse->getType()); | ||
} | ||
|
||
public function testParseRetry() | ||
{ | ||
$rawData = <<<STR | ||
retry: 12 | ||
STR; | ||
$sse = new ServerSentEvent($rawData); | ||
$this->assertSame('', $sse->getData()); | ||
$this->assertSame('', $sse->getId()); | ||
$this->assertSame('message', $sse->getType()); | ||
$this->assertSame(0.012, $sse->getRetry()); | ||
} | ||
|
||
public function testParseNewLine() | ||
{ | ||
$rawData = <<<STR | ||
|
||
|
||
data: <tag> | ||
data | ||
data: <foo /> | ||
data: | ||
data: | ||
data: </tag> | ||
STR; | ||
$sse = new ServerSentEvent($rawData); | ||
$this->assertSame("<tag>\n\n <foo />\n\n\n</tag>", $sse->getData()); | ||
} | ||
} |
Uh oh!
There was an error while loading. Please reload this page.