/**
* `DurabilitySocket` example: a Durable Object that browsers talk to directly.
*
* Clients call `inbound` handlers over one hibernatable WebSocket and receive
* `outbound` events as they happen. Creating a todo is a durable operation;
* its completion is bridged to every connected client through the lifecycle
* hook, so a crash between "accepted" and "visible" cannot lose the update.
*/
import { DurableObject } from 'cloudflare:workers';
import {
Durability,
type DurableCall,
type DurabilityLifecycleEvent,
} from 'durability';
import { DurabilitySocket, event, type SocketCall } from 'durability/socket';
import * as v from 'valibot';
type Env = { TODO_LISTS: DurableObjectNamespace<TodoList> };
const todoSchema = v.object({
id: v.string(),
title: v.pipe(v.string(), v.minLength(1)),
done: v.boolean(),
});
export type Todo = v.InferOutput<typeof todoSchema>;
type Metadata = { userId: string };
export class TodoList extends DurableObject<Env> {
readonly durability = new Durability({
context: this.ctx,
handlers: {
createTodo: async ({ payload }: DurableCall<Todo>) => {
this.ctx.storage.sql.exec(
'INSERT OR IGNORE INTO todos (id, title, done) VALUES (?, ?, ?)',
payload.id,
payload.title,
payload.done ? 1 : 0
);
return payload;
},
},
// Needed so completed lifecycle events carry the todo to broadcast.
includeResults: true,
});
readonly socket = new DurabilitySocket({
context: this.ctx,
inbound: {
list: { input: v.undefined(), handle: () => this.list() },
createTodo: {
input: v.object({ id: v.string(), payload: todoSchema }),
handle: this.durability.createTodo,
},
toggle: {
input: v.string(),
handle: (id: string, call: SocketCall<Metadata>) => {
const todo = this.list().find((candidate) => candidate.id === id);
if (!todo) {
throw new RangeError(`No todo "${id}" for ${call.metadata.userId}`);
}
const toggled = { ...todo, done: !todo.done };
this.ctx.storage.sql.exec(
'UPDATE todos SET done = ? WHERE id = ?',
toggled.done ? 1 : 0,
id
);
this.socket.updated(toggled);
return toggled;
},
},
},
outbound: {
created: event<Todo>(),
updated: event<Todo>(),
lifecycle: event<DurabilityLifecycleEvent>(),
},
// The fronting Worker authenticated the user and set this header.
metadata: (request): Metadata => ({
userId: request.headers.get('x-user-id') ?? 'anonymous',
}),
});
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
ctx.storage.sql.exec(
'CREATE TABLE IF NOT EXISTS todos (id TEXT PRIMARY KEY, title TEXT NOT NULL, done INTEGER NOT NULL)'
);
this.durability.lifecycle((lifecycleEvent) => {
if (
lifecycleEvent.type === 'attempt_settled' &&
lifecycleEvent.outcome === 'completed' &&
lifecycleEvent.result !== undefined
) {
this.socket.created(lifecycleEvent.result);
}
});
this.durability.lifecycle(this.socket.lifecycle);
}
private list(): Todo[] {
return this.ctx.storage.sql
.exec<{ id: string; title: string; done: number }>(
'SELECT id, title, done FROM todos ORDER BY rowid'
)
.toArray()
.map((row) => ({ ...row, done: row.done === 1 }));
}
override fetch(request: Request) {
return this.socket.fetch(request);
}
override webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) {
return this.socket.webSocketMessage(ws, message);
}
override webSocketClose(ws: WebSocket) {
this.socket.webSocketClose(ws);
}
override alarm(info?: AlarmInvocationInfo) {
return this.durability.alarm(info);
}
}
export default {
async fetch(request: Request, env: Env) {
const match = /^\/lists\/([^/]+)\/ws$/.exec(new URL(request.url).pathname);
if (!match?.[1]) {
return new Response('Not found', { status: 404 });
}
const userId = await authenticate(request);
if (!userId) {
return new Response('Unauthorized', { status: 401 });
}
const upgrade = new Request(request, {
headers: { ...Object.fromEntries(request.headers), 'x-user-id': userId },
});
return env.TODO_LISTS.getByName(match[1]).fetch(upgrade);
},
};
declare function authenticate(request: Request): Promise<string | undefined>;
import type { StandardSchemaV1 } from '@standard-schema/spec';
import { trace, traceFunction, traceMethods, traceStorage } from '../dev.js';
import { reportFailure, serializeError } from '../errors.js';
import { durabilitySocketMigrations } from './migrations.js';
import {
migrateCapability,
type DurabilityMigrationResult,
} from '../migrations.js';
import {
assertChannel,
defaultChannel,
engineFor,
type Engine,
} from '../scheduler/index.js';
import { isObject, isString } from '../predicates.js';
import { deserialize, serialize } from '../serialization.js';
import {
parseClientFrame,
socketMaxFrameLength,
socketProtocolErrorCode,
socketProtocolVersion,
type SocketCall,
type SocketClientFrame,
type SocketInboundHandler,
type SocketInboundMap,
type SocketInboundSchemas,
type SocketOutboundMap,
type SocketOutboundPayload,
type SocketServerFrame,
type SocketInboundMetadata,
type SocketMessageMaps,
type SocketValidatedInbound,
socketMessageMaps,
} from './protocol.js';
/** The Durable Object state a socket needs: SQLite storage and hibernatable WebSockets. */
export type DurabilitySocketContext = Pick<
DurableObjectState,
'storage' | 'acceptWebSocket' | 'getWebSockets' | 'setWebSocketAutoResponse'
>;
export type DurabilitySocketConfig<
Inbound extends SocketInboundMap,
Outbound extends SocketOutboundMap,
Metadata extends SocketInboundMetadata<Inbound>,
Schemas extends Record<keyof Inbound, StandardSchemaV1> =
SocketInboundSchemas<Inbound>,
> = {
context: DurabilitySocketContext;
/**
* Methods clients may call, keyed by the names they become on the client.
* Each validates its input with a Standard Schema before `handle` runs.
*/
inbound: Inbound & SocketValidatedInbound<Inbound, Schemas>;
/** Events the object may push, keyed by the methods they become on this instance. */
outbound: Outbound;
/** Outbound events kept for replay to reconnecting clients. Defaults to 1000. */
retention?: number;
/**
* Partitions the object's sockets, so a library and the application can each
* have one. Defaults to `default`. Each connection belongs to the channel
* whose `fetch` accepted it, and its frames reach that instance's handlers
* whichever instance `webSocketMessage` delegates to.
*/
channel?: string;
} & SocketMetadataOption<Metadata>;
type SocketMetadataConfig<Metadata> = {
/**
* Captures trusted per-connection data from the upgrade request. Stored in
* the WebSocket attachment, so it survives hibernation without re-auth.
* Required when a handler's `SocketCall<…>` metadata excludes `undefined`.
*/
metadata: (request: Request) => Metadata | Promise<Metadata>;
};
type SocketMetadataOption<Metadata> = undefined extends Metadata
? Partial<SocketMetadataConfig<Metadata>>
: SocketMetadataConfig<Metadata>;
/** Thrown to the caller when an inbound payload fails its schema. */
export class SocketInputError extends Error {
readonly issues: readonly StandardSchemaV1.Issue[];
constructor(method: string, issues: readonly StandardSchemaV1.Issue[]) {
super(
`Invalid input for "${method}": ${issues.map((issue) => issue.message).join('; ')}`
);
this.name = 'SocketInputError';
this.issues = issues;
}
}
type Attachment<Metadata> = {
metadata: Metadata;
hasMetadata: boolean;
names: string[];
channel: string;
};
type FrameHandler = (ws: WebSocket, frame: SocketClientFrame) => Promise<void>;
/** The socket instances of each Durable Object, by channel, so any of them can route a frame. */
const frameHandlersByObject = new WeakMap<Engine, Map<string, FrameHandler>>();
// A configuration problem rather than a protocol violation, so clients reconnect.
const channelMissingCloseCode = 1011;
// Service Restart: the client reconnects, and the new upgrade captures metadata.
const metadataMissingCloseCode = 1012;
type EventRow = {
seq: number;
name: string;
payload: string;
};
declare const WebSocketPair: {
new (): { 0: WebSocket; 1: WebSocket };
};
declare const WebSocketRequestResponsePair: {
new (request: string, response: string): WebSocketRequestResponsePair;
};
const reservedOutboundNames = new Set(['status', 'resync']);
const sendFrame = (ws: WebSocket, frame: SocketServerFrame): void => {
trace('socket.send', { frame });
let text = JSON.stringify(frame);
if (text.length > socketMaxFrameLength) {
if (frame.type === 'event') {
reportFailure(
'durability.socket.event_too_large',
{ name: frame.name, seq: frame.seq },
new Error('Outbound event exceeds the frame limit')
);
return;
}
text = JSON.stringify({
v: socketProtocolVersion,
type: 'error',
id: frame.id,
error: {
name: 'SocketFrameTooLargeError',
message: `Response to "${frame.type}" exceeds ${socketMaxFrameLength} characters`,
},
} satisfies SocketServerFrame);
}
try {
ws.send(text);
} catch (error) {
reportFailure('durability.socket.send_failed', { type: frame.type }, error);
}
};
const readAttachment = (ws: WebSocket): Attachment<unknown> => {
const stored: unknown = ws.deserializeAttachment();
if (!isObject(stored)) {
return {
metadata: undefined,
hasMetadata: false,
names: [],
channel: defaultChannel,
};
}
const metadata = 'metadata' in stored ? stored.metadata : undefined;
const names = 'names' in stored ? stored.names : undefined;
// Connections accepted before channels existed carry no channel.
const channel = 'channel' in stored ? stored.channel : undefined;
return {
metadata,
// Attachments written before `hasMetadata` existed captured metadata if they hold any.
hasMetadata:
'hasMetadata' in stored
? stored.hasMetadata === true
: metadata !== undefined,
names: Array.isArray(names) ? names.filter(isString) : [],
channel: isString(channel) ? channel : defaultChannel,
};
};
class DurabilitySocketCore<
Inbound extends SocketInboundMap,
Outbound extends SocketOutboundMap,
Metadata extends SocketInboundMetadata<Inbound>,
> {
declare readonly [socketMessageMaps]: SocketMessageMaps<Inbound, Outbound>;
readonly #context: DurabilitySocketContext;
readonly #storage: DurableObjectStorage;
readonly #inbound: Map<string, SocketInboundHandler<never>>;
readonly #outboundNames: Set<string>;
readonly #metadata: SocketMetadataConfig<Metadata>['metadata'] | undefined;
readonly #retention: number;
readonly #channel: string;
readonly #frameHandlers: Map<string, FrameHandler>;
constructor(config: DurabilitySocketConfig<Inbound, Outbound, Metadata>) {
const retention = config.retention ?? 1_000;
if (!Number.isSafeInteger(retention) || retention <= 0) {
throw new RangeError('retention must be a positive safe integer');
}
this.#channel = assertChannel(
'DurabilitySocket',
config.channel ?? defaultChannel
);
this.#context = config.context;
this.#storage = traceStorage(config.context.storage);
// Only own keys are callable; nothing on the prototype chain is reachable.
this.#inbound = new Map(Object.entries(config.inbound));
this.#metadata = config.metadata;
this.#retention = retention;
this.#outboundNames = new Set(Object.keys(config.outbound));
const reserved = new Set([
...Object.getOwnPropertyNames(DurabilitySocketCore.prototype),
...reservedOutboundNames,
]);
for (const name of this.#outboundNames) {
if (reserved.has(name)) {
throw new Error(`"${name}" is reserved by DurabilitySocket`);
}
Object.defineProperty(this, name, {
value: traceFunction(`DurabilitySocket.${name}`, (payload: unknown) =>
this.#publish(name, payload)
),
enumerable: true,
});
}
const engine = engineFor({ context: config.context });
engine.migrateSchema('socket', durabilitySocketMigrations);
engine.claimChannel(
'durability_socket_events',
this.#channel,
'DurabilitySocket'
);
const frameHandlers =
frameHandlersByObject.get(engine) ?? new Map<string, FrameHandler>();
frameHandlers.set(this.#channel, (ws, frame) => this.#handle(ws, frame));
frameHandlersByObject.set(engine, frameHandlers);
this.#frameHandlers = frameHandlers;
// Keep-alive pings are answered by the runtime without waking a hibernated object.
this.#context.setWebSocketAutoResponse(
new WebSocketRequestResponsePair(
JSON.stringify({ v: socketProtocolVersion, type: 'ping' }),
JSON.stringify({ v: socketProtocolVersion, type: 'pong' })
)
);
}
/** Applies or reverts the `durability_socket_events` schema. */
static migrate(
context: Pick<DurableObjectState, 'storage'>,
target?: string | null
): DurabilityMigrationResult {
return migrateCapability(
context.storage,
'socket',
durabilitySocketMigrations,
target
);
}
/** Accepts a WebSocket upgrade; call from the Durable Object's `fetch`. */
async fetch(request: Request): Promise<Response> {
if (request.headers.get('Upgrade')?.toLowerCase() !== 'websocket') {
return new Response('Expected a WebSocket upgrade', { status: 426 });
}
const metadata = await this.#metadata?.(request);
const pair = new WebSocketPair();
const client = pair[0];
const server = pair[1];
this.#context.acceptWebSocket(server);
server.serializeAttachment({
metadata,
hasMetadata: this.#metadata !== undefined,
names: [],
channel: this.#channel,
} satisfies Attachment<Metadata | undefined>);
return new Response(null, { status: 101, webSocket: client });
}
/**
* Handles one inbound frame; call from the Durable Object's
* `webSocketMessage`. The frame goes to the socket of the connection's
* channel, which need not be this one.
*/
async webSocketMessage(
ws: WebSocket,
message: string | ArrayBuffer
): Promise<void> {
const text = isString(message)
? message
: new TextDecoder().decode(message);
const frame = parseClientFrame(text);
if (!frame) {
trace('socket.close', {
code: socketProtocolErrorCode,
reason: 'Invalid frame',
});
ws.close(socketProtocolErrorCode, 'Invalid frame');
return;
}
const { channel } = readAttachment(ws);
const handle = this.#frameHandlers.get(channel);
if (!handle) {
reportFailure(
'durability.socket.channel_missing',
{ channel },
new Error(`No DurabilitySocket is attached for channel "${channel}"`)
);
trace('socket.close', {
code: channelMissingCloseCode,
reason: 'Socket channel is not attached',
});
ws.close(channelMissingCloseCode, 'Socket channel is not attached');
return;
}
await handle(ws, frame);
}
/**
* Call from the Durable Object's `webSocketClose`. Subscriptions live in the
* socket's attachment, so nothing needs cleaning up; the runtime requires
* the method to exist for hibernatable WebSockets.
*/
webSocketClose(_ws: WebSocket): void {}
async #handle(ws: WebSocket, frame: SocketClientFrame): Promise<void> {
// A connection accepted before this socket captured metadata, such as
// before a deploy added it, must not reach a handler without it.
if (this.#metadata !== undefined && !readAttachment(ws).hasMetadata) {
trace('socket.close', {
code: metadataMissingCloseCode,
reason: 'Socket metadata was not captured',
});
ws.close(metadataMissingCloseCode, 'Socket metadata was not captured');
return;
}
if (frame.type === 'subscribe') {
this.#subscribe(ws, frame);
return;
}
await this.#call(ws, frame);
}
async #call(
ws: WebSocket,
frame: Extract<SocketClientFrame, { type: 'call' }>
): Promise<void> {
const handler = this.#inbound.get(frame.method);
if (!handler) {
sendFrame(ws, {
v: socketProtocolVersion,
type: 'error',
id: frame.id,
error: {
name: 'SocketUnknownMethodError',
message: `Unknown method "${frame.method}"`,
},
});
return;
}
const call: SocketCall<never> = {
// SAFETY: #inbound erases each handler's metadata type to never. With
// config.metadata set, #handle closed every connection whose attachment
// lacks its result; without it, the handlers' metadata admits undefined.
metadata: readAttachment(ws).metadata as never,
};
try {
// SAFETY: the input passed handler.input, and SocketValidatedInbound
// requires each handle to accept its own schema's output.
const output = await handler.handle(
(await this.#validate(frame, handler.input)) as never,
call
);
sendFrame(ws, {
v: socketProtocolVersion,
type: 'result',
id: frame.id,
output,
});
} catch (error) {
sendFrame(ws, {
v: socketProtocolVersion,
type: 'error',
id: frame.id,
error: serializeError(error),
});
}
}
async #validate<Output>(
frame: Extract<SocketClientFrame, { type: 'call' }>,
schema: StandardSchemaV1<unknown, Output>
): Promise<Output> {
const result = await schema['~standard'].validate(frame.input);
if (result.issues) {
throw new SocketInputError(frame.method, result.issues);
}
return result.value;
}
#subscribe(
ws: WebSocket,
frame: Extract<SocketClientFrame, { type: 'subscribe' }>
): void {
const unknown = frame.names.find((name) => !this.#outboundNames.has(name));
if (unknown !== undefined) {
sendFrame(ws, {
v: socketProtocolVersion,
type: 'error',
id: frame.id,
error: {
name: 'SocketUnknownEventError',
message: `Unknown event "${unknown}"`,
},
});
return;
}
const attachment = readAttachment(ws);
ws.serializeAttachment({
...attachment,
names: frame.names,
} satisfies Attachment<unknown>);
const head = this.#headSeq();
const replayed = this.#replay(ws, frame.names, frame.since, head);
sendFrame(ws, {
v: socketProtocolVersion,
type: 'subscribed',
id: frame.id,
seq: head,
replayed,
});
}
/**
* Replays retained events after `since` and reports whether the client is
* now caught up. A client ahead of the log or behind its oldest row must
* rebuild its state from a fresh snapshot instead.
*/
#replay(
ws: WebSocket,
names: string[],
since: number | undefined,
head: number
): boolean {
if (since === undefined || since > head) {
return false;
}
if (since === head) {
return true;
}
const oldest = this.#storage.sql
.exec<{ seq: number }>(
'SELECT MIN(seq) AS seq FROM durability_socket_events WHERE channel = ?',
this.#channel
)
.one().seq;
if (since + 1 < oldest) {
return false;
}
const rows = this.#storage.sql
.exec<EventRow>(
'SELECT seq, name, payload FROM durability_socket_events WHERE channel = ? AND seq > ? ORDER BY seq',
this.#channel,
since
)
.toArray();
const wanted = new Set(names);
for (const row of rows) {
if (!wanted.has(row.name)) {
continue;
}
sendFrame(ws, {
v: socketProtocolVersion,
type: 'event',
seq: row.seq,
name: row.name,
payload: deserialize(row.payload),
});
}
return true;
}
#headSeq(): number {
const row = this.#storage.sql
.exec<{ seq: number | null }>(
'SELECT MAX(seq) AS seq FROM durability_socket_events WHERE channel = ?',
this.#channel
)
.one();
return row.seq ?? 0;
}
#publish(name: string, payload: unknown): void {
const serialized = serialize(payload);
const sql = this.#storage.sql;
// Trimming keeps the newest event of a channel, so its maximum never goes back.
const { seq } = sql
.exec<{ seq: number }>(
`INSERT INTO durability_socket_events (channel, seq, name, payload, created_at)
SELECT ?, COALESCE(MAX(seq), 0) + 1, ?, ?, ?
FROM durability_socket_events WHERE channel = ?
RETURNING seq`,
this.#channel,
name,
serialized,
Date.now(),
this.#channel
)
.one();
sql.exec(
'DELETE FROM durability_socket_events WHERE channel = ? AND seq <= ?',
this.#channel,
seq - this.#retention
);
const frame: SocketServerFrame = {
v: socketProtocolVersion,
type: 'event',
seq,
name,
payload,
};
for (const ws of this.#context.getWebSockets()) {
if (ws.readyState !== WebSocket.OPEN) {
continue;
}
const attachment = readAttachment(ws);
if (
attachment.channel !== this.#channel ||
!attachment.names.includes(name)
) {
continue;
}
sendFrame(ws, frame);
}
}
}
type OutboundMethods<Outbound extends SocketOutboundMap> = {
[Name in keyof Outbound]: (
payload: SocketOutboundPayload<Outbound[Name]>
) => void;
};
/**
* Typed WebSocket RPC and event push for one Durable Object, over hibernatable
* WebSockets.
*
* Every `outbound` event becomes a method on the instance that persists the
* event for replay and pushes it to subscribed clients. Clients call `inbound`
* handlers through `durability/client`.
*
* @example
* ```ts
* class TodoList extends DurableObject<Env> {
* readonly socket = new DurabilitySocket({
* context: this.ctx,
* inbound: {
* list: { input: v.undefined(), handle: () => this.repo.list() },
* create: {
* input: TodoSchema,
* handle: async (todo) => {
* await this.repo.insert(todo);
* this.socket.created(todo);
* },
* },
* },
* outbound: { created: event<Todo>() },
* });
*
* fetch(request: Request) {
* return this.socket.fetch(request);
* }
*
* webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) {
* return this.socket.webSocketMessage(ws, message);
* }
*
* webSocketClose(ws: WebSocket) {
* this.socket.webSocketClose(ws);
* }
* }
* ```
*/
export type DurabilitySocket<
Inbound extends SocketInboundMap,
Outbound extends SocketOutboundMap,
Metadata extends SocketInboundMetadata<Inbound> =
SocketInboundMetadata<Inbound>,
> = DurabilitySocketCore<Inbound, Outbound, Metadata> &
OutboundMethods<Outbound>;
export interface DurabilitySocketConstructor {
new <
Inbound extends SocketInboundMap,
Outbound extends SocketOutboundMap,
Metadata extends SocketInboundMetadata<Inbound> =
SocketInboundMetadata<Inbound>,
Schemas extends Record<keyof Inbound, StandardSchemaV1> =
SocketInboundSchemas<Inbound>,
>(
config: DurabilitySocketConfig<Inbound, Outbound, Metadata, Schemas>
): DurabilitySocket<Inbound, Outbound, Metadata>;
migrate: typeof DurabilitySocketCore.migrate;
}
traceMethods(DurabilitySocketCore.prototype, 'DurabilitySocket');
// SAFETY: the constructor defines a method for every outbound event name on the
// instance, members TypeScript cannot declare from a generic event map.
export const DurabilitySocket =
DurabilitySocketCore as DurabilitySocketConstructor;
export { durabilitySocketMigrations } from './migrations.js';
export {
event,
type SocketCall,
type SocketInboundHandler,
type SocketInboundMap,
type SocketOutboundEvent,
type SocketOutboundMap,
} from './protocol.js';