Streaming responses
Read Server-Sent Events or newline-delimited JSON as a Stream, and handle how a stream fails or stops.
Some APIs send their answer a piece at a time: progress feeds,
notifications, exports, the answers of language models. Waiting for the
whole body would mean showing nothing until the end. api.sse and
api.ndjson give such a body as an Effect Stream, one value at a time,
as it arrives. This page shows how to read both formats, define stream
endpoints, and handle a stream that fails or that you stop.
Read Server-Sent Events
api.sse reads a text/event-stream body. Each value is an event, with
its event name ("message" when the server sends none), its id, and its
data, decoded with output:
import * as from "effect/Effect";
import * as from "effect/Schema";
import * as from "effect/Stream";
import type { } from "@monarcode/effetch";
declare const : .;
const = .({ : . });
export const = (: number) =>
.("/jobs/:id/events", { : { }, : }).(
.(() => .. === 100),
.(() => .(`${..}%`)),
);output decodes each event's data as JSON. Without it, or with
Fetch.text(), data is the text as it was sent.
The request is a GET by default. An API that streams its answer to a
request usually takes a POST with a body, so pass method and body:
import * as from "effect/Schema";
import type { } from "@monarcode/effetch";
declare const : .;
const = .({ : . });
const = .({ : . });
export const = (: string) =>
.("/completions", {
: "POST",
: ,
: { },
: ,
});The request sends Accept: text/event-stream, unless the call or the
client sets an accept header.
How events are parsed
Events are parsed by the WHATWG rules, which most servers follow without you noticing. A few of them can surprise you:
- Comment lines are ignored. A multi-line
datais joined with\n, and anidcarries over to the events after it. - An event without any
dataline is dropped. - An event ends at a blank line. When the server closes the connection without one after its last event, that last event is dropped.
- An event over 10 MiB fails the stream with a
DecodeError. - A response whose
Content-Typeis set to a type other thantext/event-stream, such as a login page from a proxy, fails the stream with aDecodeErrorbefore any event. - The stream doesn't reconnect, and ignores
retry:lines.
Limitations shows how to pick up a stream where it stopped.
Stop at a sentinel
output decodes every event, so an event whose data doesn't match it fails
the stream, after the events before it. Some servers end with a sentinel
that isn't JSON, such as data: [DONE]. For those, leave output out,
stop at the sentinel, then decode the rest:
import * as from "effect/Schema";
import * as from "effect/Stream";
import type { } from "@monarcode/effetch";
declare const : .;
const = .(.({ : . }));
export const = (: string) =>
.("/completions", { : "POST", : { } }).(
.(() => . !== "[DONE]"),
.(() => .()(.)),
);Read newline-delimited JSON
api.ndjson reads an application/x-ndjson body, also called JSON Lines:
one JSON value per line, each decoded with output:
import * as from "effect/Schema";
import * as from "effect/Stream";
import type { } from "@monarcode/effetch";
declare const : .;
const = .({ : ., : . });
export const =
.("/export/users", { : })
.(.);The following rules apply to an NDJSON call:
- Without
output, each value is the parsed JSON, typedunknown.Fetch.text()gives each line's text instead. - Blank lines are skipped, and the last line needs no line end.
- The request sends
Accept: application/x-ndjson, unless anacceptheader is set. - Unlike SSE, the response's
Content-Typeisn't checked. A body that isn't NDJSON, such as an HTML page, fails on its first line as invalid JSON, unless you read the lines as text withFetch.text().
Define a stream endpoint
An endpoint defined with stream: "sse" or
stream: "ndjson" returns a Stream from its calls, however it's bound:
import * as from "effect/Effect";
import * as from "effect/Schema";
import * as from "effect/Stream";
import { } from "@monarcode/effetch";
const = .({ : . });
const = .("GET /jobs/:id/events", {
: ,
: "sse",
});
class extends .<>()("Api", {
: "https://api.example.com",
}) {}
export class extends .<>()("JobApi", , {
: ,
}) {}
export const = (: number) =>
.(function* () {
const = yield* ;
return yield* .({ : { } }).(.);
});Its calls follow the same rules as api.sse or api.ndjson.
How a stream fails
A stream fails in two stages: while its request is sent, and while its body is read.
The request runs as any call does, up to the response's headers:
- Plugins run once.
retryandtimeoutapply to getting the response, not to reading the body. - When no response arrives, the stream fails with a
NetworkError. - A plugin's error fails it too, such as the
TimeoutErrorof thetimeoutplugin. - An error status fails it with an
HttpError, or astatusErrorserror, before it gives any value. - A
204 No Contentor205 Reset Contentgives an empty stream.
Then the body is read as it arrives, and the values before a failure are
given first. A value that doesn't match output, or a body that breaks
off, fails the stream with a DecodeError, which names the event or the
line, as in Line 3 doesn't match the output schema.
On React Native, the built-in fetch doesn't stream response bodies, so
every stream fails there with a DecodeError.
Platform notes shows which fetch to use
instead.
For plugins, a stream's call ends when the response's headers arrive:
loggertimes every call up to the headers, so for a stream, it logs the time to the headers.onExithooks,consoleLogger's among them, run when the headers arrive, and report the time to the headers.- A
DecodeErrorwhile the body is read reaches neither.
Handle errors from the body on the stream itself, with
Stream.catchTag("DecodeError", …) or Stream.tapError.
Stop a stream
Interrupting the stream, or taking only part of it, as with Stream.take,
aborts the request. You don't need to close the connection yourself.
Options a stream doesn't take
A stream can't take responseMode, since it gives the body's values, or an
output made with Fetch.bytes(), which can't decode them one at a time.
A call that passes one dies, and a definition with one throws when it's
made.
What's next
- Pagination: follow a list's pages as a
Stream. - Test stream endpoints: answer a stream endpoint from a fake backend.
- Limitations: see what streams don't do, such as reconnecting.