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. 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),
.(() => .(`${..}%`)),
);The following rules apply to an SSE call:
-
outputdecodes each event'sdataas JSON. Without it, or withFetch.text(),datais the text as it was sent. -
methoddefaults to"GET". APIs that stream the answer to a request take"POST"and abody: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 anacceptheader. -
Events are parsed by the WHATWG rules: comment lines are ignored, a multi-line
datais joined with\n, and anidcarries over to the events after it. The stream doesn't reconnect, and ignoresretry:lines. -
A response whose
Content-Typeis set to another type thantext/event-stream, such as a login page from a proxy, fails the stream with aDecodeError.
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. When the server ends with a
sentinel that isn't JSON, such as data: [DONE], 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, 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.
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* .({ : { } }).(.);
});How a stream fails
A stream's 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. - 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. 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:
Line 3 doesn't match the output schema.
For plugins, the call ends when the response's headers arrive. Their
onExit hooks, and so logger and consoleLogger, report it then, with
the time to the headers, and a DecodeError while reading the body doesn't
reach them. Handle it on the stream, 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. Nothing else is needed to close the connection.
Options a stream doesn't take
A stream can't take responseMode, or an output made with
Fetch.bytes(). 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.
- Errors by status: fail a stream with your own error for a status.