Skip to Content
Reference@streamsy/serve

Cloudflare

Reference for the host exports in @streamsy/serve/cloudflare. They route protocol requests to Durable Objects and schedule work over each object's storage.

import * as Cloudflare from "@streamsy/serve/cloudflare";
import type * as Workers from "@cloudflare/workers-types";
import { Context, type Effect, type Layer, type Option, type Schedule, type Scope } from "effect";
import type { HttpClientError, HttpRouter, HttpServerRespondable } from "effect/http";
import type { Storage, StorageFault, Streamsy } from "@streamsy/core";

The Cloudflare host sends each protocol request to the Durable Object that owns the stream. Each object has its own storage, routes, and alarm. See Run on Cloudflare.

Object host

Cloudflare.StreamsyObject

declare const StreamsyObject: {
  make: <Env = unknown, R = never, L = never>(
    configuration: Cloudflare.ObjectConfiguration<Env, R, L>,
  ) => new (state: Workers.DurableObjectState, env: Env) => ObjectHost<Env, R, L>;
};

// ObjectHost has no exported name. Keep the package's nominal instance type,
// which extends the platform DurableObject and implements ObjectInstance.
type ObjectHost<Env, R, L> = InstanceType<
  ReturnType<typeof Cloudflare.StreamsyObject.make<Env, R, L>>
>;

Cloudflare.StreamsyObject.make returns a Durable Object class for an ObjectConfiguration. On the first fetch or alarm, the object acquires its storage and builds its routes. After an acquisition succeeds, every later fetch and alarm reuses it.

When the acquisition fails, fetch answers 503 with Retry-After: 1, and the next fetch or alarm acquires again. The host closes the scope of the failed acquisition first. When the acquisition fails during an alarm, the alarm Promise rejects, so the platform retries the alarm.

The host reconciles the wakeup due times after the acquisition, and after every PUT, POST, and DELETE request, rejected requests included. It also reconciles after a request that calls Wakeups.touch. When a route dies, the object answers 500 with the protocol security headers. The object does not log requests.

Cloudflare.ObjectConfiguration

interface ObjectConfiguration<Env, R = never, L = never> {
  readonly app: ObjectApp<R | L>;
  readonly wakeups?: ReadonlyArray<Cloudflare.WakeupSource<Storage | R | L>>;
  readonly layer: (
    state: Workers.DurableObjectState,
    env: Env,
  ) => Layer.Layer<Storage | R, StorageFault, L>;
  readonly links?: (env: Env) => ReadonlyArray<Cloudflare.LinkClient<L>>;
  readonly live?: Cloudflare.LiveConfiguration;
}

// ObjectApp has no exported name. It is the route Layer that the object hosts accept.
type ObjectApp<R = never> = Layer.Layer<
  never,
  never,
  | HttpRouter.HttpRouter
  | HttpRouter.Request.From<"Requires", Storage | Cloudflare.Wakeups | R>
  | HttpRouter.Request.From<"Error", HttpServerRespondable.Respondable>
>;

Cloudflare.ObjectConfiguration holds the routes, the local services, the wakeups, the links, and the live sockets of an object class.

FieldMeaning
appThe route Layer. It can use storage, Wakeups, the local services R, and the linked services L
layerBuilds the Layer of local storage and services from the object state and the environment
wakeupsMore wakeups. The host always adds stream expiry
linksBuilds the clients of streams that live on other objects
liveTurns on live=websocket. Off by default. See LiveConfiguration

The host provides the alarm slot from state.storage. It builds the linked services before the local Layer, so the local Layer can use them. When the local Layer also provides a linked stream, the acquisition fails with StorageFault. Keep linked streams out of the local storage group.

Cloudflare.ObjectInstance

interface ObjectInstance {
  fetch(request: Request): Promise<Response>;
  alarm(info?: Workers.AlarmInvocationInfo): Promise<void>;
  webSocketMessage(ws: Workers.WebSocket, message: string | ArrayBuffer): Promise<void>;
  webSocketClose(
    ws: Workers.WebSocket,
    code: number,
    reason: string,
    wasClean: boolean,
  ): Promise<void>;
  webSocketError(ws: Workers.WebSocket, error: unknown): Promise<void>;
}

Cloudflare.ObjectInstance is the shape of an object: its fetch, alarm, and socket handler methods. alarm ignores info. No HTTP request can run an alarm turn.

The socket handlers serve live sockets. The runtime answers the client's ping itself, so webSocketMessage runs only for another message, and it closes the socket with 4400. webSocketClose does nothing, because the runtime answers close frames from compatibility date 2026-04-07. webSocketError logs the error.

Live sockets

live=websocket is a Streamsy extension to Durable Streams HTTP. The object accepts the socket with the WebSocket Hibernation API, so it can hibernate while its readers wait. See Follow streams over WebSockets.

Cloudflare.LiveConfiguration

interface LiveConfiguration {
  readonly websocket: true | Cloudflare.LiveSocketOptions;
}

Cloudflare.LiveConfiguration turns on live sockets for an object class. true uses the default options. StreamsyObject.make throws a RangeError when an option is out of range.

With live set, fetch takes a GET with Upgrade: websocket and live=websocket to a stream under prefix. It reads the stream through the object's routes, as a catch-up GET at the same URL. When that read does not answer 200, the upgrade gets the read's answer. A missing offset gets 400. Otherwise the object answers 101, sends the catch-up frames, and keeps the socket's offset in the socket attachment.

At the end of each fetch and alarm turn, the object pushes the stream ids that the event committed. The push reads each stream from each distinct socket offset and sends the frames to every socket at that offset. Every other request goes to the routes as before.

Close codeWhen
1000The stream closed, after a control frame with streamClosed
1011A push read failed with another status, or a push failed
1012The socket attachment has an unknown version
4100A connect passed maxCatchUpBytes, or a push passed maxPushBytes
4400The client sent a message other than ping
4404A push read answered 404
4410A push read answered 410

Cloudflare.LiveSocketOptions

interface LiveSocketOptions {
  readonly prefix?: `/${string}`;
  readonly maxSockets?: number;
  readonly maxPushBytes?: number;
  readonly maxCatchUpBytes?: number;
}
FieldMeaning
prefixThe prefix of the stream routes, as in Http.routes and router. The default is /
maxSocketsOpen sockets per object, up to 32,768. An upgrade over the limit gets 503. The default is 1,000
maxPushBytesData bytes a socket gets in one event before it closes with 4100. The default is 1 MiB
maxCatchUpBytesData bytes a connect sends before it closes with 4100. The default is 4 MiB

Worker routing and placement

Cloudflare.router

declare function router<Env>(options: Cloudflare.RouterOptions<Env>): Workers.ExportedHandler<Env>;

Cloudflare.router returns a Worker fetch handler that forwards each protocol request to the object that placement names. Placement gets the stream path without the mount prefix. The object gets the original request unchanged, with its encoded path segments, query, headers, and body. The router sends a fork request to the object of the child stream.

Authenticate the caller before you pass the request to the router. The router serves protocol paths only, so route Serve paths in your own Worker code.

ConditionResponse
Path starts with /__404, without calling an object
Path has no stream id under the prefix400, without calling an object
Placement returns an empty or non-string name400, without calling an object
Placement throws500, without calling an object

A fork source and its child must live on the same object. Do not change the placement of an object that holds data.

Cloudflare.rule

declare function rule<Params>(spec: OwnerRule<Params>): ErasedOwnerRule;

// These rule shapes have no exported names. OwnerRule keeps the type of the
// decoded params. ErasedOwnerRule hides it, so one byRoute table can hold rules
// with different params.
interface OwnerRule<Params> {
  readonly stream: { parse(id: string): Option.Option<Params> };
  owner(params: Params): string;
}
interface ErasedOwnerRule {
  readonly stream: { parse(id: string): Option.Option<unknown> };
  owner(params: never): string;
}

Cloudflare.rule returns spec with owner typed to take the decoded params of stream. Pass the result to Placement.byRoute. owner has method syntax, so the compiler still infers the params of each owner, and one table can hold rules with different params.

Cloudflare.Placement

interface Placement {
  readonly name: (streamPath: string) => string;
}

declare const Placement: {
  readonly byStream: () => Cloudflare.Placement;
  readonly byKey: (key: (streamPath: string) => string) => Cloudflare.Placement;
  readonly byRoute: (rules: ReadonlyArray<ErasedOwnerRule>) => Cloudflare.Placement;
};

// ErasedOwnerRule has no exported name. Build these values with rule.
interface ErasedOwnerRule {
  readonly stream: { parse(id: string): Option.Option<unknown> };
  owner(params: never): string;
}

Cloudflare.Placement names the object that owns a stream path. It has three constructors:

ConstructorObject name
byStream()The stripped stream path, unchanged
byKey(key)The result of key(streamPath)
byRoute(rules)The owner result of the first rule whose stream parses the path

When the stream of a rule cannot decode a segment, byRoute tries the next rule. When no rule matches, byRoute returns an empty string, and the router answers 400.

Cloudflare.RouterOptions

interface RouterOptions<Env> {
  readonly namespace: (env: Env) => Workers.DurableObjectNamespace;
  readonly placement?: Cloudflare.Placement;
  readonly prefix?: `/${string}`;
}

Cloudflare.RouterOptions holds the object namespace, the placement, and the protocol mount prefix of router.

FieldDefaultMeaning
namespaceRequiredReturns the Durable Object namespace binding from the Worker environment
placementPlacement.byStream()Names the object of each stream path, without the prefix
prefix/The protocol mount prefix

The router adds a trailing slash to the prefix when it has none, and then strips the prefix from each path. The object gets the original path, so its protocol mount must use the same prefix.

Wakeups

Cloudflare.Wakeup

interface Wakeup<R = never> {
  readonly name: string;
  readonly next: Effect.Effect<Option.Option<number>, StorageFault, R>;
  readonly run: Effect.Effect<void | Cloudflare.WakeupProgress, unknown, R>;
  readonly retry?: Schedule.Schedule<unknown>;
  readonly retryable?: (cause: Cause.Cause<unknown>) => boolean;
  readonly deferred?: Effect.Effect<number, StorageFault, R>;
  readonly bind?: (host: Cloudflare.WakeupHost) => Effect.Effect<void>;
  readonly changed?: Effect.Effect<void>;
}

declare const Wakeup: {
  make: <R>(wakeup: Cloudflare.Wakeup<R>) => Cloudflare.Wakeup<R>;
};

Cloudflare.Wakeup is a kind of scheduled work in an object: a bounded, idempotent run, and a next that reads its due time from committed state. Wakeup.make runs run under the permit of the object for that name. The permit is not reentrant, so a run must not call its own run.

FieldMeaning
nameA name unique in the object. Stream expiry uses streamsy/expiry
nextThe next due time in epoch milliseconds, or None when there is no work
runThe work, which can run more than once. Returns { more: true } when it stops at its bound with due work left
retryTiming only. The runner calls the schedule once per retryable failed pass with no input
retryableOptional predicate on a failed run's cause. false stops automatic retries without stepping the schedule
deferredThe number of failed units awaiting another attempt, including stopped units. Without it, status reports 0
bindReceives the wakeup's host once at acquisition, before the initial alarm reconciliation
changedRuns after a run or failed deadline read updates the host's retry state

The host runs stream expiry first, and then the other wakeups in declaration order. Two wakeups with the same name fail the acquisition. When one wakeup fails in next or run, the others still run.

Without retry, the backoff after each failure doubles from 1 second, up to 1 hour. A run that reports no more work also backs off when work that was due before it started is still due. When a finite retry schedule ends or its step dies, the host stops retrying. A dying step is logged. A retryable predicate returning false, or a next failure with StorageFault.retryable: false, also stops automatic retries without stepping the schedule. WakeupHost.retry or a new acquisition resumes the wakeup. A run that makes progress resets the failure count. The backoff state is in memory, so an eviction clears it.

Cloudflare.WakeupHost

interface WakeupHost {
  readonly reconcile: Effect.Effect<void>;
  readonly retry: Effect.Effect<void>;
  readonly state: Effect.Effect<{
    readonly failures: number;
    readonly retryAt: Option.Option<number>;
  }>;
}

Cloudflare.WakeupHost supplies effects bound to one acquired wakeup. They also work outside requests. See Alarms.

FieldMeaning
reconcileRecomputes the alarm from every wakeup's next deadline; it can also run inside a wakeup's run
retryClears this wakeup’s backoff floor without resetting its retry schedule
stateReads consecutive failed passes and the automatic or reconciled explicitly requested retry deadline

Cloudflare.Wakeups

class Wakeups extends Context.Service<
  Wakeups,
  {
    readonly touch: Effect.Effect<void, never, never>;
    readonly reconcile: Effect.Effect<void, never, never>;
    readonly status: Effect.Effect<
      ReadonlyArray<{
        readonly name: string;
        readonly next: Option.Option<number>;
        readonly failures: number;
        readonly retryAt: Option.Option<number>;
        readonly deferred: number;
      }>,
      never,
      never
    >;
  }
>()("@streamsy/serve/cloudflare/Wakeups") {}

Cloudflare.Wakeups is the service key of the wakeup scheduler of an object.

MemberMeaning
touchMarks the current request, so the host reconciles when its handler returns
reconcileReads the due times and arms the alarm for the earliest one, or clears the alarm when no work remains
statusReads the due time, the failure count, the retry time, and the deferred count of each wakeup

Call touch before the handler returns. When a streamed body queues work after the handler returns, call reconcile instead. Work outside a request also calls reconcile.

reconcile does not run due work inside the request. It arms the alarm for now + 1 instead. An alarm turn arms a recovery alarm 30 seconds ahead before it runs due work, and reconciles again after the work. In status, retryAt is the earliest time at which the backoff lets the wakeup run. deferred is the count that the deferred field of the wakeup reports, such as failed bindings, including stopped ones, in either durability mode of a ProjectionWakeup. When next or deferred fails inside status, status dies.

Cloudflare.alarmSlotLayer

declare function alarmSlotLayer(
  storage: Workers.DurableObjectStorage,
): Layer.Layer<AlarmSlot, never, never>;

// AlarmSlot has no exported name. It is the object's one platform alarm slot.
interface AlarmSlot extends Context.ServiceClass.Shape<
  "@streamsy/serve/cloudflare/AlarmSlot",
  {
    readonly current: Effect.Effect<Option.Option<number>, never, never>;
    readonly arm: (at: number) => Effect.Effect<void, never, never>;
    readonly clear: Effect.Effect<void, never, never>;
  }
> {}

Cloudflare.alarmSlotLayer provides the alarm service of the scheduler with getAlarm, setAlarm, and deleteAlarm on the storage of the object. When no alarm is set, the slot reads None. When a platform Promise rejects, the Effect dies.

StreamsyObject.make provides this Layer itself. An Alchemy object must include it in the Layer that it passes to objectHandlers.

Cloudflare.WakeupProgress

interface WakeupProgress {
  readonly more: boolean;
}

Cloudflare.WakeupProgress is the result of a bounded run. more is true when the run stopped at its bound with work left. When more is true and the work is still due, the scheduler arms the alarm again at once, without backoff.

Cloudflare.WakeupSource

type WakeupSource<R = never> =
  | Cloudflare.Wakeup<R | Cloudflare.Wakeups>
  | Effect.Effect<Cloudflare.Wakeup<R | Cloudflare.Wakeups>, never, R | Scope.Scope>;

Cloudflare.WakeupSource is a wakeup, or an Effect that builds one in the storage scope of the object. Requests and wakeups get the same services from the acquisition.

Cloudflare.ObjectStreams

declare const ObjectStreams: {
  readonly layer: <const Keys extends ReadonlyArray<Streamsy.Any>>(
    group: Streamsy.Group<Keys>,
    options: Cloudflare.ObjectStreamsOptions,
  ) => Layer.Layer<Streamsy.Services<Streamsy.Group<Keys>>, never, never>;
};

Cloudflare.ObjectStreams.layer provides stream services that send each request to the owner object through its stub, not over the network. The owner must serve an Http.routes mount at prefix. The client declares that the owner supports producers and expected offsets.

The client answers 404 without calling an object when a request is outside the prefix or the group. A placement failure answers 400 or 500, as in router. An Effect transport gets the context, the tracing, and the interruption of the caller.

interface ObjectLink<Keys extends ReadonlyArray<Streamsy.Any>> {
  readonly group: Streamsy.Group<Keys>;
  readonly prefix: `/__${string}`;
  readonly routes: Cloudflare.LinkRoutes<Streamsy.Services<Streamsy.Group<Keys>>>;
  readonly client: (
    objects: Workers.DurableObjectNamespace | Cloudflare.ObjectFetch,
  ) => Cloudflare.LinkClient<Streamsy.Services<Streamsy.Group<Keys>>>;
}

declare const ObjectLink: {
  readonly make: <const Keys extends ReadonlyArray<Streamsy.Any>>(
    options: Cloudflare.ObjectLinkOptions<Keys>,
  ) => Cloudflare.ObjectLink<Keys>;
};

Cloudflare.ObjectLink.make declares a link: an internal mount on the owner object, and the client that other objects use to reach it. Add routes to the app of the owner, and return client(objects) from the links of each caller.

make throws a RangeError unless the prefix starts with /__ followed by a character other than /. The usual protocol prefix checks also apply. The public routers of the package reject a reserved path before they call an object.

access applies to every stream of the link, Durable State wake streams included. Use full when the producer must create a missing wake stream with PUT. A link trusts any caller that holds a stub of the object. See Connect Durable Objects.

Cloudflare.ObjectFetch

type ObjectFetch = (
  name: string,
  request: Request,
) => Effect.Effect<Response, HttpClientError.HttpClientError, never>;

Cloudflare.ObjectFetch is an Effect transport that sends a web request to the object with a given name. ObjectStreams.layer and ObjectLink.client take this transport or a native namespace. To build one from Alchemy stubs, use Alchemy.objectFetch.

Cloudflare.ObjectStreamsOptions

interface ObjectStreamsOptions {
  readonly objects: Workers.DurableObjectNamespace | Cloudflare.ObjectFetch;
  readonly placement: Cloudflare.Placement;
  readonly prefix: `/${string}`;
  readonly headers?: Readonly<Record<string, string>>;
}

Cloudflare.ObjectStreamsOptions holds the owner transport, the placement, and the mount of ObjectStreams.layer.

FieldMeaning
objectsThe owner namespace or an Effect transport
placementThe same placement rules that the public router uses
prefixThe protocol mount on the owner, such as /streams or /__wake
headersExtra headers for every request. The default is {}

Cloudflare.ObjectLinkOptions

interface ObjectLinkOptions<Keys extends ReadonlyArray<Streamsy.Any>> {
  readonly group: Streamsy.Group<Keys>;
  readonly prefix: `/__${string}`;
  readonly placement: Cloudflare.Placement;
  readonly access: Cloudflare.LinkAccess;
}

Cloudflare.ObjectLinkOptions gives both sides of a link the same group, internal mount, and placement rules.

FieldMeaning
groupThe streams that the owner serves to other objects
prefixThe reserved internal mount. ObjectLink.make checks it
placementNames the owner object of each stream
accessThe methods that the owner mount allows

Cloudflare.LinkAccess

type LinkAccess = "read" | "append" | "full";

Cloudflare.LinkAccess sets the methods that the owner mount of a link allows. read allows OPTIONS, GET, and HEAD. append adds POST, and full adds PUT and DELETE. A method that the access does not allow gets 405.

Cloudflare.LinkClient

interface LinkClient<I> {
  readonly streams: ReadonlyArray<Streamsy.Any>;
  readonly layer: Layer.Layer<I, never, never>;
}

Cloudflare.LinkClient is the client side of a link in a caller object. streams lists the remote stream classes, and layer provides their clients. During the acquisition, the host checks that the local Layer provides none of streams.

Cloudflare.LinkRoutes

type LinkRoutes<I> = Layer.Layer<
  never,
  never,
  HttpRouter.HttpRouter | HttpRouter.Request.From<"Requires", Exclude<I, HttpRouter.Provided>>
>;

Cloudflare.LinkRoutes is the route Layer of a link on the owner object. Its request requirements are the linked stream services that the router does not provide itself.

On this page