-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[HttpFoundation] Streamlining server event streaming #58743
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
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
110 changes: 110 additions & 0 deletions
110
src/Symfony/Component/HttpFoundation/EventStreamResponse.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
<?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\HttpFoundation; | ||
|
||
/** | ||
* Represents a streaming HTTP response for sending server events | ||
* as part of the Server-Sent Events (SSE) streaming technique. | ||
* | ||
* To broadcast events to multiple users at once, for long-running | ||
* connections and for high-traffic websites, prefer using the Mercure | ||
* Symfony Component, which relies on Software designed for these use | ||
* cases: https://symfony.com/doc/current/mercure.html | ||
* | ||
* @see ServerEvent | ||
* | ||
* @author Yonel Ceruto <open@yceruto.dev> | ||
* | ||
* Example usage: | ||
* | ||
* return new EventStreamResponse(function () { | ||
* yield new ServerEvent(time()); | ||
* | ||
* sleep(1); | ||
* | ||
* yield new ServerEvent(time()); | ||
* }); | ||
*/ | ||
class EventStreamResponse extends StreamedResponse | ||
{ | ||
/** | ||
* @param int|null $retry The number of milliseconds the client should wait | ||
* before reconnecting in case of network failure | ||
*/ | ||
public function __construct(?callable $callback = null, int $status = 200, array $headers = [], private ?int $retry = null) | ||
{ | ||
$headers += [ | ||
'Connection' => 'keep-alive', | ||
yceruto marked this conversation as resolved.
Show resolved
Hide resolved
|
||
'Content-Type' => 'text/event-stream', | ||
'Cache-Control' => 'private, no-cache, no-store, must-revalidate, max-age=0', | ||
'X-Accel-Buffering' => 'no', | ||
'Pragma' => 'no-cache', | ||
'Expire' => '0', | ||
]; | ||
|
||
parent::__construct($callback, $status, $headers); | ||
} | ||
|
||
public function setCallback(callable $callback): static | ||
{ | ||
if ($this->callback) { | ||
return parent::setCallback($callback); | ||
} | ||
|
||
$this->callback = function () use ($callback) { | ||
if (is_iterable($events = $callback($this))) { | ||
foreach ($events as $event) { | ||
$this->sendEvent($event); | ||
|
||
if (connection_aborted()) { | ||
break; | ||
} | ||
} | ||
} | ||
}; | ||
|
||
return $this; | ||
} | ||
|
||
/** | ||
* Sends a server event to the client. | ||
* | ||
* @return $this | ||
*/ | ||
public function sendEvent(ServerEvent $event): static | ||
{ | ||
if ($this->retry > 0 && !$event->getRetry()) { | ||
$event->setRetry($this->retry); | ||
} | ||
|
||
foreach ($event as $part) { | ||
echo $part; | ||
|
||
if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true)) { | ||
static::closeOutputBuffers(0, true); | ||
flush(); | ||
} | ||
} | ||
|
||
return $this; | ||
} | ||
|
||
public function getRetry(): ?int | ||
{ | ||
return $this->retry; | ||
} | ||
|
||
public function setRetry(int $retry): void | ||
{ | ||
$this->retry = $retry; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,147 @@ | ||
<?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\HttpFoundation; | ||
|
||
/** | ||
* An event generated on the server intended for streaming to the client | ||
* as part of the SSE streaming technique. | ||
* | ||
* @implements \IteratorAggregate<string> | ||
* | ||
* @author Yonel Ceruto <open@yceruto.dev> | ||
*/ | ||
class ServerEvent implements \IteratorAggregate | ||
{ | ||
/** | ||
* @param string|iterable<string> $data The event data field for the message | ||
* @param string|null $type The event type | ||
* @param int|null $retry The number of milliseconds the client should wait | ||
* before reconnecting in case of network failure | ||
* @param string|null $id The event ID to set the EventSource object's last event ID value | ||
* @param string|null $comment The event comment | ||
*/ | ||
public function __construct( | ||
private string|iterable $data, | ||
private ?string $type = null, | ||
private ?int $retry = null, | ||
private ?string $id = null, | ||
private ?string $comment = null, | ||
) { | ||
} | ||
|
||
public function getData(): iterable|string | ||
{ | ||
return $this->data; | ||
} | ||
|
||
/** | ||
* @return $this | ||
*/ | ||
public function setData(iterable|string $data): static | ||
{ | ||
$this->data = $data; | ||
|
||
return $this; | ||
} | ||
|
||
public function getType(): ?string | ||
{ | ||
return $this->type; | ||
} | ||
|
||
/** | ||
* @return $this | ||
*/ | ||
public function setType(string $type): static | ||
{ | ||
$this->type = $type; | ||
|
||
return $this; | ||
} | ||
|
||
public function getRetry(): ?int | ||
{ | ||
return $this->retry; | ||
} | ||
|
||
/** | ||
* @return $this | ||
*/ | ||
public function setRetry(?int $retry): static | ||
{ | ||
$this->retry = $retry; | ||
|
||
return $this; | ||
} | ||
|
||
public function getId(): ?string | ||
{ | ||
return $this->id; | ||
} | ||
|
||
/** | ||
* @return $this | ||
*/ | ||
public function setId(string $id): static | ||
{ | ||
$this->id = $id; | ||
|
||
return $this; | ||
} | ||
|
||
public function getComment(): ?string | ||
{ | ||
return $this->comment; | ||
} | ||
|
||
public function setComment(string $comment): static | ||
{ | ||
$this->comment = $comment; | ||
|
||
return $this; | ||
} | ||
|
||
/** | ||
* @return \Traversable<string> | ||
*/ | ||
public function getIterator(): \Traversable | ||
{ | ||
static $lastRetry = null; | ||
|
||
$head = ''; | ||
if ($this->comment) { | ||
$head .= \sprintf(': %s', $this->comment)."\n"; | ||
} | ||
if ($this->id) { | ||
$head .= \sprintf('id: %s', $this->id)."\n"; | ||
} | ||
if ($this->retry > 0 && $this->retry !== $lastRetry) { | ||
$head .= \sprintf('retry: %s', $lastRetry = $this->retry)."\n"; | ||
} | ||
if ($this->type) { | ||
$head .= \sp 6D47 rintf('event: %s', $this->type)."\n"; | ||
} | ||
yield $head; | ||
|
||
if ($this->data) { | ||
if (is_iterable($this->data)) { | ||
foreach ($this->data as $data) { | ||
yield \sprintf('data: %s', $data)."\n"; | ||
} | ||
} else { | ||
yield \sprintf('data: %s', $this->data)."\n"; | ||
} | ||
} | ||
|
||
yield "\n"; | ||
} | ||
} |
127 changes: 127 additions & 0 deletions
127
src/Symfony/Component/HttpFoundation/Tests/EventStreamResponseTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,127 @@ | ||
<?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\HttpFoundation\Tests; | ||
|
||
use PHPUnit\Framework\TestCase; | 9E81||
use Symfony\Component\HttpFoundation\EventStreamResponse; | ||
use Symfony\Component\HttpFoundation\ServerEvent; | ||
|
||
class EventStreamResponseTest extends TestCase | ||
{ | ||
public function testInitializationWithDefaultValues() | ||
{ | ||
$response = new EventStreamResponse(); | ||
|
||
$this->assertSame('text/event-stream', $response->headers->get('content-type')); | ||
$this->assertSame('max-age=0, must-revalidate, no-cache, no-store, private', $response->headers->get('cache-control')); | ||
$this->assertSame('keep-alive', $response->headers->get('connection')); | ||
|
||
$this->assertSame(200, $response->getStatusCode()); | ||
$this->assertNull($response->getRetry()); | ||
} | ||
|
||
public function testStreamSingleEvent() | ||
{ | ||
$response = new EventStreamResponse(function () { | ||
yield new ServerEvent( | ||
data: 'foo', | ||
type: 'bar', | ||
retry: 100, | ||
id: '1', | ||
comment: 'bla bla', | ||
); | ||
}); | ||
|
||
$expected = <<<STR | ||
: bla bla | ||
id: 1 | ||
retry: 100 | ||
event: bar | ||
data: foo | ||
|
||
|
||
STR; | ||
|
||
$this->assertSameResponseContent($expected, $response); | ||
} | ||
|
||
public function testStreamEventsAndData() | ||
{ | ||
$data = static function (): iterable { | ||
yield 'first line'; | ||
yield 'second line'; | ||
yield 'third line'; | ||
}; | ||
|
||
$response = new EventStreamResponse(function () use ($data) { | ||
yield new ServerEvent('single line'); | ||
yield new ServerEvent(['first line', 'second line']); | ||
yield new ServerEvent($data()); | ||
}); | ||
|
||
$expected = <<<STR | ||
data: single line | ||
|
||
data: first line | ||
data: second line | ||
|
||
data: first line | ||
data: second line | ||
data: third line | ||
|
||
|
||
STR; | ||
|
||
$this->assertSameResponseContent($expected, $response); | ||
} | ||
|
||
public function testStreamEventsWithRetryFallback() | ||
{ | ||
$response = new EventStreamResponse(function () { | ||
yield new ServerEvent('foo'); | ||
yield new ServerEvent('bar'); | ||
yield new ServerEvent('baz', retry: 1000); | ||
}, retry: 1500); | ||
|
||
$expected = <<<STR | ||
retry: 1500 | ||
data: foo | ||
|
||
data: bar | ||
|
||
retry: 1000 | ||
data: baz | ||
|
||
|
||
STR; | ||
|
||
$this->assertSameResponseContent($expected, $response); | ||
} | ||
|
||
public function testStreamEventWithSendMethod() | ||
{ | ||
$response = new EventStreamResponse(function (EventStreamResponse $response) { | ||
$response->sendEvent(new ServerEvent('foo')); | ||
}); | ||
|
||
$this->assertSameResponseContent("data: foo\n\n", $response); | ||
} | ||
|
||
private function assertSameResponseContent(string $expected, EventStreamResponse $response): void | ||
{ | ||
ob_start(); | ||
$response->send(); | ||
$actual = ob_get_clean(); | ||
|
||
$this->assertSame($expected, $actual); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.