-
Notifications
You must be signed in to change notification settings - Fork 2k
feat: SSEResponse class for streaming Server-Side Events
#9931
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
base: 4.8
Are you sure you want to change the base?
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,22 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| /** | ||
| * This file is part of CodeIgniter 4 framework. | ||
| * | ||
| * (c) CodeIgniter Foundation <admin@codeigniter.com> | ||
| * | ||
| * For the full copyright and license information, please view | ||
| * the LICENSE file that was distributed with this source code. | ||
| */ | ||
|
|
||
| namespace CodeIgniter\HTTP; | ||
|
|
||
| /** | ||
| * Marker interface for responses that bypass output buffering | ||
| * and send their body directly to the client (e.g. downloads, SSE streams). | ||
| */ | ||
| interface NonBufferedResponseInterface | ||
| { | ||
| } |
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,205 @@ | ||||||
| <?php | ||||||
|
|
||||||
| declare(strict_types=1); | ||||||
|
|
||||||
| /** | ||||||
| * This file is part of CodeIgniter 4 framework. | ||||||
| * | ||||||
| * (c) CodeIgniter Foundation <admin@codeigniter.com> | ||||||
| * | ||||||
| * For the full copyright and license information, please view | ||||||
| * the LICENSE file that was distributed with this source code. | ||||||
| */ | ||||||
|
|
||||||
| namespace CodeIgniter\HTTP; | ||||||
|
|
||||||
| use Closure; | ||||||
| use Config\App; | ||||||
| use JsonException; | ||||||
|
|
||||||
| /** | ||||||
| * HTTP response for Server-Sent Events (SSE) streaming. | ||||||
| * | ||||||
| * @see \CodeIgniter\HTTP\SSEResponseTest | ||||||
| */ | ||||||
| class SSEResponse extends Response implements NonBufferedResponseInterface | ||||||
| { | ||||||
| /** | ||||||
| * Constructor. | ||||||
| * | ||||||
| * @param Closure(SSEResponse): void $callback | ||||||
| */ | ||||||
| public function __construct(private readonly Closure $callback) | ||||||
| { | ||||||
| parent::__construct(config(App::class)); | ||||||
| } | ||||||
|
|
||||||
| /** | ||||||
| * Send an SSE event to the client. | ||||||
| * | ||||||
| * @param array<string, mixed>|string $data Event data (arrays are JSON-encoded) | ||||||
| * @param string|null $event Event type | ||||||
| * @param string|null $id Event ID | ||||||
| */ | ||||||
| public function event(array|string $data, ?string $event = null, ?string $id = null): bool | ||||||
| { | ||||||
| if ($this->isConnectionAborted()) { | ||||||
| return false; | ||||||
| } | ||||||
|
|
||||||
| $output = ''; | ||||||
|
|
||||||
| if ($event !== null) { | ||||||
| $output .= 'event: ' . $this->sanitizeLine($event) . "\n"; | ||||||
| } | ||||||
|
|
||||||
| if ($id !== null) { | ||||||
| $output .= 'id: ' . $this->sanitizeLine($id) . "\n"; | ||||||
| } | ||||||
|
|
||||||
| if (is_array($data)) { | ||||||
| try { | ||||||
| $data = json_encode($data, JSON_THROW_ON_ERROR); | ||||||
| } catch (JsonException $e) { | ||||||
| log_message('error', 'SSE JSON encode failed: {message}', ['message' => $e->getMessage()]); | ||||||
|
|
||||||
| return false; | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| $output .= $this->formatMultiline('data', $data); | ||||||
|
|
||||||
| return $this->write($output); | ||||||
| } | ||||||
|
|
||||||
| /** | ||||||
| * Send an SSE comment (useful for keep-alive). | ||||||
| */ | ||||||
| public function comment(string $text): bool | ||||||
| { | ||||||
| if ($this->isConnectionAborted()) { | ||||||
| return false; | ||||||
| } | ||||||
|
|
||||||
| return $this->write($this->formatMultiline('', $text)); | ||||||
| } | ||||||
|
|
||||||
| /** | ||||||
| * Set the client reconnection interval. | ||||||
| * | ||||||
| * @param int $milliseconds Retry interval in milliseconds | ||||||
| */ | ||||||
| public function retry(int $milliseconds): bool | ||||||
| { | ||||||
| if ($this->isConnectionAborted()) { | ||||||
| return false; | ||||||
| } | ||||||
|
|
||||||
| return $this->write("retry: {$milliseconds}\n\n"); | ||||||
| } | ||||||
|
|
||||||
| /** | ||||||
| * Check if the client connection has been lost. | ||||||
| */ | ||||||
| private function isConnectionAborted(): bool | ||||||
| { | ||||||
| return connection_status() !== CONNECTION_NORMAL || connection_aborted() === 1; | ||||||
| } | ||||||
|
|
||||||
| /** | ||||||
| * Strip newlines from a single-line SSE field (event, id). | ||||||
| */ | ||||||
| private function sanitizeLine(string $value): string | ||||||
| { | ||||||
| return str_replace(["\r\n", "\r", "\n"], '', $value); | ||||||
| } | ||||||
|
|
||||||
| /** | ||||||
| * Format a value as prefixed SSE lines, normalizing line endings. | ||||||
| * | ||||||
| * Each line becomes "{prefix}: {line}\n", terminated by an extra "\n". | ||||||
| */ | ||||||
| private function formatMultiline(string $prefix, string $value): string | ||||||
| { | ||||||
| $value = str_replace(["\r\n", "\r"], "\n", $value); | ||||||
| $output = ''; | ||||||
|
|
||||||
| foreach (explode("\n", $value) as $line) { | ||||||
| $output .= ($prefix !== '' ? "{$prefix}: " : ': ') . $line . "\n"; | ||||||
| } | ||||||
|
|
||||||
| return $output . "\n"; | ||||||
| } | ||||||
|
|
||||||
| /** | ||||||
| * Write raw SSE output and flush. | ||||||
| */ | ||||||
| private function write(string $output): bool | ||||||
|
Contributor
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.
Suggested change
Member
Author
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. Again, I can't imagine a legitimate scenario where this may be handy. If a concrete need comes up later, promoting private to protected is a non-breaking change. Going the other direction isn't. |
||||||
| { | ||||||
| echo $output; | ||||||
|
|
||||||
| if (ENVIRONMENT !== 'testing') { | ||||||
| if (ob_get_level() > 0) { | ||||||
| ob_flush(); | ||||||
| } | ||||||
|
|
||||||
| flush(); | ||||||
| } | ||||||
|
|
||||||
| return true; | ||||||
| } | ||||||
|
|
||||||
| /** | ||||||
| * {@inheritDoc} | ||||||
| * | ||||||
| * @return $this | ||||||
| */ | ||||||
| public function send() | ||||||
| { | ||||||
| // Turn off output buffering completely, even if php.ini output_buffering is not off | ||||||
| if (ENVIRONMENT !== 'testing') { | ||||||
| set_time_limit(0); | ||||||
| ini_set('zlib.output_compression', 'Off'); | ||||||
|
|
||||||
| while (ob_get_level() > 0) { | ||||||
| ob_end_clean(); | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| // Close session if active to prevent blocking other requests | ||||||
| if (session_status() === PHP_SESSION_ACTIVE) { | ||||||
| session_write_close(); | ||||||
| } | ||||||
|
|
||||||
| $this->setContentType('text/event-stream', 'UTF-8'); | ||||||
| $this->removeHeader('Cache-Control'); | ||||||
| $this->setHeader('Cache-Control', 'no-cache'); | ||||||
| $this->setHeader('Content-Encoding', 'identity'); | ||||||
| $this->setHeader('X-Accel-Buffering', 'no'); | ||||||
michalsn marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
|
||||||
| // Connection: keep-alive is only valid for HTTP/1.x | ||||||
| if (version_compare($this->getProtocolVersion(), '2.0', '<')) { | ||||||
| $this->setHeader('Connection', 'keep-alive'); | ||||||
| } | ||||||
|
|
||||||
| // Intentionally skip CSP finalize: no HTML/JS execution in SSE streams. | ||||||
| $this->sendHeaders(); | ||||||
| $this->sendCookies(); | ||||||
|
|
||||||
| ($this->callback)($this); | ||||||
|
|
||||||
| return $this; | ||||||
| } | ||||||
|
|
||||||
| /** | ||||||
| * {@inheritDoc} | ||||||
| * | ||||||
| * No-op — body is streamed via the callback, not stored. | ||||||
| * | ||||||
| * @return $this | ||||||
| */ | ||||||
| public function sendBody() | ||||||
| { | ||||||
| return $this; | ||||||
| } | ||||||
| } | ||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| /** | ||
| * This file is part of CodeIgniter 4 framework. | ||
| * | ||
| * (c) CodeIgniter Foundation <admin@codeigniter.com> | ||
| * | ||
| * For the full copyright and license information, please view | ||
| * the LICENSE file that was distributed with this source code. | ||
| */ | ||
|
|
||
| namespace CodeIgniter\HTTP; | ||
|
|
||
| use CodeIgniter\Test\CIUnitTestCase; | ||
| use PHPUnit\Framework\Attributes\Group; | ||
| use PHPUnit\Framework\Attributes\PreserveGlobalState; | ||
| use PHPUnit\Framework\Attributes\RunInSeparateProcess; | ||
| use PHPUnit\Framework\Attributes\WithoutErrorHandler; | ||
|
|
||
| /** | ||
| * @internal | ||
| */ | ||
| #[Group('SeparateProcess')] | ||
| final class SSEResponseSendTest extends CIUnitTestCase | ||
| { | ||
| #[PreserveGlobalState(false)] | ||
| #[RunInSeparateProcess] | ||
| #[WithoutErrorHandler] | ||
| public function testSendEmitsHeadersCookiesAndStream(): void | ||
| { | ||
| $response = new SSEResponse(static function (SSEResponse $sse): void { | ||
| $sse->event('hello'); | ||
| }); | ||
| $response->pretend(false); | ||
| $response->setCookie('foo', 'bar'); | ||
|
|
||
| ob_start(); | ||
| $response->send(); | ||
| $output = ob_get_clean(); | ||
|
|
||
| $this->assertSame("data: hello\n\n", $output); | ||
| $this->assertHeaderEmitted('Content-Type: text/event-stream; charset=UTF-8'); | ||
| $this->assertHeaderEmitted('Cache-Control: no-cache'); | ||
| $this->assertHeaderEmitted('X-Accel-Buffering: no'); | ||
| $this->assertHeaderEmitted('Set-Cookie: foo=bar;'); | ||
|
|
||
| if (version_compare($response->getProtocolVersion(), '2.0', '<')) { | ||
| $this->assertHeaderEmitted('Connection: keep-alive'); | ||
| } else { | ||
| $this->assertHeaderNotEmitted('Connection: keep-alive'); | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
formatMultiline()andwrite()appear to be natural extensionboundaries (I/O and formatting).
Would making them
protectedhelp avoid duplication or frameworkforking when custom SSE behavior is needed?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Formatting methods are dictated by the spec, not by application needs. I don't see a scenario where this would need modification.