Skip to content

Commit 9d27004

Browse files
authored
feat: add StreamResponse and SSE response factories (#10395)
1 parent f4b5beb commit 9d27004

16 files changed

Lines changed: 738 additions & 80 deletions

File tree

‎structarmed.php‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
use CodeIgniter\HTTP\Header;
1717
use CodeIgniter\HTTP\IncomingRequest;
1818
use CodeIgniter\HTTP\SSEResponse;
19+
use CodeIgniter\HTTP\StreamResponse;
1920
use CodeIgniter\HTTP\ResponseInterface;
2021
use CodeIgniter\DataCaster\DataCaster;
2122
use CodeIgniter\Entity\Cast\CastInterface;
@@ -155,4 +156,5 @@
155156
->skipClassViolation(RedirectResponse::class, [PagerInterface::class])
156157
->skipClassViolation(DownloadResponse::class, [PagerInterface::class])
157158
->skipClassViolation(SSEResponse::class, [PagerInterface::class])
159+
->skipClassViolation(StreamResponse::class, [PagerInterface::class])
158160
->skipClassViolation(Validation::class, [RendererInterface::class]);

‎system/HTTP/ResponseInterface.php‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -397,6 +397,23 @@ public function redirect(string $uri, string $method = 'auto', ?int $code = null
397397
*/
398398
public function download(string $filename = '', $data = '', bool $setMime = false);
399399

400+
/**
401+
* Creates a response that streams its body to the client as it is
402+
* generated, instead of buffering the complete body first.
403+
*
404+
* @param (callable(StreamResponse): void)|iterable<string> $callbackOrChunks A callback that
405+
* streams output via write(), or an iterable of
406+
* string chunks to be written in order
407+
*/
408+
public function stream(callable|iterable $callbackOrChunks): StreamResponse;
409+
410+
/**
411+
* Creates a response for streaming Server-Sent Events (SSE).
412+
*
413+
* @param callable(SSEResponse): void $callback
414+
*/
415+
public function eventStream(callable $callback): SSEResponse;
416+
400417
// --------------------------------------------------------------------
401418
// CSP Methods
402419
// --------------------------------------------------------------------

‎system/HTTP/ResponseTrait.php‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -394,7 +394,7 @@ public function send()
394394
* need it avoids the cost of constructing a 1000+ line service on every
395395
* request.
396396
*/
397-
private function shouldFinalizeCsp(): bool
397+
protected function shouldFinalizeCsp(): bool
398398
{
399399
// Developer already touched CSP through getCSP(); respect it.
400400
if ($this->CSP !== null) {
@@ -810,6 +810,29 @@ public function download(string $filename = '', $data = '', bool $setMime = fals
810810
return $response;
811811
}
812812

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

‎system/HTTP/SSEResponse.php‎

Lines changed: 12 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,23 @@
1313

1414
namespace CodeIgniter\HTTP;
1515

16-
use Closure;
1716
use JsonException;
1817

1918
/**
2019
* HTTP response for Server-Sent Events (SSE) streaming.
2120
*
2221
* @see \CodeIgniter\HTTP\SSEResponseTest
2322
*/
24-
class SSEResponse extends Response implements NonBufferedResponseInterface
23+
class SSEResponse extends StreamResponse
2524
{
2625
/**
2726
* Constructor.
2827
*
29-
* @param Closure(SSEResponse): void $callback
28+
* @param callable(SSEResponse): void $callback
3029
*/
31-
public function __construct(private readonly Closure $callback)
30+
public function __construct(callable $callback)
3231
{
33-
parent::__construct();
32+
parent::__construct($callback);
3433
}
3534

3635
/**
@@ -42,7 +41,7 @@ public function __construct(private readonly Closure $callback)
4241
*/
4342
public function event(array|string $data, ?string $event = null, ?string $id = null): bool
4443
{
45-
if ($this->isConnectionAborted()) {
44+
if (! $this->isClientConnected()) {
4645
return false;
4746
}
4847

@@ -76,10 +75,6 @@ public function event(array|string $data, ?string $event = null, ?string $id = n
7675
*/
7776
public function comment(string $text): bool
7877
{
79-
if ($this->isConnectionAborted()) {
80-
return false;
81-
}
82-
8378
return $this->write($this->formatMultiline('', $text));
8479
}
8580

@@ -90,21 +85,9 @@ public function comment(string $text): bool
9085
*/
9186
public function retry(int $milliseconds): bool
9287
{
93-
if ($this->isConnectionAborted()) {
94-
return false;
95-
}
96-
9788
return $this->write("retry: {$milliseconds}\n\n");
9889
}
9990

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-
10891
/**
10992
* Strip newlines from a single-line SSE field (event, id).
11093
*/
@@ -130,75 +113,33 @@ private function formatMultiline(string $prefix, string $value): string
130113
return $output . "\n";
131114
}
132115

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-
151116
/**
152117
* {@inheritDoc}
153118
*
154-
* @return $this
119+
* SSE headers are fixed by the protocol, so they override
120+
* anything set on the response.
155121
*/
156-
public function send()
122+
protected function prepareStreamHeaders(): void
157123
{
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-
173124
$this->setContentType('text/event-stream', 'UTF-8');
174125
$this->removeHeader('Cache-Control');
175126
$this->setHeader('Cache-Control', 'no-cache');
176-
$this->setHeader('Content-Encoding', 'identity');
177127
$this->setHeader('X-Accel-Buffering', 'no');
178128

179129
// Connection: keep-alive is only valid for HTTP/1.x
180130
if (version_compare($this->getProtocolVersion(), '2.0', '<')) {
181131
$this->setHeader('Connection', 'keep-alive');
182132
}
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;
191133
}
192134

193135
/**
194136
* {@inheritDoc}
195137
*
196-
* No-op — body is streamed via the callback, not stored.
197-
*
198-
* @return $this
138+
* CSP is not finalized for SSE responses, as Content Security
139+
* Policy does not apply to event streams.
199140
*/
200-
public function sendBody()
141+
protected function shouldFinalizeCsp(): bool
201142
{
202-
return $this;
143+
return false;
203144
}
204145
}

‎system/HTTP/StreamResponse.php‎

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
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 (callable(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. A value
35+
* that is both callable and iterable is treated
36+
* as a callback.
37+
*/
38+
public function __construct(callable|iterable $callbackOrChunks)
39+
{
40+
parent::__construct();
41+
42+
$this->callback = is_callable($callbackOrChunks)
43+
? $callbackOrChunks(...)
44+
: static function (self $response) use ($callbackOrChunks): void {
45+
foreach ($callbackOrChunks as $chunk) {
46+
if (! $response->write($chunk)) {
47+
break;
48+
}
49+
}
50+
};
51+
}
52+
53+
/**
54+
* Write a chunk of the streamed body.
55+
*
56+
* @param bool $flush Whether to flush output to the client immediately.
57+
* Pass false when writing many small chunks, then call
58+
* flush() at intervals.
59+
*
60+
* @return bool false if the client has disconnected
61+
*/
62+
public function write(string $chunk, bool $flush = true): bool
63+
{
64+
if (! $this->isClientConnected()) {
65+
return false;
66+
}
67+
68+
echo $chunk;
69+
70+
if ($flush) {
71+
$this->flush();
72+
}
73+
74+
return true;
75+
}
76+
77+
/**
78+
* Flush buffered output to the client.
79+
*/
80+
public function flush(): void
81+
{
82+
if (! service('environment')->isTesting()) {
83+
if (ob_get_level() > 0) {
84+
ob_flush();
85+
}
86+
87+
flush();
88+
}
89+
}
90+
91+
/**
92+
* Whether the client connection is still open.
93+
*
94+
* Note: PHP only detects a disconnect when attempting to write,
95+
* so this may return true until the next write() call fails.
96+
*/
97+
public function isClientConnected(): bool
98+
{
99+
return connection_status() === CONNECTION_NORMAL && connection_aborted() === 0;
100+
}
101+
102+
/**
103+
* {@inheritDoc}
104+
*
105+
* @return $this
106+
*/
107+
public function send()
108+
{
109+
// Turn off output buffering completely, even if php.ini output_buffering is not off
110+
if (! service('environment')->isTesting()) {
111+
set_time_limit(0);
112+
ini_set('zlib.output_compression', 'Off');
113+
114+
while (ob_get_level() > 0) {
115+
ob_end_clean();
116+
}
117+
}
118+
119+
// Close session if active to prevent blocking other requests
120+
if (session_status() === PHP_SESSION_ACTIVE) {
121+
session_write_close();
122+
}
123+
124+
$this->prepareStreamHeaders();
125+
126+
// Give CSP a chance to build its headers. Nonce placeholders cannot be
127+
// replaced in a streamed body; call getCSP()->getScriptNonce() or
128+
// getStyleNonce() before returning the response instead.
129+
if ($this->shouldFinalizeCsp()) {
130+
$this->getCSP()->finalize($this);
131+
}
132+
133+
$this->sendHeaders();
134+
$this->sendCookies();
135+
136+
($this->callback)($this);
137+
138+
return $this;
139+
}
140+
141+
/**
142+
* Applies headers needed for unbuffered delivery, without overriding
143+
* any the developer has already set.
144+
*/
145+
protected function prepareStreamHeaders(): void
146+
{
147+
if (! $this->hasHeader('X-Accel-Buffering')) {
148+
$this->setHeader('X-Accel-Buffering', 'no');
149+
}
150+
}
151+
152+
/**
153+
* {@inheritDoc}
154+
*
155+
* No-op — body is streamed via the callback, not stored.
156+
*
157+
* @return $this
158+
*/
159+
public function sendBody()
160+
{
161+
return $this;
162+
}
163+
}

0 commit comments

Comments
 (0)