Skip to content

Commit c782fda

Browse files
committed
Add SseDecoder to decode Server-Sent Events from any readable stream
1 parent 9b86517 commit c782fda

4 files changed

Lines changed: 676 additions & 1 deletion

File tree

‎README.md‎

Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ of [ReactPHP](https://reactphp.org/)'s event-driven architecture.
2525
* [MessageEvent::$data](#messageeventdata)
2626
* [MessageEvent::$lastEventId](#messageeventlasteventid)
2727
* [MessageEvent::$type](#messageeventtype)
28+
* [SseDecoder](#ssedecoder)
2829
* [Install](#install)
2930
* [Tests](#tests)
3031
* [License](#license)
@@ -325,6 +326,146 @@ See also [`message` event](#message-event).
325326
If the message does not contain a `event` field or the `event` field is empty,
326327
the `$type` property will default to `message`.
327328

329+
### SseDecoder
330+
331+
The `SseDecoder` class is responsible for decoding the Server-Sent Events (SSE)
332+
wire protocol from any readable byte stream.
333+
334+
Unlike the [`EventSource`](#eventsource) class which implements the higher-level
335+
HTML5 EventSource API (HTTP `GET` request, automatic reconnection, `readyState`
336+
and `Last-Event-ID` handling), this class only decodes the `text/event-stream`
337+
wire protocol. This makes it reusable whenever you already have a readable
338+
stream of SSE data, such as a streaming HTTP response to a custom request. This
339+
is common for LLM streaming APIs that return SSE over an HTTP `POST` request:
340+
341+
```php
342+
$browser = new React\Http\Browser();
343+
344+
$response = await($browser->requestStreaming(
345+
'POST',
346+
'https://api.example.com/v1/messages',
347+
$headers,
348+
$body
349+
));
350+
assert($response instanceof Psr\Http\Message\ResponseInterface);
351+
352+
$stream = $response->getBody();
353+
assert($stream instanceof React\Stream\ReadableStreamInterface);
354+
355+
$sse = new Clue\React\EventSource\SseDecoder($stream);
356+
$sse->on('data', function (Clue\React\EventSource\MessageEvent $message) {
357+
$data = json_decode($message->data);
358+
359+
if ($data?->type === 'content_block_delta') {
360+
echo $data->delta->text;
361+
}
362+
});
363+
```
364+
365+
Its constructor requires a readable stream that emits the raw SSE bytes:
366+
367+
```php
368+
$sse = new Clue\React\EventSource\SseDecoder($stream);
369+
```
370+
371+
When resuming a previously interrupted stream, you can pass the last event ID to
372+
continue from, so any message without an `id` field inherits it:
373+
374+
```php
375+
$sse = new Clue\React\EventSource\SseDecoder($stream, $lastEventId);
376+
```
377+
378+
The `SseDecoder` implements ReactPHP's
379+
[`ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface)
380+
and emits a `data` event with a [`MessageEvent` object](#messageevent) for each
381+
incoming event. It is commonly used for transporting structured data such as JSON:
382+
383+
```
384+
data: {"name":"Alice","age":30}
385+
386+
data: {"name":"Bob","age":50}
387+
```
388+
```php
389+
$sse->on('data', function (Clue\React\EventSource\MessageEvent $message) {
390+
$data = json_decode($message->data);
391+
echo "{$data->name} is {$data->age} years old" . PHP_EOL;
392+
});
393+
```
394+
395+
ReactPHP's underlying streams emit chunks of data strings and make no assumption
396+
about their lengths. These chunks do not necessarily represent complete SSE
397+
messages, as a single message may be broken up into multiple data chunks.
398+
This class reassembles these messages by buffering incomplete ones.
399+
400+
Each event is dispatched as soon as its terminating blank line has been read.
401+
As per the SSE specification, an event with an empty data buffer (such as a
402+
comment or a lone `retry` field) will not be dispatched, and an incomplete event
403+
left in the buffer when the input stream ends will be discarded.
404+
405+
The `id` and `retry` fields will be saved in the `string $lastEventId = ''`
406+
and `?float $lastRetryTime = null` properties respectively. They are
407+
assigned to the decoder before each `data` event is emitted as they may appear
408+
on events that are never dispatched. You can read their value from any event:
409+
410+
```php
411+
$sse->on('close', function () use ($sse) {
412+
printf(
413+
'Reconnect in %.1f seconds with last event ID %s' . PHP_EOL,
414+
$sse->lastRetryTime ?? 3.0,
415+
$sse->lastEventId
416+
);
417+
});
418+
```
419+
420+
If the underlying stream emits an `error` event, it will forward this `error`
421+
event and then `close` the input stream. As per the SSE specs, any unknown or
422+
malformed fields will be ignored and will not cause an `error` event:
423+
424+
```php
425+
$sse->on('error', function (Exception $error) {
426+
// an error occurred, stream will close next
427+
});
428+
```
429+
430+
If the underlying stream emits an `end` event, it will clear any incomplete
431+
data from the buffer and emit a final `end` event:
432+
433+
```php
434+
$sse->on('end', function () {
435+
// stream successfully ended, stream will close next
436+
});
437+
```
438+
439+
If either the underlying stream or the `SseDecoder` is closed, it will forward
440+
the `close` event:
441+
442+
```php
443+
$sse->on('close', function () {
444+
// stream closed
445+
// possibly after an "end" event or due to an "error" event
446+
});
447+
```
448+
449+
The `close(): void` method can be used to explicitly close the `SseDecoder`
450+
and its underlying stream:
451+
452+
```php
453+
$sse->close();
454+
```
455+
456+
The `pipe(WritableStreamInterface $dest, array $options = array(): WritableStreamInterface`
457+
method can be used to forward all data to the given destination stream.
458+
Please note that the `SseDecoder` emits structured `MessageEvent` objects,
459+
while many writable streams expect only data chunks:
460+
461+
```php
462+
$map = new ThroughStream(fn (MessageEvent $message) => $message->data);
463+
$sse->pipe($map)->pipe($logger);
464+
```
465+
466+
For more details, see ReactPHP's
467+
[`ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface).
468+
328469
## Install
329470

330471
The recommended way to install this library is [through Composer](https://getcomposer.org/).

‎composer.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
"evenement/evenement": "^3.0 || ^2.0",
1616
"react/event-loop": "^1.6",
1717
"react/http": "^1.11",
18-
"react/promise": "^3.3 || ^2.10 || ^1.2.1"
18+
"react/promise": "^3.3 || ^2.10 || ^1.2.1",
19+
"react/stream": "^1.4"
1920
},
2021
"require-dev": {
2122
"phpunit/phpunit": "^9.6 || ^8.5 || ^5.7 || ^4.8.36"

‎src/SseDecoder.php‎

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
<?php
2+
3+
namespace Clue\React\EventSource;
4+
5+
use Evenement\EventEmitter;
6+
use React\Stream\ReadableStreamInterface;
7+
use React\Stream\Util;
8+
use React\Stream\WritableStreamInterface;
9+
10+
/**
11+
* The `SseDecoder` reads from a plain byte stream and emits a `MessageEvent` for each Server-Sent Event (SSE).
12+
*
13+
* Unlike the `EventSource` class which implements the higher-level HTML5
14+
* EventSource API (HTTP `GET` request, automatic reconnection, `readyState`
15+
* and `Last-Event-ID` handling), this class only decodes the SSE wire protocol.
16+
* This makes it reusable for any readable stream of `text/event-stream` data,
17+
* such as a streaming HTTP response to a custom request (think LLM streaming
18+
* APIs using an HTTP `POST` request).
19+
*/
20+
class SseDecoder extends EventEmitter implements ReadableStreamInterface
21+
{
22+
/** @var ReadableStreamInterface */
23+
private $input;
24+
25+
/** @var string */
26+
private $buffer = '';
27+
28+
/** @var bool */
29+
private $closed = false;
30+
31+
/**
32+
* @var string (read-only) last event ID received from the `id` field or an empty string if not given
33+
* @psalm-readonly-allow-private-mutation
34+
*/
35+
public $lastEventId = '';
36+
37+
/**
38+
* @var ?float (read-only) reconnection time in seconds from the `retry` field or null if not given
39+
* @psalm-readonly-allow-private-mutation
40+
*/
41+
public $lastRetryTime = null;
42+
43+
/**
44+
* @param ReadableStreamInterface $input readable byte stream emitting `text/event-stream` data
45+
* @param string $lastEventId optional last event ID to resume from a previous stream
46+
*/
47+
public function __construct(ReadableStreamInterface $input, $lastEventId = '')
48+
{
49+
$this->input = $input;
50+
$this->lastEventId = $lastEventId;
51+
52+
if (!$input->isReadable()) {
53+
$this->close();
54+
return;
55+
}
56+
57+
$this->input->on('data', array($this, 'handleData'));
58+
$this->input->on('end', array($this, 'handleEnd'));
59+
$this->input->on('error', array($this, 'handleError'));
60+
$this->input->on('close', array($this, 'close'));
61+
}
62+
63+
public function isReadable()
64+
{
65+
return !$this->closed;
66+
}
67+
68+
public function close()
69+
{
70+
if ($this->closed) {
71+
return;
72+
}
73+
74+
$this->closed = true;
75+
$this->buffer = '';
76+
77+
$this->input->close();
78+
79+
$this->emit('close');
80+
$this->removeAllListeners();
81+
}
82+
83+
public function pause()
84+
{
85+
$this->input->pause();
86+
}
87+
88+
public function resume()
89+
{
90+
$this->input->resume();
91+
}
92+
93+
public function pipe(WritableStreamInterface $dest, array $options = array())
94+
{
95+
Util::pipe($this, $dest, $options);
96+
97+
return $dest;
98+
}
99+
100+
/** @internal */
101+
public function handleData($data)
102+
{
103+
if (!\is_string($data)) {
104+
$this->handleError(new \UnexpectedValueException('Expected stream to emit string, but got ' . \gettype($data)));
105+
return;
106+
}
107+
108+
$this->buffer .= $data;
109+
110+
// keep parsing while a complete event (terminated by a blank line) has been found
111+
while (\preg_match('/(?:\r\n|\r(?!\n)|\n){2}/S', $this->buffer, $match, \PREG_OFFSET_CAPTURE) === 1) {
112+
// read event up until blank line and remove from buffer (including trailing blank line)
113+
$event = (string) \substr($this->buffer, 0, $match[0][1]);
114+
$this->buffer = (string) \substr($this->buffer, $match[0][1] + \strlen($match[0][0]));
115+
116+
// `id` and `retry` configure the event stream rather than a single message and may
117+
// arrive on events that are never dispatched, so they are assigned to this stream
118+
// before the `data` event is emitted and can be read at any time
119+
$message = MessageEvent::parse($event, $this->lastEventId, $this->lastRetryTime);
120+
$this->lastEventId = $message->lastEventId;
121+
122+
// dispatch event unless its data buffer is empty (as per SSE specs)
123+
if ($message->data !== '') {
124+
$this->emit('data', array($message));
125+
126+
if ($this->closed) {
127+
return;
128+
}
129+
}
130+
}
131+
}
132+
133+
/** @internal */
134+
public function handleEnd()
135+
{
136+
// discard any incomplete event left in the buffer (as per SSE specs)
137+
if (!$this->closed) {
138+
$this->emit('end');
139+
$this->close();
140+
}
141+
}
142+
143+
/** @internal */
144+
public function handleError(\Exception $error)
145+
{
146+
$this->emit('error', array($error));
147+
$this->close();
148+
}
149+
}

0 commit comments

Comments
 (0)