/**
* Producer side of the `job-dashboard` example. Runs durable operations, fans
* their lifecycle out to the tenant's `Dashboard`, and hands out tracker
* handles so callers can wait for a result over Workers RPC. Browsers never
* connect here.
*/
import { DurableObject } from 'cloudflare:workers';
import {
Durability,
DurabilityFanout,
DurabilityScheduler,
type DurableCall,
} from 'durability';
import { DurabilityTracker } from 'durability/experimental';
import type { Env, JobEvent, OrderSummary } from './shared';
export class Pipeline extends DurableObject<Env> {
private readonly scheduler = new DurabilityScheduler({ context: this.ctx });
private readonly durability = new Durability({
scheduler: this.scheduler,
handlers: {
importOrder: async ({
id,
payload,
signal,
}: DurableCall<{ orderId: string }>): Promise<OrderSummary> => {
const response = await this.env.ORDERS.fetch(
`https://orders/${payload.orderId}`,
{ headers: { 'Idempotency-Key': id }, signal }
);
if (!response.ok) {
throw new Error(`Order lookup failed with ${response.status}`);
}
return response.json();
},
},
// Completed lifecycle events carry the summary the dashboard publishes.
includeResults: true,
});
private readonly tracker = new DurabilityTracker({
sources: { jobs: this.durability },
});
// Push side. Delivery is durable: the dashboard gets the batch again after
// an eviction or a failed call, until `ingest` returns without throwing.
private readonly fanout = new DurabilityFanout<JobEvent>({
scheduler: this.scheduler,
targets: {
dashboard: {
deliver: (messages) =>
this.env.DASHBOARD.getByName(this.tenant).ingest(
messages.map((message) => message.body)
),
ackOnReturn: true,
},
},
batchDelayMs: 100,
});
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
// Lifecycle hooks are best-effort. If the object dies between a job
// settling and this enqueue committing, that one event is lost until the
// dashboard resyncs. Enqueue from inside the handler, keyed by `id`, when
// that gap matters.
this.durability.lifecycle((event) => {
if (event.type === 'registered') {
return this.publish(event, { status: 'pending' });
}
if (
event.type === 'attempt_settled' &&
event.outcome === 'completed' &&
event.result !== undefined
) {
return this.publish(event, {
status: 'completed',
result: event.result,
});
}
if (
(event.type === 'attempt_settled' && event.outcome === 'failed') ||
event.type === 'terminal'
) {
return this.publish(event, { status: 'failed', error: event.error });
}
return undefined;
});
}
private get tenant(): string {
return this.ctx.id.name ?? this.ctx.id.toString();
}
private async publish(
event: { id: string; generation: string; timestamp: number },
state: JobEvent['state']
): Promise<void> {
await this.fanout.enqueue([
{
id: `${event.id}:${event.generation}:${state.status}`,
body: {
id: event.id,
name: 'importOrder',
generation: event.generation,
createdAt: event.timestamp,
state,
},
},
]);
}
/** Registers the import; resolves on acceptance, not completion. */
importOrder(orderId: string) {
return this.durability.importOrder({
id: `import:${orderId}`,
payload: { orderId },
});
}
/**
* Pull side. Over Workers RPC the handle's `get` and `wait` become stubs, so
* `stub.track(id).wait({ timeoutMs })` waits in one pipelined round trip.
*/
async track(orderId: string) {
const handle = await this.tracker.get('jobs', `import:${orderId}`);
if (!handle) {
throw new Error(`Order "${orderId}" was never imported`);
}
return handle;
}
override alarm(info?: AlarmInvocationInfo) {
return this.scheduler.alarm(info);
}
}
/**
* Hub of the `job-dashboard` example. Three kinds of peers talk to it:
*
* - Browsers, over `DurabilitySocket`. `work` serves `tracker.records()` as
* the snapshot (plain JSON, no functions); every ingested change is pushed
* as a `job` event, which the socket persists and replays after reconnects.
* `importOrder` starts a job on the tenant's `Pipeline` and waits for its
* result through a tracker handle, in one pipelined RPC round trip.
* - The tenant's `Pipeline`, through fanout deliveries into `ingest`.
*
* The ingested table is itself a `TrackedSource`, so `this.tracker.get` also
* works locally: its `watch` is settled by `ingest`.
*/
import { DurableObject } from 'cloudflare:workers';
import {
DurabilityTracker,
type TrackedRecord,
type TrackedSource,
type TrackedStatus,
} from 'durability/experimental';
import { DurabilitySocket, event } from 'durability/socket';
import * as v from 'valibot';
import type { Env, JobEvent, Jobs } from './shared';
type JobRow = {
id: string;
name: string;
generation: string;
created_at: number;
status: string;
state: string;
};
const toRecord = (row: JobRow): TrackedRecord<Jobs> => ({
id: row.id,
name: 'importOrder',
generation: row.generation,
createdAt: row.created_at,
state: JSON.parse(row.state),
});
// Browsers send the cursor back, so it is parsed like any other input.
const jobsCursor = v.tuple([v.number(), v.string()]);
const workQuery = v.object({
cursor: v.optional(v.string()),
status: v.optional(v.picklist(['pending', 'completed', 'failed'])),
});
export class Dashboard extends DurableObject<Env> {
private readonly sql = this.ctx.storage.sql;
private readonly watchers = new Map<
string,
Set<(settled?: TrackedRecord<Jobs>) => void>
>();
/** The ingested table, read through the tracker's source contract. */
private readonly jobs: TrackedSource<Jobs> = {
get: async (id) => {
const row = this.readRow(id);
return row && toRecord(row);
},
list: async ({ limit, cursor, status, name }) => {
const [createdAt, afterId] =
cursor === undefined
? [-1, '']
: v.parse(jobsCursor, JSON.parse(cursor));
const rows = this.sql
.exec<JobRow>(
`SELECT * FROM jobs
WHERE (? IS NULL OR status = ?)
AND (? IS NULL OR name = ?)
AND (created_at > ? OR (created_at = ? AND id > ?))
ORDER BY created_at, id
LIMIT ?`,
status ?? null,
status ?? null,
name ?? null,
name ?? null,
createdAt,
createdAt,
afterId,
limit + 1
)
.toArray();
const page = rows.slice(0, limit);
const last = page[page.length - 1];
const records = page.map(toRecord);
return rows.length > limit && last
? { records, cursor: JSON.stringify([last.created_at, last.id]) }
: { records };
},
watch: (id, listener) => {
const listeners = this.watchers.get(id) ?? new Set();
this.watchers.set(id, listeners.add(listener));
return () => {
listeners.delete(listener);
};
},
};
private readonly tracker = new DurabilityTracker({
sources: { jobs: this.jobs },
});
readonly socket = new DurabilitySocket({
context: this.ctx,
inbound: {
importOrder: {
input: v.pipe(v.string(), v.minLength(1)),
handle: async (orderId: string) => {
const pipeline = this.env.PIPELINE.getByName(this.tenant);
await pipeline.importOrder(orderId);
return pipeline.track(orderId).wait({ timeoutMs: 30_000 });
},
},
work: {
input: workQuery,
handle: (query: {
cursor?: string | undefined;
status?: TrackedStatus | undefined;
}) => this.tracker.records(query),
},
},
outbound: { job: event<TrackedRecord<Jobs>>() },
});
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
this.sql.exec(
`CREATE TABLE IF NOT EXISTS jobs (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
generation TEXT NOT NULL,
created_at INTEGER NOT NULL,
status TEXT NOT NULL,
state TEXT NOT NULL
)`
);
}
private get tenant(): string {
return this.ctx.id.name ?? this.ctx.id.toString();
}
/** Called by the pipeline's fanout. Returning without throwing acks the batch. */
ingest(events: JobEvent[]): void {
for (const job of events) {
// Deliveries can arrive out of order on retry: a late `pending` must not
// overwrite a settled row of the same generation.
this.sql.exec(
`INSERT INTO jobs (id, name, generation, created_at, status, state)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
generation = excluded.generation,
created_at = excluded.created_at,
status = excluded.status,
state = excluded.state
WHERE excluded.generation != jobs.generation OR jobs.status = 'pending'`,
job.id,
job.name,
job.generation,
job.createdAt,
job.state.status,
JSON.stringify(job.state)
);
const row = this.readRow(job.id);
if (!row) {
continue;
}
const record = toRecord(row);
this.socket.job(record);
for (const listener of this.watchers.get(job.id) ?? []) {
listener();
}
}
}
private readRow(id: string): JobRow | undefined {
return this.sql
.exec<JobRow>('SELECT * FROM jobs WHERE id = ?', id)
.toArray()[0];
}
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);
}
}
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';