Http
Reference for the Http namespace in @streamsy/core. It serves the Durable Streams protocol over HTTP for a group of stream classes.
import { Http, Streamsy, type StreamId } from "@streamsy/core";
import type { StreamsReader, StreamsWriter } from "@streamsy/core/protocol";
import type { Duration, Effect, Layer, Stream } from "effect";
import type { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";Http serves the Durable Streams protocol over HTTP. An application mounts Http.routes for a group. Protocol tools and hosts use the other exports. See Expose the stream protocol.
The entry point @streamsy/core/http exports the same module, with each name at the top level. Http.routes and routes from @streamsy/core/http are the same function. This page uses the Http. form.
import { routes, ShutdownSignal } from "@streamsy/core/http";Routes
Http.routes
declare function routes<const Keys extends ReadonlyArray<Streamsy.Any>>(
group: Streamsy.Group<Keys>,
options: Http.RoutesOptions,
): Layer.Layer<
never,
never,
| HttpRouter.HttpRouter
| HttpRouter.Request.From<
"Requires",
Exclude<Streamsy.Host<Streamsy.Group<Keys>>, HttpRouter.Provided>
>
>;
routes returns an HttpRouter route Layer that serves the protocol for each stream class in group, under options.prefix. The Layer needs the service of each class in the group, so provide a storage Layer for the group.
routesanswers 404 to a request for an id that no class owns.routesanswers 405, with anallowheader, to a method that the access of the class does not allow.routesanswers 400 to a request for the bare prefix.routesremoves one trailing/fromprefix, so/streams/is the same as/streams.
routes throws a RangeError when prefix does not start with /, or contains ?, :, #, *, or //. It also throws for the same groups as Streamsy.group, and when sseDeadlineMs is not a positive finite number.
Http.RoutesOptions
interface RoutesOptions extends Omit<Http.HttpOptions, "pathPrefix"> {
readonly prefix?: `/${string}`;
readonly access: Http.Access["access"] | ((stream: Streamsy.Any) => Http.Access["access"]);
}
RoutesOptions holds the options of routes: the HttpOptions except pathPrefix, and these two.
| Option | Meaning |
|---|---|
prefix | The path under which the stream ids are served. The default is / |
access | One access level for every class, or a function that returns the access level of each class |
Http.Access
interface Access<S extends Streamsy.Any = Streamsy.Any> {
readonly stream: S;
readonly access: "read" | "append" | "full";
}
Access pairs a stream class with its access level. RoutesOptions.access uses its access field.
| Access | Methods |
|---|---|
read | GET, HEAD, OPTIONS |
append | GET, HEAD, POST, OPTIONS |
full | GET, HEAD, PUT, POST, DELETE, OPTIONS |
For a class with read or append access, the response to OPTIONS lists only the allowed methods in access-control-allow-methods.
Programs
Http.app
declare function app(
options?: Http.HttpOptions,
): Effect.Effect<
HttpServerResponse.HttpServerResponse,
never,
HttpServerRequest.HttpServerRequest | StreamsReader | StreamsWriter
>;
app returns the HTTP program of the whole protocol, over the generic StreamsReader and StreamsWriter. It serves every id under pathPrefix, with no access rules. routes runs it for each request that a class owns, and routes from @streamsy/core/protocol mounts it unchanged.
app answers every request and never fails. It maps each protocol error to its HTTP status, for example StreamNotFound to 404 and OffsetMismatch to 409. app answers 500 for a StorageFault or a TransportFault, and 413 for a body larger than maxMessageSize. Every response has the securityHeaders.
app throws a RangeError when sseDeadlineMs is not a positive finite number.
Http.HttpOptions
interface HttpOptions {
readonly pathPrefix?: string;
readonly sseDeadlineMs?: number;
readonly maxMessageSize?: number;
readonly cacheVisibility?: "private" | "public";
}
HttpOptions holds the options of app.
| Option | Meaning |
|---|---|
pathPrefix | The path before each stream id. The default is / |
sseDeadlineMs | The lifetime of an SSE response. The default is 60 s |
maxMessageSize | The largest request body, in bytes. The default is 1 MiB |
cacheVisibility | private or public in the cache-control header of a read. The default is private |
Http.read
declare function read(
id: StreamId,
options?: Http.ReadOptions,
): Effect.Effect<
HttpServerResponse.HttpServerResponse,
ReadNextError | StreamsFault,
HttpServerRequest.HttpServerRequest | StreamsReader
>;
read answers a GET or HEAD request for the stream id, which the caller has already resolved. It handles catch-up reads, long polls, and SSE, as app does. For a HEAD request, read answers with the metadata of the stream in headers.
Unlike app, read does not map errors to responses. It fails with the protocol error or the fault, and the caller builds the response. read throws a RangeError when sseDeadlineMs is not a positive finite number.
Http.ReadOptions
interface ReadOptions {
readonly sseDeadlineMs?: number;
readonly cacheVisibility?: "private" | "public";
}
ReadOptions holds the options of read. They mean the same as in HttpOptions. This type is not the root ReadOptions, which holds the options of a protocol read.
Http.checkReadOptions
declare function checkReadOptions(options: Http.ReadOptions): void;
checkReadOptions throws a RangeError when options.sseDeadlineMs is set and is not a positive finite number. app, routes, and read call it when they are built. A host that builds its own read route can call it to fail at the same point.
Http.streamPath
declare function streamPath(pathPrefix?: string): {
requiredPathPattern: () => string;
strip: (pathname: string) => string;
canonicalizeForkSource: (source: string) => string;
};
streamPath returns the path helpers of a prefix. It adds a trailing / to pathPrefix when it has none. The default prefix is /.
| Member | Returns |
|---|---|
requiredPathPattern | The pattern of a stream path, for example /streams/{path}, for error messages |
strip | pathname without the prefix. strip returns a path without the prefix unchanged |
canonicalizeForkSource | The stream id of a fork source. It strips the prefix when the source has it, and otherwise removes one leading / |
Http.securityHeaders
declare const securityHeaders: Readonly<{
"x-content-type-options": "nosniff";
"cross-origin-resource-policy": "cross-origin";
}>;
securityHeaders is the frozen record of the headers that app, routes, and read add to every response.
Live sockets
live=websocket is a Streamsy extension. Only the Cloudflare object host accepts the upgrade. See Follow streams over WebSockets. read and app answer live=websocket with 426 Upgrade Required after the offset checks, so a client falls back to long-poll. These exports hold the frames and close codes of the streamsy-live.v1 protocol, for hosts and clients.
Http.LiveCloseCode
declare const LiveCloseCode: {
readonly StreamClosed: 1000;
readonly InternalError: 1011;
readonly Restart: 1012;
readonly CatchUpRequired: 4100;
readonly BadMessage: 4400;
readonly NotFound: 4404;
readonly Gone: 4410;
};
type LiveCloseCode = (typeof LiveCloseCode)[keyof typeof LiveCloseCode];
LiveCloseCode names the close codes of a live socket. closeCodeForStatus maps a read status to one: 404 to NotFound, 410 to Gone, and any other status to InternalError.
Http.openFrame and Http.controlFrame
declare const LIVE_SOCKET_PROTOCOL: "streamsy-live.v1";
declare function openFrame(contentType: string, streamNextOffset: string): string;
declare function controlFrame(batch: Http.LiveBatch): string;
declare function closeCodeForStatus(status: number): Http.LiveCloseCode;
interface LiveBatch {
readonly nextOffset: string;
readonly cursor: string;
readonly upToDate: boolean;
readonly closed: boolean;
}
openFrame returns the JSON text of the first frame, { type: "open", protocol, contentType, streamNextOffset }. controlFrame returns the JSON text of a control frame. It follows the SSE control rules: a closed batch has streamClosed and no streamCursor or upToDate. Http.nextCursor(previous) is an Effect that returns the cursor a long-poll response would carry after previous.
Http.isLiveUpgrade and Http.upgradeRequired
declare function isLiveUpgrade(request: Request): boolean;
declare function upgradeRequired(): Response;
declare const LIVE_PING: "ping";
declare const LIVE_PONG: "pong";
isLiveUpgrade is true for a GET with Upgrade: websocket and live=websocket. upgradeRequired returns the 426 answer, with Upgrade: websocket and Cache-Control: no-store. LIVE_PING is the client heartbeat, and LIVE_PONG is the runtime's answer.
Shutdown
ShutdownSignal lets a host stop live reads before it closes. When the host starts to drain, a parked long poll answers 204 with its offset and cursor, and an open SSE body ends after its last whole batch. The client then reconnects as after a timeout. Serve.layer from @streamsy/serve provides the signal and drains it. See Clean shutdown.
Http.ShutdownSignal
class ShutdownSignal extends Context.Service<ShutdownSignal, Http.ShutdownSignalService>()(
"@streamsy/core/ShutdownSignal",
) {}
ShutdownSignal is the service key of the shutdown signal, and its service is a ShutdownSignalService. The service is optional. A live read looks it up with Effect.serviceOption, so a host without it, such as the Durable Object host, serves live reads with no drain.
Http.layerShutdownSignal
declare const layerShutdownSignal: Layer.Layer<Http.ShutdownSignal>;
layerShutdownSignal is a Layer that provides a new signal with no live reads. Provide it to the routes, and call drain before the routes close.
Http.ShutdownSignalService
interface ShutdownSignalService {
readonly draining: Effect.Effect<void>;
readonly track: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
readonly trackStream: <A, E, R>(stream: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>;
readonly drain: (timeout: Duration.Input) => Effect.Effect<void>;
readonly active: Effect.Effect<number>;
}
ShutdownSignalService is the service of ShutdownSignal.
| Member | Does |
|---|---|
draining | Completes when the drain starts. It never fails |
track | Counts a live read while effect runs |
trackStream | Counts a live read while stream runs |
drain | Starts the drain, then waits until no live read runs or timeout passes. A second call is safe |
active | Returns the number of live reads that run now |
A long poll that starts after the drain started answers 204 at once.