examples/realtime-todos/client.ts examples/realtime-todos/worker.ts packages/durability/src/socket/client.ts packages/durability/src/socket/index.ts packages/durability/src/operations/index.ts packages/durability/src/socket/client.ts Open source ↗ /**
* Browser side of the `realtime-todos` example. Imports only `durability/client`,
* which has no Workers dependencies, and derives every method and event type
* from the Durable Object's socket.
*/
import { DurabilitySocketClient, logging } from 'durability/client' ;
import type { Todo, TodoList } from './worker' ;
const client = new DurabilitySocketClient < TodoList [ 'socket' ]>({
url : ( listId ) => `wss://todos.example.com/lists/${ listId }/ws` ,
}). with ( logging ());
export const openList = ( listId : string , render : ( todos : Todo []) => void ) => {
const conn = client. connect (listId);
const todos = new Map < string , Todo >();
const reload = async () => {
todos. clear ();
for ( const todo of await conn.rpc. list ()) {
todos. set (todo.id, todo);
}
render ([ ... todos. values ()]);
};
// Fires on first connect and whenever missed events could not be replayed.
conn.on. resync (() => void reload ());
conn.on. created (( todo ) => {
todos. set (todo.id, todo);
render ([ ... todos. values ()]);
});
conn.on. updated (( todo ) => {
todos. set (todo.id, todo);
render ([ ... todos. values ()]);
});
conn.on. status (( status ) => console. info ( 'todo list' , listId, status));
return {
create : ( title : string ) =>
conn.rpc. createTodo ({
id: crypto. randomUUID (),
payload: { id: crypto. randomUUID (), title, done: false },
}),
toggle : ( id : string ) => conn.rpc. toggle (id),
close : () => conn. close (),
};
}; /**
* `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 { reportFailure, type SerializedError } from '../errors.js' ;
import { isString } from '../predicates.js' ;
import {
parseServerFrame,
socketProtocolErrorCode,
socketProtocolVersion,
type AnyDurabilitySocket,
type InboundOf,
type OutboundOf,
type SocketClientFrame,
type SocketInboundInput,
type SocketInboundOutput,
type SocketOutboundPayload,
type SocketServerFrame,
} from './protocol.js' ;
import { SharedTimer } from '../shared-timer.js' ;
import { exponential, jitter } from '../utils.js' ;
/** Rejection for calls still waiting when `close()` was called. */
export class SocketClosedError extends Error {
constructor () {
super ( 'Socket connection was closed' );
this .name = 'SocketClosedError' ;
}
}
/**
* Rejection for calls that were sent but unanswered when the connection
* dropped. They are never replayed: the server may or may not have run them.
*/
export class SocketConnectionLostError extends Error {
constructor ( method : string ) {
super ( `Connection lost while "${ method }" was in flight` );
this .name = 'SocketConnectionLostError' ;
}
}
/** Rejection for calls unanswered within the configured timeout. */
export class SocketTimeoutError extends Error {
constructor ( method : string , timeoutMs : number ) {
super ( `"${ method }" timed out after ${ timeoutMs }ms` );
this .name = 'SocketTimeoutError' ;
}
}
/** The server sent a frame this client cannot interpret; the connection is abandoned. */
export class SocketProtocolError extends Error {
constructor ( message : string ) {
super (message);
this .name = 'SocketProtocolError' ;
}
}
/** A handler on the server threw; `name` and `message` are the server's. */
export class SocketRemoteError extends Error {
constructor ( error : SerializedError ) {
super (error.message);
this .name = error.name;
}
}
export type SocketStatus =
| 'connecting'
| 'connected'
| 'disconnected'
| 'closed' ;
/** Wraps every `rpc` call; `next` forwards with the same or a replaced input. */
export type SocketTransform = ( call : {
method : string ;
input : unknown ;
next : ( input ?: unknown ) => Promise < unknown >;
}) => Promise < unknown >;
/** The part of a `WebSocket` the client uses. */
type SocketClientWebSocket = Pick <
WebSocket ,
'addEventListener' | 'close' | 'send'
>;
export type DurabilitySocketClientConfig = {
/** Builds the WebSocket URL for one Durable Object. */
url : ( id : string ) => string ;
/** Rejects unanswered calls after this long. Defaults to 2 minutes. */
timeoutMs ?: number ;
/** Interval between keep-alive pings; a silent connection is dropped after two. Defaults to 30 seconds. */
pingIntervalMs ?: number ;
/** WebSocket implementation. Defaults to the global `WebSocket`. */
webSocket ?: new ( url : string ) => SocketClientWebSocket ;
};
type RpcMethod < Input , Output > = [ Input ] extends [ void ]
? () => Promise < Output >
: ( input : Input ) => Promise < Output >;
type RpcMethods < Inbound > = {
[ Method in keyof Inbound ] : RpcMethod <
SocketInboundInput < Inbound [ Method ]>,
SocketInboundOutput < Inbound [ Method ]>
>;
};
type EventHandlers < Outbound > = {
[ Name in keyof Outbound ] : (
handler : ( payload : SocketOutboundPayload < Outbound [ Name ]>) => void
) => () => void ;
} & {
/** Observes connection status; the handler runs immediately with the current value. */
status : ( handler : ( status : SocketStatus ) => void ) => () => void ;
/**
* Fires when subscribers to `names` have no continuous history: on their
* first subscription, and whenever missed events could not be replayed.
* Rebuild their state from a snapshot.
*/
resync : ( handler : ( info : SocketResync ) => void ) => () => void ;
};
export type SocketResync = { names : string [] };
/** One connection to one Durable Object. */
export type SocketConnection < Socket extends AnyDurabilitySocket > = {
rpc : RpcMethods < InboundOf < Socket >>;
on : EventHandlers < OutboundOf < Socket >>;
readonly status : SocketStatus ;
/** Permanently closes the connection and rejects outstanding calls. */
close () : void ;
};
type PendingCall = {
method : string ;
text : string ;
sent : boolean ;
resolve : ( output : unknown ) => void ;
reject : ( error : Error ) => void ;
cancelTimeout : () => void ;
};
const pingText = JSON . stringify ({ v: socketProtocolVersion, type: 'ping' });
const pongText = JSON . stringify ({ v: socketProtocolVersion, type: 'pong' });
class Connection {
readonly #config : Required < DurabilitySocketClientConfig >;
readonly #url : string ;
readonly #transforms : readonly SocketTransform [];
readonly #pending = new Map < string , PendingCall >();
readonly #handlers = new Map < string , Set <( payload : unknown ) => void >>();
readonly #statusHandlers = new Set <( status : SocketStatus ) => void >();
readonly #resyncHandlers = new Set <( info : SocketResync ) => void >();
readonly #subscribes = new Map < string , string []>();
#acknowledged = new Set < string >();
#status : SocketStatus = 'disconnected' ;
#ws : SocketClientWebSocket | undefined ;
#generation = 0 ;
#nextId = 0 ;
#lastSeq : number | undefined ;
#attempt = 0 ;
// Every pending call holds a timeout, and nothing limits how many are pending.
readonly #timer = new SharedTimer ();
#cancelRetry : (() => void ) | undefined ;
#cancelPing : (() => void ) | undefined ;
#lastReceivedAt = 0 ;
constructor (
config : Required < DurabilitySocketClientConfig >,
id : string ,
transforms : readonly SocketTransform []
) {
this .#config = config;
this .#url = config. url (id);
this .#transforms = transforms;
}
get status () : SocketStatus {
return this .#status;
}
call ( method : string , input : unknown ) : Promise < unknown > {
const run = ( index : number , currentInput : unknown ) : Promise < unknown > => {
const transform = this .#transforms[index];
if ( ! transform) {
return this . #send (method, currentInput);
}
return transform ({
method,
input: currentInput,
next : ( nextInput = currentInput) => run (index + 1 , nextInput),
});
};
return run ( 0 , input);
}
on ( name : string , handler : ( payload : unknown ) => void ) : () => void {
let handlers = this .#handlers. get (name);
if ( ! handlers) {
handlers = new Set ();
this .#handlers. set (name, handlers);
this . #subscribe ();
}
handlers. add (handler);
return () => {
handlers. delete (handler);
if (handlers.size === 0 && this .#handlers. get (name) === handlers) {
this .#handlers. delete (name);
this . #subscribe ();
}
};
}
onStatus ( handler : ( status : SocketStatus ) => void ) : () => void {
this .#statusHandlers. add (handler);
handler ( this .#status);
return () => {
this .#statusHandlers. delete (handler);
};
}
onResync ( handler : ( info : SocketResync ) => void ) : () => void {
this .#resyncHandlers. add (handler);
return () => {
this .#resyncHandlers. delete (handler);
};
}
close () : void {
if ( this .#status === 'closed' ) {
return ;
}
this . #setStatus ( 'closed' );
this . #stopTimers ();
this .#generation += 1 ;
for ( const pending of this .#pending. values ()) {
pending. cancelTimeout ();
pending. reject ( new SocketClosedError ());
}
this .#pending. clear ();
this .#handlers. clear ();
this .#statusHandlers. clear ();
this .#resyncHandlers. clear ();
this .#ws?. close ( 1000 , 'Client closed' );
this .#ws = undefined ;
}
# send ( method : string , input : unknown ) : Promise < unknown > {
if ( this .#status === 'closed' ) {
return Promise . reject ( new SocketClosedError ());
}
const id = String ( ++ this .#nextId);
const frame : SocketClientFrame = {
v: socketProtocolVersion,
type: 'call' ,
id,
method,
input,
};
return new Promise (( resolve , reject ) => {
const pending : PendingCall = {
method,
text: JSON . stringify (frame),
sent: false ,
resolve,
reject,
cancelTimeout: this .#timer. schedule (
() => {
this .#pending. delete (id);
reject ( new SocketTimeoutError (method, this .#config.timeoutMs));
},
this .#config.timeoutMs
),
};
this .#pending. set (id, pending);
this . #flush ();
});
}
# subscribe () : void {
if ( this .#status !== 'connected' ) {
this . #connect ();
return ;
}
const names = [ ... this .#handlers. keys ()];
const frame : Extract < SocketClientFrame , { type : 'subscribe' }> = {
v: socketProtocolVersion,
type: 'subscribe' ,
id: `subscribe:${ ++ this . #nextId }` ,
names,
};
if ( this .#lastSeq !== undefined ) {
frame.since = this .#lastSeq;
}
this .#subscribes. set (frame.id, names);
this .#ws?. send ( JSON . stringify (frame));
}
/** Names whose subscribers start without history: new ones, or all when replay failed. */
# subscribed ( frame : Extract < SocketServerFrame , { type : 'subscribed' }>) : void {
this .#lastSeq = frame.seq;
const names = this .#subscribes. get (frame.id) ?? [];
this .#subscribes. delete (frame.id);
const fresh = frame.replayed
? names. filter (( name ) => ! this .#acknowledged. has (name))
: names;
this .#acknowledged = new Set (names);
if (fresh. length === 0 ) {
return ;
}
for ( const handler of this .#resyncHandlers) {
this . #invoke (handler, { names: fresh }, 'resync' );
}
}
/** Sends unsent calls; opens the connection first when needed. */
# flush () : void {
if ( this .#status !== 'connected' || ! this .#ws) {
this . #connect ();
return ;
}
for ( const pending of this .#pending. values ()) {
if (pending.sent) {
continue ;
}
pending.sent = true ;
this .#ws. send (pending.text);
}
}
/** Opens a socket unless one is open, opening, or already scheduled by backoff. */
# connect () : void {
if ( this .#status !== 'disconnected' || this .#cancelRetry !== undefined ) {
return ;
}
this . #setStatus ( 'connecting' );
const generation = ++ this .#generation;
const ws = new this .#config. webSocket ( this .#url);
this .#ws = ws;
const current = () => generation === this .#generation;
ws. addEventListener ( 'open' , () => {
if ( ! current ()) {
return ;
}
this .#attempt = 0 ;
this .#lastReceivedAt = Date. now ();
this . #setStatus ( 'connected' );
if ( this .#handlers.size > 0 ) {
this . #subscribe ();
}
this . #flush ();
this . #startPing ();
});
ws. addEventListener ( 'message' , ( message ) => {
if ( ! current ()) {
return ;
}
this . #receive ( isString (message.data) ? message.data : '' );
});
ws. addEventListener ( 'close' , ( closed ) => {
if ( ! current ()) {
return ;
}
this . #disconnected (closed.code);
});
ws. addEventListener ( 'error' , () => {
if ( current ()) {
ws. close ();
}
});
}
# receive ( text : string ) : void {
this .#lastReceivedAt = Date. now ();
if (text === pongText) {
return ;
}
const frame = parseServerFrame (text);
if ( ! frame) {
this . #abandon ( new SocketProtocolError ( 'Received an invalid frame' ));
return ;
}
switch (frame.type) {
case 'event' :
this .#lastSeq = frame.seq;
this . #dispatch (frame.name, frame.payload);
return ;
case 'subscribed' :
this . #subscribed (frame);
return ;
case 'result' :
this . #settle (frame, ( pending ) => pending. resolve (frame.output));
return ;
case 'error' :
if ( this .#subscribes. delete (frame.id)) {
reportFailure ( 'durability.socket.subscribe_failed' , {}, frame.error);
return ;
}
this . #settle (frame, ( pending ) =>
pending. reject ( new SocketRemoteError (frame.error))
);
return ;
}
}
# settle (
frame : Extract < SocketServerFrame , { id : string }>,
settle : ( pending : PendingCall ) => void
) : void {
const pending = this .#pending. get (frame.id);
if ( ! pending) {
return ;
}
this .#pending. delete (frame.id);
pending. cancelTimeout ();
settle (pending);
}
# dispatch ( name : string , payload : unknown ) : void {
for ( const handler of this .#handlers. get (name) ?? []) {
this . #invoke (handler, payload, name);
}
}
# invoke < Payload >(
handler : ( payload : Payload ) => void ,
payload : Payload ,
name : string
) : void {
try {
handler (payload);
} catch (error) {
reportFailure ( 'durability.socket.handler_failed' , { name }, error);
}
}
# disconnected ( code : number ) : void {
this . #stopTimers ();
this .#ws = undefined ;
this .#subscribes. clear ();
for ( const [ id , pending ] of this .#pending) {
if ( ! pending.sent) {
continue ;
}
this .#pending. delete (id);
pending. cancelTimeout ();
pending. reject ( new SocketConnectionLostError (pending.method));
}
if (code === socketProtocolErrorCode) {
this . #abandon ( new SocketProtocolError ( 'Server rejected the protocol' ));
return ;
}
this . #setStatus ( 'disconnected' );
this .#attempt += 1 ;
this .#cancelRetry = this .#timer. schedule (
() => {
this .#cancelRetry = undefined ;
this . #connect ();
},
jitter ( exponential ( this .#attempt, 250 , 60_000 ))
);
}
/** Stops reconnecting after a protocol failure, which a retry cannot fix. */
# abandon ( error : SocketProtocolError ) : void {
reportFailure ( 'durability.socket.protocol_error' , {}, error);
for ( const pending of this .#pending. values ()) {
pending. cancelTimeout ();
pending. reject (error);
}
this .#pending. clear ();
this . close ();
}
# startPing () : void {
const interval = this .#config.pingIntervalMs;
const ping = () : void => {
// Scheduled before the socket is used, so a close that stops the timers
// also stops the next ping.
this .#cancelPing = this .#timer. schedule (ping, interval);
if (Date. now () - this .#lastReceivedAt > interval * 2 ) {
this .#ws?. close ( 4000 , 'Keep-alive timeout' );
return ;
}
this .#ws?. send (pingText);
};
this .#cancelPing = this .#timer. schedule (ping, interval);
}
# stopTimers () : void {
this . #cancelPing ?.();
this .#cancelPing = undefined ;
this . #cancelRetry ?.();
this .#cancelRetry = undefined ;
}
# setStatus ( status : SocketStatus ) : void {
if ( this .#status === status) {
return ;
}
this .#status = status;
for ( const handler of this .#statusHandlers) {
this . #invoke (handler, status, 'status' );
}
}
}
const defaultWebSocket = () : ( new ( url : string ) => WebSocket ) => {
if ( typeof WebSocket === 'undefined' ) {
throw new Error (
'No WebSocket implementation; pass `webSocket` in the client config'
);
}
return WebSocket;
};
/**
* Browser client for a { @link DurabilitySocket } . Connections open lazily,
* reconnect with jittered backoff, and resubscribe from the last seen event.
*
* @example
* ```ts
* const client = new DurabilitySocketClient<TodoList['socket']>({
* url: (id) => `wss://example.com/todos/${id}`,
* });
* const conn = client.connect('personal');
* const todos = await conn.rpc.list();
* conn.on.created((todo) => render(todo));
* conn.on.resync(() => reload());
* ```
*/
export class DurabilitySocketClient < Socket extends AnyDurabilitySocket > {
readonly #config : Required < DurabilitySocketClientConfig >;
readonly #transforms : readonly SocketTransform [];
constructor (
config : DurabilitySocketClientConfig ,
transforms : readonly SocketTransform [] = []
) {
this .#config = {
url: config.url,
timeoutMs: config.timeoutMs ?? 120_000 ,
pingIntervalMs: config.pingIntervalMs ?? 30_000 ,
webSocket: config.webSocket ?? defaultWebSocket (),
};
this .#transforms = transforms;
}
/** Returns a client that also applies `transform` around every call. */
with ( transform : SocketTransform ) : DurabilitySocketClient < Socket > {
return new DurabilitySocketClient ( this .#config, [
... this .#transforms,
transform,
]);
}
connect ( id : string ) : SocketConnection < Socket > {
const connection = new Connection ( this .#config, id, this .#transforms);
// SAFETY: the get trap returns a method for every string key, so the
// empty target is never read.
const rpc = new Proxy ({} as RpcMethods < InboundOf < Socket >>, {
get : ( _target , method ) =>
isString (method)
? ( input ?: unknown ) => connection. call (method, input)
: undefined ,
});
// SAFETY: the get trap returns a subscriber for every string key, so the
// empty target is never read.
const on = new Proxy ({} as EventHandlers < OutboundOf < Socket >>, {
get : ( _target , name ) => {
if (name === 'status' ) {
return ( handler : ( status : SocketStatus ) => void ) =>
connection. onStatus (handler);
}
if (name === 'resync' ) {
return ( handler : ( info : SocketResync ) => void ) =>
connection. onResync (handler);
}
return isString (name)
? ( handler : ( payload : unknown ) => void ) =>
connection. on (name, handler)
: undefined ;
},
});
return {
rpc,
on,
get status () {
return connection.status;
},
close : () => connection. close (),
};
}
}
/** One call recorded by { @link logging } : its output if it resolved, or its error. */
export type SocketCallLog =
| {
method : string ;
input : unknown ;
output : unknown ;
durationMs : number ;
}
| {
method : string ;
input : unknown ;
error : unknown ;
durationMs : number ;
};
/** Logs every call's input, output or error, and duration. */
export const logging =
( log : ( entry : SocketCallLog ) => void = console.log) : SocketTransform =>
async ({ method , input , next }) => {
const startedAt = Date. now ();
try {
const output = await next ();
log ({ method, input, output, durationMs: Date. now () - startedAt });
return output;
} catch (error) {
log ({ method, input, error, durationMs: Date. now () - startedAt });
throw error;
}
};
export {
socketMessageMaps,
type AnyDurabilitySocket,
type InboundOf,
type OutboundOf,
type SocketInboundInput,
type SocketInboundOutput,
type SocketMessageMaps,
type SocketOutboundPayload,
} from './protocol.js' ; 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' ; import * as v from 'valibot' ;
import { traceFunction, traceMethods } from '../dev.js' ;
import {
DuplicateDurableCallError,
DuplicateDurablePayloadError,
DurableAttemptsExhaustedError,
DurableAttemptTimeoutError,
DurableResultSerializationError,
isErrorInstance,
NonRetryableError,
reportFailure,
} from '../errors.js' ;
import {
createLifecycleHooks,
type DurabilityLifecycleEvent,
type LifecycleHook,
type LifecycleHooks,
type OperationLifecycleEntity,
} from '../lifecycle.js' ;
import { durabilityOperationMigrations } from './migrations.js' ;
import { durabilityMemoMigrations } from '../memoize/migrations.js' ;
import {
migrateCapability,
type DurabilityMigrationResult,
} from '../migrations.js' ;
import {
createPolicyResolver,
methodOptionsSchema,
type DurabilityMethodOptions,
type ExecutionPolicyOptions,
type MethodPolicy,
type PolicyResolver,
} from '../policy.js' ;
import {
assertChannel,
defaultChannel,
engineFor,
type ActiveExecution,
type Engine,
type SchedulerAttachment,
} from '../scheduler/index.js' ;
import { canonical, deserialize, serialize } from '../serialization.js' ;
import {
createMemoize,
deleteMemosOfDroppedTable,
memoizedKeys,
type DurableMemoize,
} from '../memoize/index.js' ;
import { listCreated, updateAttempt, type DurableTable } from '../storage.js' ;
import {
registerTrackedSource,
type UntypedRecord,
type UntypedSource,
} from '../tracker/source.js' ;
const callRowSchema = v. object ({
id: v. string (),
channel: v. string (),
operation: v. string (),
payload: v. string (),
status: v. picklist ([ 'pending' , 'completed' , 'failed' ]),
result: v. nullable (v. string ()),
attempt: v. pipe (v. number (), v. safeInteger (), v. minValue ( 0 )),
next_attempt_at: v. pipe (v. number (), v. safeInteger (), v. minValue ( 0 )),
last_error: v. nullable (v. string ()),
last_error_name: v. nullable (v. string ()),
completed_at: v. nullable (v. pipe (v. number (), v. safeInteger (), v. minValue ( 0 ))),
created_at: v. pipe (v. number (), v. safeInteger (), v. minValue ( 0 )),
generation_id: v. string (),
});
type CallRow = v . InferOutput < typeof callRowSchema>;
const callsTable : DurableTable = { name: 'durability_calls' , key: 'id' };
const readCall = (
sql : SqlStorage ,
channel : string ,
id : string
) : CallRow | undefined =>
v. parse (
v. optional (callRowSchema),
sql
. exec (
'SELECT * FROM durability_calls WHERE channel = ? AND id = ?' ,
channel,
id
)
. toArray ()[ 0 ]
);
/**
* The context passed to a durable operation handler for each attempt.
*
* @example
* ```ts
* const sendEmail = async ({ id, payload, signal }: DurableCall<EmailPayload>) =>
* fetch(payload.url, {
* method: 'POST',
* headers: { 'Idempotency-Key': id },
* signal,
* });
* ```
*/
export type DurableCall < Payload > = {
/**
* The stable idempotency key supplied when the operation was registered. This
* is the operation's logical identity: key any external deduplication or
* once-only effect by `id`, never by `attempt`.
*/
id : string ;
/** The handler name used to register the operation. */
operation : string ;
/** The JSON-serializable payload supplied when the operation was registered. */
payload : Payload ;
/**
* The one-based attempt ordinal, durably recorded before the handler runs. It
* is retry and logging context, not a record of what the handler did: never
* gate once-only work on it (such as `attempt === 1`). Key such work on
* durable state keyed by `id` instead. See the README identity glossary.
*/
attempt : number ;
/** Aborts when the attempt exceeds its configured timeout. */
signal : AbortSignal ;
/** Persists a callback's result by key so a retry of this operation reuses it. */
memoize : DurableMemoize ;
};
/** A function that executes one attempt of a durable operation. */
export type DurableHandler < Payload , Result > = (
call : DurableCall < Payload >
) => Result | Promise < Result >;
export type HandlerMap = Record < string , ( ... args : never []) => unknown >;
type HandlerPayload < Handler > = Handler extends (
call : DurableCall < infer Payload >
) => unknown
? Payload
: never ;
type HandlerResult < Handler > = Handler extends ( ... args : never []) => infer Result
? Awaited < Result >
: never ;
/** Result types of every operation, keyed by handler name. */
export type OperationResults < Handlers extends HandlerMap > = {
[ Operation in Extract < keyof Handlers , string >] : HandlerResult <
Handlers [ Operation ]
>;
};
type DurableOperationInput < Handler > = {
/** Stable idempotency key; bound to the operation and its payload. */
id : string ;
/** JSON-serializable input passed to the operation handler. */
payload : HandlerPayload < Handler >;
};
/**
* The persisted state and result of a durable operation.
*
* Operation methods only wait for durable registration, not handler completion.
* Call `getResult` later and narrow on `status` before reading a result or error.
*/
export type DurableOperationResult < Result > =
| {
/** No operation exists for the supplied idempotency key. */
status : 'not_found' ;
}
| {
/** The operation is waiting to run or retry. */
status : 'pending' ;
/** The number of attempts already started. */
attempt : number ;
/** Unix timestamp in milliseconds when the next attempt becomes eligible. */
nextAttemptAt : number ;
/** The previous attempt's error message, or null before the first attempt. */
lastError : string | null ;
}
| {
/** The operation exhausted its attempts or failed with a non-retryable error. */
status : 'failed' ;
/** The number of attempts that were started. */
attempt : number ;
/** The terminal error's serialized name and message. */
error : { name : string ; message : string };
}
| {
/** The operation completed successfully. */
status : 'completed' ;
/** The handler's persisted return value. */
result : Result ;
};
type OperationEvent = Extract <
DurabilityLifecycleEvent ,
{ entityKind : 'operation' }
>;
type TypedOperationEvent <
Operation extends string ,
Result ,
> = OperationEvent extends infer Event
? Event extends { outcome : 'completed' }
? Omit < Event , 'operation' | 'result' > & {
operation : Operation ;
/** Present only when the instance was created with `includeResults: true`. */
result ?: Result ;
}
: Event extends object
? Omit < Event , 'operation' > & { operation : Operation }
: never
: never ;
/**
* A lifecycle event for one of this instance's operations. Completed events
* carry the handler's typed result only when the instance is created with
* `includeResults: true`.
*/
export type DurabilityOperationEvent < Handlers extends HandlerMap > =
| {
[ Operation in Extract < keyof Handlers , string >] : TypedOperationEvent <
Operation ,
HandlerResult < Handlers [ Operation ]>
>;
}[ Extract < keyof Handlers , string >]
| Extract < DurabilityLifecycleEvent , { type : 'purged' }>;
/** Registers calls for one handler and reads their persisted results. */
export type DurableOperation < Handler > = ((
input : DurableOperationInput < Handler >
) => Promise < void >) & {
/** Reads the persisted state for an idempotency key. */
getResult : (
idempotencyKey : string
) => Promise < DurableOperationResult < HandlerResult < Handler >>>;
};
/**
* Configuration for durable operations.
*
* @example
* ```ts
* const options: DurabilityOptions<typeof handlers> = {
* attemptTimeoutMs: 30_000,
* retries: { maxAttempts: 5 },
* methods: {
* resizeImage: { attemptTimeoutMs: 60_000, retries: { maxAttempts: 2 } },
* },
* };
* ```
*/
export type DurabilityOptions < Handlers extends HandlerMap = HandlerMap > =
ExecutionPolicyOptions & {
/** Execution policy overrides keyed by handler name. */
methods ?: Partial <
Record < Extract < keyof NoInfer < Handlers >, string >, DurabilityMethodOptions >
>;
/** Receives best-effort, non-durable lifecycle metrics events. */
onLifecycleEvent ?: LifecycleHook ;
/**
* Attach the handler's return value to `completed` lifecycle events.
* Off by default so results never reach telemetry sinks unintentionally;
* enable only when the sink is trusted with result content.
*/
includeResults ?: boolean ;
};
/**
* Constructor configuration: the operation handlers, their policies, and
* either a shared `scheduler` or the Durable Object `context` (plus scheduler
* options) to create a private one.
*/
export type DurabilityConfig < Handlers extends HandlerMap = HandlerMap > =
DurabilityOptions < Handlers > &
SchedulerAttachment & {
/** Operation handlers keyed by the method names they become. */
handlers : Handlers ;
/**
* Stable channel ID. Instances on one scheduler share storage,
* partitioned by channel; call IDs are unique within a channel, and
* each instance runs, lists and purges only its own. A library should
* use its own channel so its calls never meet the application's.
* Defaults to `default`.
*/
channel ?: string ;
};
const assertOperation = (
id : string ,
existingOperation : string ,
requestedOperation : string
) : void => {
if (existingOperation !== requestedOperation) {
throw new DuplicateDurableCallError (
id,
existingOperation,
requestedOperation
);
}
};
const callState = (
call : CallRow
) : Exclude < DurableOperationResult < unknown >, { status : 'not_found' }> => {
if (call.status === 'pending' ) {
return {
status: 'pending' ,
attempt: call.attempt,
nextAttemptAt: call.next_attempt_at,
lastError: call.last_error,
};
}
if (call.status === 'failed' ) {
return {
status: 'failed' ,
attempt: call.attempt,
error: {
name: call.last_error_name ?? 'Error' ,
message: call.last_error ?? 'Durable operation failed' ,
},
};
}
if (call.result === null ) {
throw new Error ( `Completed durable call "${ call . id }" has no result` );
}
return { status: 'completed' , result: deserialize (call.result) };
};
const callRecord = ( sql : SqlStorage , call : CallRow ) : UntypedRecord => {
const state = callState (call);
return {
id: call.id,
name: call.operation,
generation: call.generation_id,
createdAt: call.created_at,
state:
state.status === 'pending'
? {
... state,
memoized: memoizedKeys (
sql,
{ ... callsTable, channel: call.channel },
call.id,
call.generation_id
),
}
: state,
};
};
const operationEntity = ( call : CallRow ) : OperationLifecycleEntity => ({
entityKind: 'operation' ,
operation: call.operation,
id: call.id,
generation: call.generation_id,
});
class DurabilityCore < Handlers extends HandlerMap > {
readonly #engine : Engine ;
readonly #channel : string ;
readonly #table : DurableTable ;
readonly #handlers : Handlers ;
readonly #policy : PolicyResolver < MethodPolicy >;
readonly #lifecycle : LifecycleHooks ;
readonly #emit : LifecycleHooks [ 'emit' ];
readonly #includeResults : boolean ;
readonly #active = new Map < string , ActiveExecution >();
readonly #executionStarts = new Map < string , Promise < void >>();
constructor ( config : DurabilityConfig < Handlers >) {
const { handlers } = config;
this .#channel = assertChannel (
'Durability' ,
config.channel ?? defaultChannel
);
this .#table = { ... callsTable, channel: this .#channel };
this .#engine = engineFor (config);
this .#handlers = handlers;
this .#policy = createPolicyResolver (
config,
config.methods ?? {},
methodOptionsSchema
);
this .#lifecycle = createLifecycleHooks (
( hook ) => this .#engine. emitter (hook),
config.onLifecycleEvent
);
this .#emit = this .#lifecycle.emit;
this .#includeResults = config.includeResults ?? false ;
const reserved = new Set (
Object. getOwnPropertyNames ( DurabilityCore . prototype )
);
for ( const operation of Object. keys (handlers)) {
if (reserved. has (operation)) {
throw new Error ( `"${ operation }" is reserved by Durability` );
}
const method = Object. assign (
traceFunction (
`Durability.${ operation }` ,
( input : { id : string ; payload : unknown }) =>
this . #run ({ ... input, operation })
),
{
getResult: traceFunction (
`Durability.${ operation }.getResult` ,
( idempotencyKey : string ) =>
this . #getResult (operation, idempotencyKey)
),
}
);
Object. defineProperty ( this , operation, {
value: method,
enumerable: true ,
});
}
this .#engine. migrateSchema ( 'operations' , durabilityOperationMigrations);
this .#engine. migrateSchema ( 'memos' , durabilityMemoMigrations);
this .#engine. registerChannel ({
table: this .#table,
channel: this .#channel,
helper: 'Durability' ,
runDue : ( now ) => this . #runDue (now),
});
registerTrackedSource ( this , this . #trackedSource ());
}
/** Applies or reverts the `durability_calls` schema; see { @link migrateCapability } . */
static migrate (
context : Pick < DurableObjectState , 'storage' >,
target ?: string | null
) : DurabilityMigrationResult {
const result = migrateCapability (
context.storage,
'operations' ,
durabilityOperationMigrations,
target
);
deleteMemosOfDroppedTable (context.storage.sql, callsTable);
return result;
}
/** Processes due operations and re-arms the physical alarm. */
alarm ( info ?: AlarmInvocationInfo ) : Promise < void > {
return this .#engine. alarm (info);
}
/**
* Attaches a best-effort lifecycle hook alongside `onLifecycleEvent` and
* returns a function that detaches it.
*/
lifecycle (
hook : ( event : DurabilityOperationEvent < Handlers >) => void | Promise < void >
) : () => void {
// SAFETY: this instance emits only its purge event and events for its own
// calls, whose `operation` is a key of Handlers and whose result is that
// handler's return value.
return this .#lifecycle. add (hook as LifecycleHook );
}
/**
* Destructively removes operation records created strictly before the
* timestamp, regardless of status, and returns how many were removed.
*/
async purgeBefore ( before : number ) : Promise < number > {
const count = await this .#engine. purge (
this .#table,
before,
this .#active,
'Durable operation was purged'
);
this . #emit ({
type: 'purged' ,
entityKind: 'operation' ,
timestamp: Date. now (),
before,
count,
});
return count;
}
# trackedSource () : UntypedSource {
const sql = this .#engine.sql;
return {
get : async ( id ) => {
const call = readCall (sql, this .#channel, id);
return call && callRecord (sql, call);
},
list : async ({ limit , cursor , status , name }) => {
const page = listCreated (sql, this .#table, 'operation' , {
limit,
after: cursor,
status,
name,
});
const records = v
. parse (v. array (callRowSchema), page.rows)
. map (( call ) => callRecord (sql, call));
return page.next === undefined
? { records }
: { records, cursor: page.next };
},
watch : ( id , listener ) =>
this .#engine. watch ( this .#table, id, () => listener ()),
};
}
async # runDue ( now : number ) : Promise < void > {
const due = v. parse (
v. array (v. object ({ id: v. string () })),
this .#engine.sql
. exec (
`SELECT id FROM durability_calls
WHERE channel = ? AND status = 'pending' AND next_attempt_at <= ?
ORDER BY next_attempt_at ASC
LIMIT 100` ,
this .#channel,
now
)
. toArray ()
);
// With liveTimers an active operation reschedules itself when it settles, so
// skipping it keeps a long handler from blocking a concurrent alarm pass.
const pending = this .#engine.liveTimers
? due. filter (({ id : key }) => ! this .#active. has (key))
: due;
await this .#engine. runConcurrent (pending, async ({ id : key }) => {
try {
await this . #execute (key);
} catch {
return ;
}
});
}
async # getResult (
operation : string ,
idempotencyKey : string
) : Promise < DurableOperationResult < unknown >> {
const call = readCall ( this .#engine.sql, this .#channel, idempotencyKey);
if ( ! call) {
return { status: 'not_found' };
}
assertOperation (idempotencyKey, call.operation, operation);
return callState (call);
}
async # run ( input : {
id : string ;
operation : string ;
payload : unknown ;
}) : Promise < void > {
const key = input.id;
const payload = serialize (input.payload);
const now = Date. now ();
const generation = crypto. randomUUID ();
const { inserted , winner } = await this .#engine. transaction (( sql ) => {
const created =
sql
. exec (
`INSERT INTO durability_calls
(id, channel, operation, payload, status, attempt,
next_attempt_at, created_at, generation_id)
VALUES (?, ?, ?, ?, 'pending', 0, ?, ?, ?)
ON CONFLICT(channel, id) DO NOTHING
RETURNING id` ,
key,
this .#channel,
input.operation,
payload,
now,
now,
generation
)
. toArray (). length > 0 ;
const current = readCall (sql, this .#channel, key);
if ( ! current) {
throw new Error ( `Durable call "${ input . id }" was not persisted` );
}
assertOperation (input.id, current.operation, input.operation);
// Reuse is idempotent only for the same data; anything else is a caller
// bug that would otherwise be dropped silently.
if ( ! created && canonical (current.payload) !== canonical (payload)) {
throw new DuplicateDurablePayloadError (input.id, input.operation);
}
return { inserted: created, winner: current };
});
if ( ! inserted) {
return ;
}
this . #emit ({
... operationEntity (winner),
type: 'registered' ,
timestamp: now,
attempt: 0 ,
});
// Start eagerly only when a permit is free; otherwise the reconciled alarm picks the row up.
const eagerPermit = this .#engine. tryAcquirePermit ();
if ( ! eagerPermit) {
return ;
}
const onError = ( cause : unknown ) =>
reportFailure (
'durability.background_execution.failed' ,
{ operation: input.operation, id: input.id },
cause
);
const background = this . #execute (key, eagerPermit)
. then (() => this .#engine. scheduleNextAlarm ())
. catch (onError);
this .#engine. waitUntil (background, onError);
}
/**
* Looks up a call by row key and starts it unless the same generation is
* already running. Lookups for one key are serialized so two concurrent
* callers cannot both miss the active map while awaiting storage.
*/
async # execute ( key : string , eagerPermit ?: () => void ) : Promise < void > {
const previousStart = this .#executionStarts. get (key) ?? Promise . resolve ();
let releaseStart !: () => void ;
const currentStart = new Promise < void >(( resolve ) => {
releaseStart = resolve;
});
this .#executionStarts. set (key, currentStart);
let permitTransferred = false ;
try {
await previousStart;
const call = readCall ( this .#engine.sql, this .#channel, key);
if ( ! call || call.status !== 'pending' ) {
return ;
}
const running = this .#active. get (key);
if (running?.generation === call.generation_id) {
releaseStart ();
await running.settled;
return ;
}
const execution = this . #start (call, eagerPermit);
permitTransferred = true ;
releaseStart ();
return execution;
} finally {
releaseStart ();
if ( this .#executionStarts. get (key) === currentStart) {
this .#executionStarts. delete (key);
}
if ( ! permitTransferred) {
eagerPermit ?.();
}
}
}
# start ( call : CallRow , eagerPermit : (() => void ) | undefined ) : Promise < void > {
const policy = this . #policy (call.operation);
// SAFETY: the row was stored by the method for `call.operation`, which
// takes that handler's payload; rows of removed handlers find undefined.
const handler = this .#handlers[call.operation] as
| (( durableCall : DurableCall < unknown >) => unknown)
| undefined ;
return this .#engine. startExecution (
{
table: this .#table,
key: call.id,
row: call,
label: `operation "${ call . operation }"` ,
entity: operationEntity (call),
active: this .#active,
policy,
emit: this .#emit,
includeResult: this .#includeResults,
exhaustedError : () =>
new DurableAttemptsExhaustedError (
'operation' ,
call.operation,
policy.maxAttempts
),
timeoutError : () =>
new DurableAttemptTimeoutError (
call.operation,
policy.attemptTimeoutMs
),
invoke : ( attempt , signal ) => {
if ( ! handler) {
throw new NonRetryableError (
`No handler registered for operation "${ call . operation }"`
);
}
return handler ({
id: call.id,
operation: call.operation,
payload: deserialize (call.payload),
attempt,
signal,
memoize: createMemoize ( this .#engine.sql, this .#table, {
key: call.id,
generation: call.generation_id,
attempt,
}),
});
},
complete : ( result , attempt ) => {
let serialized : string ;
try {
serialized = serialize (result);
} catch (error) {
throw new DurableResultSerializationError (call.operation, error);
}
const timestamp = Date. now ();
const updated = updateAttempt (
this .#engine.sql,
this .#table,
{ key: call.id, generation: call.generation_id, attempt },
`status = 'completed', result = ?, last_error = NULL,
last_error_name = NULL, completed_at = ?` ,
serialized,
timestamp
);
return updated ? timestamp : undefined ;
},
isTerminal : ( error ) =>
isErrorInstance (error, DurableResultSerializationError),
},
eagerPermit
);
}
}
type OperationMethods < Handlers extends HandlerMap > = {
[ Operation in keyof Handlers ] : DurableOperation < Handlers [ Operation ]>;
};
/**
* Alarm-backed, at-least-once durable operations for one Durable Object.
*
* Every handler becomes a typed method on the instance. Methods resolve once
* the call is durably registered; read outcomes through `getResult`.
*
* Delivery is at least once: a handler may run again after a crash, timeout, or
* eviction. The call `id` is a stable idempotency key; pass it to external
* systems and make effects idempotent or reconcilable to reach an effectively
* once outcome. See the README "Delivery and safety contract".
*
* @example
* ```ts
* class ImageJobs extends DurableObject<Env> {
* private readonly durability = new Durability({
* context: this.ctx,
* handlers: {
* resizeImage: async ({ id, payload }: DurableCall<{ imageId: string }>) =>
* this.env.IMAGES.resize(payload.imageId, { idempotencyKey: id }),
* },
* });
*
* resize(imageId: string) {
* return this.durability.resizeImage({ id: `resize:${imageId}`, payload: { imageId } });
* }
*
* alarm(info?: AlarmInvocationInfo) {
* return this.durability.alarm(info);
* }
* }
* ```
*/
export type Durability < Handlers extends HandlerMap > = DurabilityCore < Handlers > &
OperationMethods < Handlers >;
/** Any `Durability` instance, without the index signature of `Durability<HandlerMap>`. */
export type AnyDurability = DurabilityCore < HandlerMap >;
export interface DurabilityConstructor {
new < Handlers extends HandlerMap >(
config : DurabilityConfig < Handlers >
) : Durability < Handlers >;
migrate : typeof DurabilityCore.migrate;
}
traceMethods ( DurabilityCore . prototype , 'Durability' );
// SAFETY: the constructor defines a method for every handler name on the
// instance, members TypeScript cannot declare from a generic handler map.
export const Durability = DurabilityCore as DurabilityConstructor ;