@@ -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).
325326If the message does not contain a ` event ` field or the ` event ` field is empty,
326327the ` $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
330471The recommended way to install this library is [ through Composer] ( https://getcomposer.org/ ) .
0 commit comments