Skip to content

[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

Merged
merged 1 commit into from
Aug 6, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Component/HttpClient/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ CHANGELOG
* added support for pausing responses with a new `pause_handler` callable exposed as an info item
* added `StreamableInterface` to ease turning responses into PHP streams
* added `MockResponse::getRequestMethod()` and `getRequestUrl()` to allow inspecting which request has been sent
* added `EventSourceHttpClient` a Server-Sent events stream implementing the [EventSource specification](https://www.w3.org/TR/eventsource/#eventsource)

5.1.0
-----
Expand Down
79 changes: 79 additions & 0 deletions src/Symfony/Component/HttpClient/Chunk/ServerSentEvent.php
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;
}
}
153 changes: 153 additions & 0 deletions src/Symfony/Component/HttpClient/EventSourceHttpClient.php
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
{
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
Copy link
Member

Choose a reason for hiding this comment

The 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 ->connect() receive other chunks than event ones ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, will code using ->connect() receive other chunks than event ones ?

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.

Copy link
Member

@nicolas-grekas nicolas-grekas Jun 12, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, having this implement HttpClientInterface allows streaming both regular requests and event-streams at the same time.

{
$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();

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')));
} 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);
}
$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;
Copy link
Member

Choose a reason for hiding this comment

The 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 ?

Copy link
Member

Choose a reason for hiding this comment

The 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 ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The 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 ServerSentEvent chunk (which parses only full chunks). The full data will be retrieved later by using a Last-Event-Id and there's no need to process it here.

Copy link
Member

Choose a reason for hiding this comment

The 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());
}
}
Loading