Serve
Reference for the Serve namespace in @streamsy/serve. It mounts read routes, serves JSON values, and drains live reads when a host stops.
import { Serve } from "@streamsy/serve";
import type { Duration, Effect, Layer, Runtime, Schema } from "effect";
import type { HttpRouter, HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";
import type { Http, StreamAddress, Streamsy } from "@streamsy/core";
import type { ShutdownSignal } from "@streamsy/core/http";
import type { StreamRoute } from "@streamsy/core/protocol";
import type { CanonicalValue } from "@streamsy/serve/contract";Serve builds the HTTP read routes for streams and Durable State, and the responses for computed JSON values. Serve.layer serves the routes and drains live reads when the host stops. See Serve application reads and Clean shutdown.
The error classes and ServeError are on the Serve errors page.
Serve.mount
declare function mount<P, A, K, RD, RE, const Path extends `/${string}`>(
declaration: {
readonly paramSchema: StreamRoute.PathSchema<P>;
readonly at: (params: P) => Streamsy.Address<A, K, RD, RE>;
},
path: Path & ExactPath<Path, NoInfer<P>>,
options?: Serve.ReadOptions,
): Layer.Layer<
never,
never,
| HttpRouter.HttpRouter
| HttpRouter.Request<"Error", Serve.InvalidParams>
| HttpRouter.Request<"Error", Serve.ProtocolVersionUnsupported>
| HttpRouter.Request<"Error", Serve.ResumeRejected>
| HttpRouter.Request<"Error", Serve.TransportUnavailable>
| HttpRouter.Request<"Error", Serve.WireEncodeFailed>
| HttpRouter.Request.From<"Requires", Exclude<K, HttpRouter.Provided>>
>;
// These local types have no exported names. They require the path's param
// names to match P when Path is a literal.
type Names<S extends string> = S extends `${string}:${infer N}/${infer Tail}`
? N | Names<Tail>
: S extends `${string}:${infer N}`
? N
: never;
type ExactPath<Path extends string, P> = `/${string}` extends Path
? unknown
: [Exclude<Names<Path>, keyof P>, Exclude<keyof P, Names<Path>>] extends [never, never]
? unknown
: never;
mount adds a route at path. For each request, the route decodes the path params with declaration.paramSchema and calls declaration.at with them to get the address. It serves an address that has collections with state, and any other address with stream. mount does not create a stream.
When path is a literal, its param names must be exactly the keys of P. The compiler rejects a missing name, an extra name, or an optional param such as :seat?. It skips this check for a path typed as `/${string}`.
When the params do not decode, or declaration.at throws, the route fails with Serve.InvalidParams. The route serves GET and HEAD, and answers any other method with 405 and allow: GET, HEAD.
mount decodes percent-encoded params, but the protocol routes use the raw encoded id. Use URL-safe stream segments. When two routes have the same path shape, the Layer build fails.
Serve.route
declare function route<E, R>(
path: HttpRouter.PathInput,
handler: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,
): Layer.Layer<
never,
never,
| HttpRouter.HttpRouter
| HttpRouter.Request.From<"Error", E>
| HttpRouter.Request.From<"Requires", Exclude<R, HttpRouter.Provided>>
>;
route adds a route for every method at path, so no request for path falls through to a protocol wildcard route. It runs handler for GET and HEAD. It answers any other method with 405, allow: GET, HEAD, and Http.securityHeaders.
The Layer type carries the errors and services of handler as router request types. route does not decode params, and it does not change the response of handler to a HEAD request.
Serve.params
declare const params: <P>(declaration: {
readonly paramSchema: StreamRoute.PathSchema<P>;
}) => Effect.Effect<P, Serve.InvalidParams, HttpRouter.RouteContext>;
params decodes the path params of the matched route with declaration.paramSchema. When they do not decode, params fails with Serve.InvalidParams, with parameter: "params" and detail: "Invalid path parameters".
Serve.stream
declare function stream<A, K, RD, RE>(
address: Streamsy.Address<A, K, RD, RE>,
options?: Serve.ReadOptions,
): Effect.Effect<
HttpServerResponse.HttpServerResponse,
| Serve.ProtocolVersionUnsupported
| Serve.ResumeRejected
| Serve.TransportUnavailable
| Serve.WireEncodeFailed,
K | HttpServerRequest.HttpServerRequest | HttpRouter.RouteContext
>;
stream answers the request with Http.read on address, and adds the Durable Streams version and contract headers. It serves catch-up reads, long polls, SSE, and HEAD requests.
stream accepts protocol version 1, and treats a request with no version header as version 1. Any other version fails with Serve.ProtocolVersionUnsupported. When the request sends a contract header that differs from the current fingerprint, stream fails with Serve.ResumeRejected and reason "contract-changed".
A request other than HEAD resumes when its offset is present and is neither -1 nor now. An invalid offset fails with Serve.ResumeRejected and reason "invalid-offset". A resume fails with reason "history-unavailable" when the stream does not exist or was deleted. A request that does not resume answers 404 when the stream does not exist, and 410 when it was deleted.
A StorageFault or TransportFault from the read fails with Serve.TransportUnavailable. When the read fails with NotSupported, stream answers 400. The error type lists Serve.WireEncodeFailed because stream shares its read path with state, but only state fails with it.
Serve.state
declare function state<C extends StreamAddress.Collections, K, RD, RE>(
address: StreamAddress.StateAddress<C, RD, RE> &
Streamsy.Address<StreamAddress.CollectionsEvent<C>, K, RD, RE>,
options?: Serve.ReadOptions,
): Effect.Effect<
HttpServerResponse.HttpServerResponse,
| Serve.ProtocolVersionUnsupported
| Serve.ResumeRejected
| Serve.TransportUnavailable
| Serve.WireEncodeFailed,
K | HttpServerRequest.HttpServerRequest | HttpRouter.RouteContext
>;
state serves the change stream of a Durable State address with the state version and contract headers. It follows the version, resume, and fault rules of stream.
state sends stored control messages in order with the changes. It does not create snapshots, and it answers a request with x-streamsy-state-reset: snapshot with 400. See State routes.
The contract fingerprint of state includes the collection names and their key fields. When the collection metadata of the address does not decode, state fails with Serve.WireEncodeFailed.
Serve.value
declare const value: <A, I extends CanonicalValue, E, R, RE>(
schema: Schema.Codec<A, I, never, RE>,
compute: Effect.Effect<A, E, R>,
options?: Serve.ValueOptions | undefined,
) => Effect.Effect<
HttpServerResponse.HttpServerResponse,
E | Serve.ContractChanged | Serve.WireEncodeFailed,
R | RE | HttpServerRequest.HttpServerRequest | HttpRouter.RouteContext
>;
value runs compute, encodes the result with schema, and answers with the result as canonical JSON and an ETag. When compute fails, value fails with the same error. When schema cannot encode the result, or the encoded value holds a non-finite number, value fails with Serve.WireEncodeFailed.
When the request sends a value contract header that differs from the fingerprint, value fails with Serve.ContractChanged before it runs compute. The fingerprint covers the route, the cache policy, and options.contract.
When if-none-match holds * or the current ETag, value answers 304. The header can list several tags separated by commas, and a weak tag matches its strong form. value runs compute and encodes the result before it compares the tags. A HEAD request also runs compute, and gets the headers with an empty body.
Serve.layer
declare const layer: <
A,
E,
R,
HE = never,
HR = HttpRouter.Request.Only<"Requires", R> | HttpRouter.Request.Only<"GlobalRequires", R>,
>(
routes: Layer.Layer<A, E, R>,
options?: Serve.LayerOptions<R, HE, HR>,
) => Layer.Layer<
A,
HttpRouter.Request.Without<E>,
| HttpServer.HttpServer
| Exclude<Exclude<Exclude<HR, HttpRouter.GlobalProvided>, HttpRouter.HttpRouter>, ShutdownSignal>
| Exclude<Exclude<HttpRouter.Request.Without<R>, HttpRouter.HttpRouter>, ShutdownSignal>
>;
layer serves routes with HttpRouter.serve and provides the ShutdownSignal that live reads watch. The host provides the storage Layer and the listener Layer, and runs the result with the runMain of its runtime.
When the Layer closes, it drains live reads first. A parked long poll answers 204 with its offset and cursor, and an open SSE body ends after its last whole batch. The Layer waits until no live read runs or until drainTimeout passes, and then interrupts any handler that still runs. The default drainTimeout is 2 seconds.
See Run a process server for the Layer and runtime setup.
Serve.teardown
declare const teardown: Runtime.Teardown;
teardown chooses the process exit code when a long-running host stops. Pass it to the runMain of your runtime as { teardown: Serve.teardown }.
When the main Effect ends with interrupts only, teardown exits with code 0, whether or not an OS signal caused the interrupt. It passes every other exit to Runtime.defaultTeardown, so a startup failure still exits with a non-zero code. A Layer.launch main ends only on a failure or an interrupt.
Serve.ReadOptions
interface ReadOptions extends Http.ReadOptions {
readonly contract?: CanonicalValue;
}
ReadOptions holds the read settings of mount, stream, and state, and an optional contract revision.
| Field | Meaning |
|---|---|
sseDeadlineMs | The lifetime of an SSE response. The default is 60 s |
cacheVisibility | private or public in the read's cache-control header. The default is private |
contract | Extra metadata in the contract fingerprint. The default is null |
sseDeadlineMs must be finite and positive. When it is not, Http.read dies with a RangeError when the handler runs. Change contract when a schema changes but the stream address and the collection metadata do not.
Serve.ValueOptions
interface ValueOptions {
readonly cache?: {
readonly visibility: "private" | "public";
readonly maxAgeSeconds: number;
readonly mustRevalidate: boolean;
};
readonly contract?: CanonicalValue;
}
ValueOptions holds the cache policy of value and an optional contract revision.
| Field | Meaning |
|---|---|
cache.visibility | private or public in cache-control |
cache.maxAgeSeconds | The max-age value in seconds |
cache.mustRevalidate | true to add must-revalidate to cache-control |
contract | Extra metadata in the value contract fingerprint. The default is null |
When cache is absent, the policy is private, max-age=0, must-revalidate. When cache is present, all three cache fields are required. Change contract when the schema or the computation changes but the route and the cache policy do not.
Serve.LayerOptions
type LayerOptions<
R = never,
HE = never,
HR = HttpRouter.Request.Only<"Requires", R> | HttpRouter.Request.Only<"GlobalRequires", R>,
> = NonNullable<Parameters<typeof HttpRouter.serve<unknown, unknown, R, HE, HR>>[1]> & {
readonly drainTimeout?: Duration.Input | undefined;
};
LayerOptions holds the options of HttpRouter.serve and one more field, drainTimeout. drainTimeout is the longest time that layer waits for live reads to end, and defaults to 2 seconds. The other fields mean what they mean for HttpRouter.serve.
DurableObjectStorage
Reference for the DurableObjectStorage namespace in @streamsy/storage/durable-object. It keeps streams in the SQLite storage of a Cloudflare Durable Object.
Serve errors
Reference for the errors in @streamsy/serve. Each Serve handler fails with a tagged error class that renders as a public JSON error response.