Skip to content

Commit 9ba3fe7

Browse files
committed
feat: add StreamResponse and SSE response factories
1 parent 18ee79c commit 9ba3fe7

12 files changed

Lines changed: 514 additions & 80 deletions

File tree

‎system/HTTP/ResponseTrait.php‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
namespace CodeIgniter\HTTP;
1515

16+
use Closure;
1617
use CodeIgniter\Config\Services;
1718
use CodeIgniter\Cookie\Cookie;
1819
use CodeIgniter\Cookie\CookieStore;
@@ -810,6 +811,29 @@ public function download(string $filename = '', $data = '', bool $setMime = fals
810811
return $response;
811812
}
812813

814+
/**
815+
* Creates a response that streams its body to the client as it is
816+
* generated, instead of buffering the complete body first.
817+
*
818+
* @param (Closure(StreamResponse): void)|iterable<string> $callbackOrChunks A callback that
819+
* streams output via write(), or an iterable of
820+
* string chunks to be written in order
821+
*/
822+
public function stream(Closure|iterable $callbackOrChunks): StreamResponse
823+
{
824+
return new StreamResponse($callbackOrChunks);
825+
}
826+
827+
/**
828+
* Creates a response for streaming Server-Sent Events (SSE).
829+
*
830+
* @param Closure(SSEResponse): void $callback
831+
*/
832+
public function eventStream(Closure $callback): SSEResponse
833+
{
834+
return new SSEResponse($callback);
835+
}
836+
813837
public function getCSP(): ContentSecurityPolicy
814838
{
815839
$this->CSP ??= service('csp');

‎system/HTTP/SSEResponse.php‎

Lines changed: 7 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,16 @@
2121
*
2222
* @see \CodeIgniter\HTTP\SSEResponseTest
2323
*/
24-
class SSEResponse extends Response implements NonBufferedResponseInterface
24+
class SSEResponse extends StreamResponse
2525
{
2626
/**
2727
* Constructor.
2828
*
2929
* @param Closure(SSEResponse): void $callback
3030
*/
31-
public function __construct(private readonly Closure $callback)
31+
public function __construct(Closure $callback)
3232
{
33-
parent::__construct();
33+
parent::__construct($callback);
3434
}
3535

3636
/**
@@ -42,7 +42,7 @@ public function __construct(private readonly Closure $callback)
4242
*/
4343
public function event(array|string $data, ?string $event = null, ?string $id = null): bool
4444
{
45-
if ($this->isConnectionAborted()) {
45+
if (! $this->isClientConnected()) {
4646
return false;
4747
}
4848

@@ -76,10 +76,6 @@ public function event(array|string $data, ?string $event = null, ?string $id = n
7676
*/
7777
public function comment(string $text): bool
7878
{
79-
if ($this->isConnectionAborted()) {
80-
return false;
81-
}
82-
8379
return $this->write($this->formatMultiline('', $text));
8480
}
8581

@@ -90,21 +86,9 @@ public function comment(string $text): bool
9086
*/
9187
public function retry(int $milliseconds): bool
9288
{
93-
if ($this->isConnectionAborted()) {
94-
return false;
95-
}
96-
9789
return $this->write("retry: {$milliseconds}\n\n");
9890
}
9991

100-
/**
101-
* Check if the client connection has been lost.
102-
*/
103-
private function isConnectionAborted(): bool
104-
{
105-
return connection_status() !== CONNECTION_NORMAL || connection_aborted() === 1;
106-
}
107-
10892
/**
10993
* Strip newlines from a single-line SSE field (event, id).
11094
*/
@@ -130,46 +114,14 @@ private function formatMultiline(string $prefix, string $value): string
130114
return $output . "\n";
131115
}
132116

133-
/**
134-
* Write raw SSE output and flush.
135-
*/
136-
private function write(string $output): bool
137-
{
138-
echo $output;
139-
140-
if (! service('environment')->isTesting()) {
141-
if (ob_get_level() > 0) {
142-
ob_flush();
143-
}
144-
145-
flush();
146-
}
147-
148-
return true;
149-
}
150-
151117
/**
152118
* {@inheritDoc}
153119
*
154-
* @return $this
120+
* SSE headers are fixed by the protocol, so they override
121+
* anything set on the response.
155122
*/
156-
public function send()
123+
protected function prepareStreamHeaders(): void
157124
{
158-
// Turn off output buffering completely, even if php.ini output_buffering is not off
159-
if (! service('environment')->isTesting()) {
160-
set_time_limit(0);
161-
ini_set('zlib.output_compression', 'Off');
162-
163-
while (ob_get_level() > 0) {
164-
ob_end_clean();
165-
}
166-
}
167-
168-
// Close session if active to prevent blocking other requests
169-
if (session_status() === PHP_SESSION_ACTIVE) {
170-
session_write_close();
171-
}
172-
173125
$this->setContentType('text/event-stream', 'UTF-8');
174126
$this->removeHeader('Cache-Control');
175127
$this->setHeader('Cache-Control', 'no-cache');
@@ -180,25 +132,5 @@ public function send()
180132
if (version_compare($this->getProtocolVersion(), '2.0', '<')) {
181133
$this->setHeader('Connection', 'keep-alive');
182134
}
183-
184-
// Intentionally skip CSP finalize: no HTML/JS execution in SSE streams.
185-
$this->sendHeaders();
186-
$this->sendCookies();
187-
188-
($this->callback)($this);
189-
190-
return $this;
191-
}
192-
193-
/**
194-
* {@inheritDoc}
195-
*
196-
* No-op — body is streamed via the callback, not stored.
197-
*
198-
* @return $this
199-
*/
200-
public function sendBody()
201-
{
202-
return $this;
203135
}
204136
}

‎system/HTTP/StreamResponse.php‎

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace CodeIgniter\HTTP;
15+
16+
use Closure;
17+
18+
/**
19+
* HTTP response that streams its body to the client as it is generated,
20+
* instead of buffering the complete body first.
21+
*
22+
* @see \CodeIgniter\HTTP\StreamResponseTest
23+
*/
24+
class StreamResponse extends Response implements NonBufferedResponseInterface
25+
{
26+
/**
27+
* @var Closure(static): void
28+
*/
29+
private readonly Closure $callback;
30+
31+
/**
32+
* @param (Closure(static): void)|iterable<string> $callbackOrChunks A callback that
33+
* streams output via write(), or an iterable of
34+
* string chunks to be written in order
35+
*/
36+
public function __construct(Closure|iterable $callbackOrChunks)
37+
{
38+
parent::__construct();
39+
40+
$this->callback = $callbackOrChunks instanceof Closure
41+
? $callbackOrChunks
42+
: static function (self $response) use ($callbackOrChunks): void {
43+
foreach ($callbackOrChunks as $chunk) {
44+
if (! $response->write($chunk)) {
45+
break;
46+
}
47+
}
48+
};
49+
}
50+
51+
/**
52+
* Write a chunk of the streamed body.
53+
*
54+
* @param bool $flush Whether to flush output to the client immediately.
55+
* Pass false when writing many small chunks, then call
56+
* flush() at intervals.
57+
*
58+
* @return bool false if the client has disconnected
59+
*/
60+
public function write(string $chunk, bool $flush = true): bool
61+
{
62+
if (! $this->isClientConnected()) {
63+
return false;
64+
}
65+
66+
echo $chunk;
67+
68+
if ($flush) {
69+
$this->flush();
70+
}
71+
72+
return true;
73+
}
74+
75+
/**
76+
* Flush buffered output to the client.
77+
*/
78+
public function flush(): void
79+
{
80+
if (! service('environment')->isTesting()) {
81+
if (ob_get_level() > 0) {
82+
ob_flush();
83+
}
84+
85+
flush();
86+
}
87+
}
88+
89+
/**
90+
* Whether the client connection is still open.
91+
*
92+
* Note: PHP only detects a disconnect when attempting to write,
93+
* so this may return true until the next write() call fails.
94+
*/
95+
public function isClientConnected(): bool
96+
{
97+
return connection_status() === CONNECTION_NORMAL && connection_aborted() === 0;
98+
}
99+
100+
/**
101+
* {@inheritDoc}
102+
*
103+
* @return $this
104+
*/
105+
public function send()
106+
{
107+
// Turn off output buffering completely, even if php.ini output_buffering is not off
108+
if (! service('environment')->isTesting()) {
109+
set_time_limit(0);
110+
ini_set('zlib.output_compression', 'Off');
111+
112+
while (ob_get_level() > 0) {
113+
ob_end_clean();
114+
}
115+
}
116+
117+
// Close session if active to prevent blocking other requests
118+
if (session_status() === PHP_SESSION_ACTIVE) {
119+
session_write_close();
120+
}
121+
122+
$this->prepareStreamHeaders();
123+
124+
// Intentionally skip CSP finalize: the body is streamed, not buffered HTML.
125+
$this->sendHeaders();
126+
$this->sendCookies();
127+
128+
($this->callback)($this);
129+
130+
return $this;
131+
}
132+
133+
/**
134+
* Applies headers needed for unbuffered delivery, without overriding
135+
* any the developer has already set.
136+
*/
137+
protected function prepareStreamHeaders(): void
138+
{
139+
if (! $this->hasHeader('X-Accel-Buffering')) {
140+
$this->setHeader('X-Accel-Buffering', 'no');
141+
}
142+
143+
if (! $this->hasHeader('Content-Encoding')) {
144+
$this->setHeader('Content-Encoding', 'identity');
145+
}
146+
}
147+
148+
/**
149+
* {@inheritDoc}
150+
*
151+
* No-op — body is streamed via the callback, not stored.
152+
*
153+
* @return $this
154+
*/
155+
public function sendBody()
156+
{
157+
return $this;
158+
}
159+
}

0 commit comments

Comments
 (0)