@rivetkit/engine-runner 2.0.4-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mod.d.cts ADDED
@@ -0,0 +1,298 @@
1
+ import * as protocol from '@rivetkit/engine-runner-protocol';
2
+ import { GatewayId, RequestId } from '@rivetkit/engine-runner-protocol';
3
+ import { Logger } from 'pino';
4
+ import WebSocket from 'ws';
5
+ import { UniversalWebSocket } from '@rivetkit/virtual-websocket';
6
+
7
+ interface PendingRequest {
8
+ resolve: (response: Response) => void;
9
+ reject: (error: Error) => void;
10
+ streamController?: ReadableStreamDefaultController<Uint8Array>;
11
+ actorId?: string;
12
+ gatewayId?: GatewayId;
13
+ requestId?: RequestId;
14
+ clientMessageIndex: number;
15
+ }
16
+ interface HibernatingWebSocketMetadata {
17
+ gatewayId: GatewayId;
18
+ requestId: RequestId;
19
+ clientMessageIndex: number;
20
+ serverMessageIndex: number;
21
+ path: string;
22
+ headers: Record<string, string>;
23
+ }
24
+ declare class Tunnel {
25
+ #private;
26
+ get log(): Logger | undefined;
27
+ constructor(runner: Runner);
28
+ start(): void;
29
+ resendBufferedEvents(): void;
30
+ shutdown(): void;
31
+ restoreHibernatingRequests(actorId: string, metaEntries: HibernatingWebSocketMetadata[]): Promise<void>;
32
+ addRequestToActor(gatewayId: GatewayId, requestId: RequestId, actorId: string): void;
33
+ getRequestActor(gatewayId: GatewayId, requestId: RequestId): RunnerActor | undefined;
34
+ getAndWaitForRequestActor(gatewayId: GatewayId, requestId: RequestId): Promise<RunnerActor | undefined>;
35
+ closeActiveRequests(actor: RunnerActor): void;
36
+ handleTunnelMessage(message: protocol.ToClientTunnelMessage): Promise<void>;
37
+ sendHibernatableWebSocketMessageAck(gatewayId: ArrayBuffer, requestId: ArrayBuffer, clientMessageIndex: number): void;
38
+ }
39
+
40
+ /**
41
+ * Polyfill for Promise.withResolvers().
42
+ *
43
+ * This is specifically for Cloudflare Workers. Their implementation of Promise.withResolvers does not work correctly.
44
+ */
45
+ declare function promiseWithResolvers<T>(): {
46
+ promise: Promise<T>;
47
+ resolve: (value: T | PromiseLike<T>) => void;
48
+ reject: (reason?: any) => void;
49
+ };
50
+ declare function idToStr(id: ArrayBuffer): string;
51
+
52
+ declare const HIBERNATABLE_SYMBOL: unique symbol;
53
+ declare class WebSocketTunnelAdapter {
54
+ #private;
55
+ readonly request: Request;
56
+ get [HIBERNATABLE_SYMBOL](): boolean;
57
+ constructor(tunnel: Tunnel, actorId: string, requestId: string, serverMessageIndex: number, hibernatable: boolean, isRestoringHibernatable: boolean, request: Request, sendCallback: (data: ArrayBuffer | string, isBinary: boolean) => void, closeCallback: (code?: number, reason?: string) => void);
58
+ get websocket(): UniversalWebSocket;
59
+ _handleOpen(requestId: ArrayBuffer): void;
60
+ _handleMessage(requestId: ArrayBuffer, data: string | Uint8Array, serverMessageIndex: number, isBinary: boolean): boolean;
61
+ _handleClose(_requestId: ArrayBuffer, code?: number, reason?: string): void;
62
+ _closeWithoutCallback(code?: number, reason?: string): void;
63
+ close(code?: number, reason?: string): void;
64
+ }
65
+
66
+ interface ActorConfig {
67
+ name: string;
68
+ key: string | null;
69
+ createTs: bigint;
70
+ input: Uint8Array | null;
71
+ }
72
+ declare class RunnerActor {
73
+ /**
74
+ * List of hibernating requests provided by the gateway on actor start.
75
+ * This represents the WebSocket connections that the gateway knows about.
76
+ **/
77
+ hibernatingRequests: readonly protocol.HibernatingRequest[];
78
+ actorId: string;
79
+ generation: number;
80
+ config: ActorConfig;
81
+ pendingRequests: Array<{
82
+ gatewayId: protocol.GatewayId;
83
+ requestId: protocol.RequestId;
84
+ request: PendingRequest;
85
+ }>;
86
+ webSockets: Array<{
87
+ gatewayId: protocol.GatewayId;
88
+ requestId: protocol.RequestId;
89
+ ws: WebSocketTunnelAdapter;
90
+ }>;
91
+ actorStartPromise: ReturnType<typeof promiseWithResolvers<void>>;
92
+ lastCommandIdx: bigint;
93
+ nextEventIdx: bigint;
94
+ eventHistory: protocol.EventWrapper[];
95
+ /**
96
+ * If restoreHibernatingRequests has been called. This is used to assert
97
+ * that the caller is implemented correctly.
98
+ **/
99
+ hibernationRestored: boolean;
100
+ constructor(actorId: string, generation: number, config: ActorConfig,
101
+ /**
102
+ * List of hibernating requests provided by the gateway on actor start.
103
+ * This represents the WebSocket connections that the gateway knows about.
104
+ **/
105
+ hibernatingRequests: readonly protocol.HibernatingRequest[]);
106
+ getPendingRequest(gatewayId: protocol.GatewayId, requestId: protocol.RequestId): PendingRequest | undefined;
107
+ createPendingRequest(gatewayId: protocol.GatewayId, requestId: protocol.RequestId, clientMessageIndex: number): void;
108
+ createPendingRequestWithStreamController(gatewayId: protocol.GatewayId, requestId: protocol.RequestId, clientMessageIndex: number, streamController: ReadableStreamDefaultController<Uint8Array>): void;
109
+ deletePendingRequest(gatewayId: protocol.GatewayId, requestId: protocol.RequestId): void;
110
+ getWebSocket(gatewayId: protocol.GatewayId, requestId: protocol.RequestId): WebSocketTunnelAdapter | undefined;
111
+ setWebSocket(gatewayId: protocol.GatewayId, requestId: protocol.RequestId, ws: WebSocketTunnelAdapter): void;
112
+ deleteWebSocket(gatewayId: protocol.GatewayId, requestId: protocol.RequestId): void;
113
+ handleAckEvents(lastEventIdx: bigint): void;
114
+ recordEvent(eventWrapper: protocol.EventWrapper): void;
115
+ }
116
+
117
+ declare class RunnerShutdownError extends Error {
118
+ constructor();
119
+ }
120
+ interface RunnerConfig {
121
+ logger?: Logger;
122
+ version: number;
123
+ endpoint: string;
124
+ token?: string;
125
+ pegboardEndpoint?: string;
126
+ pegboardRelayEndpoint?: string;
127
+ namespace: string;
128
+ totalSlots: number;
129
+ runnerName: string;
130
+ runnerKey: string;
131
+ prepopulateActorNames: Record<string, {
132
+ metadata: Record<string, any>;
133
+ }>;
134
+ metadata?: Record<string, any>;
135
+ onConnected: () => void;
136
+ onDisconnected: (code: number, reason: string) => void;
137
+ onShutdown: () => void;
138
+ /** Called when receiving a network request. */
139
+ fetch: (runner: Runner, actorId: string, gatewayId: protocol.GatewayId, requestId: protocol.RequestId, request: Request) => Promise<Response>;
140
+ /**
141
+ * Called when receiving a WebSocket connection.
142
+ *
143
+ * All event listeners must be added synchronously inside this function or
144
+ * else events may be missed. The open event will fire immediately after
145
+ * this function finishes.
146
+ *
147
+ * Any errors thrown here will disconnect the WebSocket immediately.
148
+ *
149
+ * While `path` and `headers` are partially redundant to the data in the
150
+ * `Request`, they may vary slightly from the actual content of `Request`.
151
+ * Prefer to persist the `path` and `headers` properties instead of the
152
+ * `Request` itself.
153
+ *
154
+ * ## Hibernating Web Sockets
155
+ *
156
+ * ### Implementation Requirements
157
+ *
158
+ * **Requirement 1: Persist HWS Immediately**
159
+ *
160
+ * This is responsible for persisting hibernatable WebSockets immediately
161
+ * (do not wait for open event). It is not time sensitive to flush the
162
+ * connection state. If this fails to persist the HWS, the client's
163
+ * WebSocket will be disconnected on next wake in the call to
164
+ * `Tunnel::restoreHibernatingRequests` since the connection entry will not
165
+ * exist.
166
+ *
167
+ * **Requirement 2: Persist Message Index On `message`**
168
+ *
169
+ * In the `message` event listener, this handler must persist the message
170
+ * index from the event. The request ID is available at
171
+ * `event.rivetRequestId` and message index at `event.rivetMessageIndex`.
172
+ *
173
+ * The message index should not be flushed immediately. Instead, this
174
+ * should:
175
+ *
176
+ * - Debounce calls to persist the message index
177
+ * - After each persist, call
178
+ * `Runner::sendHibernatableWebSocketMessageAck` to acknowledge the
179
+ * message
180
+ *
181
+ * This mechanism allows us to buffer messages on the gateway so we can
182
+ * batch-persist events on our end on a given interval.
183
+ *
184
+ * If this fails to persist, then the gateway will replay unacked
185
+ * messages when the actor starts again.
186
+ *
187
+ * **Requirement 3: Remove HWS From Storage On `close`**
188
+ *
189
+ * This handler should add an event listener for `close` to remove the
190
+ * connection from storage.
191
+ *
192
+ * If the connection remove fails to persist, the close event will be
193
+ * called again on the next actor start in
194
+ * `Tunnel::restoreHibernatingRequests` since there will be no request for
195
+ * the given connection.
196
+ *
197
+ * ### Restoring Connections
198
+ *
199
+ * The user of this library is responsible for:
200
+ * 1. Loading all persisted hibernatable WebSocket metadata for an actor
201
+ * 2. Calling `Runner::restoreHibernatingRequests` with this metadata at
202
+ * the end of `onActorStart`
203
+ *
204
+ * `restoreHibernatingRequests` will restore all connections and attach
205
+ * the appropriate event listeners.
206
+ *
207
+ * ### No Open Event On Restoration
208
+ *
209
+ * When restoring a HWS, the open event will not be called again. It will
210
+ * go straight to the message or close event.
211
+ */
212
+ websocket: (runner: Runner, actorId: string, ws: any, gatewayId: protocol.GatewayId, requestId: protocol.RequestId, request: Request, path: string, headers: Record<string, string>, isHibernatable: boolean, isRestoringHibernatable: boolean) => Promise<void>;
213
+ hibernatableWebSocket: {
214
+ /**
215
+ * Determines if a WebSocket can continue to live while an actor goes to
216
+ * sleep.
217
+ */
218
+ canHibernate: (actorId: string, gatewayId: ArrayBuffer, requestId: ArrayBuffer, request: Request) => boolean;
219
+ };
220
+ /**
221
+ * Called when an actor starts.
222
+ *
223
+ * This callback is responsible for:
224
+ * 1. Initializing the actor instance
225
+ * 2. Loading all persisted hibernatable WebSocket metadata for this actor
226
+ * 3. Calling `Runner::restoreHibernatingRequests` with the loaded metadata
227
+ * to restore hibernatable WebSocket connections
228
+ *
229
+ * The actor should not be marked as "ready" until after
230
+ * `restoreHibernatingRequests` completes to ensure all hibernatable
231
+ * connections are fully restored before the actor processes new requests.
232
+ */
233
+ onActorStart: (actorId: string, generation: number, config: ActorConfig) => Promise<void>;
234
+ onActorStop: (actorId: string, generation: number) => Promise<void>;
235
+ noAutoShutdown?: boolean;
236
+ }
237
+ interface KvListOptions {
238
+ reverse?: boolean;
239
+ limit?: number;
240
+ }
241
+ declare class Runner {
242
+ #private;
243
+ get config(): RunnerConfig;
244
+ runnerId?: string;
245
+ get log(): Logger | undefined;
246
+ constructor(config: RunnerConfig);
247
+ sleepActor(actorId: string, generation?: number): void;
248
+ stopActor(actorId: string, generation?: number): Promise<void>;
249
+ forceStopActor(actorId: string, generation?: number): Promise<void>;
250
+ getActor(actorId: string, generation?: number): RunnerActor | undefined;
251
+ getAndWaitForActor(actorId: string, generation?: number): Promise<RunnerActor | undefined>;
252
+ hasActor(actorId: string, generation?: number): boolean;
253
+ get actors(): Map<string, RunnerActor>;
254
+ start(): Promise<void>;
255
+ shutdown(immediate: boolean, exit?: boolean): Promise<void>;
256
+ get pegboardEndpoint(): string;
257
+ get pegboardUrl(): string;
258
+ kvGet(actorId: string, keys: Uint8Array[]): Promise<(Uint8Array | null)[]>;
259
+ kvListAll(actorId: string, options?: KvListOptions): Promise<[Uint8Array, Uint8Array][]>;
260
+ kvListRange(actorId: string, start: Uint8Array, end: Uint8Array, exclusive?: boolean, options?: KvListOptions): Promise<[Uint8Array, Uint8Array][]>;
261
+ kvListPrefix(actorId: string, prefix: Uint8Array, options?: KvListOptions): Promise<[Uint8Array, Uint8Array][]>;
262
+ kvPut(actorId: string, entries: [Uint8Array, Uint8Array][]): Promise<void>;
263
+ kvDelete(actorId: string, keys: Uint8Array[]): Promise<void>;
264
+ kvDrop(actorId: string): Promise<void>;
265
+ setAlarm(actorId: string, alarmTs: number | null, generation?: number): void;
266
+ clearAlarm(actorId: string, generation?: number): void;
267
+ /** Asserts WebSocket exists and is ready. */
268
+ getPegboardWebSocketIfReady(): WebSocket | undefined;
269
+ __sendToServer(message: protocol.ToServer): void;
270
+ sendHibernatableWebSocketMessageAck(gatewayId: ArrayBuffer, requestId: ArrayBuffer, index: number): void;
271
+ /**
272
+ * Restores hibernatable WebSocket connections for an actor.
273
+ *
274
+ * This method should be called at the end of `onActorStart` after the
275
+ * actor instance is fully initialized.
276
+ *
277
+ * This method will:
278
+ * - Restore all provided hibernatable WebSocket connections
279
+ * - Attach event listeners to the restored WebSockets
280
+ * - Close any WebSocket connections that failed to restore
281
+ *
282
+ * The provided metadata list should include all hibernatable WebSockets
283
+ * that were persisted for this actor. The gateway will automatically
284
+ * close any connections that are not restored (i.e., not included in
285
+ * this list).
286
+ *
287
+ * **Important:** This method must be called after `onActorStart` completes
288
+ * and before marking the actor as "ready" to ensure all hibernatable
289
+ * connections are fully restored.
290
+ *
291
+ * @param actorId - The ID of the actor to restore connections for
292
+ * @param metaEntries - Array of hibernatable WebSocket metadata to restore
293
+ */
294
+ restoreHibernatingRequests(actorId: string, metaEntries: HibernatingWebSocketMetadata[]): Promise<void>;
295
+ getServerlessInitPacket(): string | undefined;
296
+ }
297
+
298
+ export { type ActorConfig, type HibernatingWebSocketMetadata, type KvListOptions, Runner, RunnerActor, type RunnerConfig, RunnerShutdownError, idToStr };
package/dist/mod.d.ts ADDED
@@ -0,0 +1,298 @@
1
+ import * as protocol from '@rivetkit/engine-runner-protocol';
2
+ import { GatewayId, RequestId } from '@rivetkit/engine-runner-protocol';
3
+ import { Logger } from 'pino';
4
+ import WebSocket from 'ws';
5
+ import { UniversalWebSocket } from '@rivetkit/virtual-websocket';
6
+
7
+ interface PendingRequest {
8
+ resolve: (response: Response) => void;
9
+ reject: (error: Error) => void;
10
+ streamController?: ReadableStreamDefaultController<Uint8Array>;
11
+ actorId?: string;
12
+ gatewayId?: GatewayId;
13
+ requestId?: RequestId;
14
+ clientMessageIndex: number;
15
+ }
16
+ interface HibernatingWebSocketMetadata {
17
+ gatewayId: GatewayId;
18
+ requestId: RequestId;
19
+ clientMessageIndex: number;
20
+ serverMessageIndex: number;
21
+ path: string;
22
+ headers: Record<string, string>;
23
+ }
24
+ declare class Tunnel {
25
+ #private;
26
+ get log(): Logger | undefined;
27
+ constructor(runner: Runner);
28
+ start(): void;
29
+ resendBufferedEvents(): void;
30
+ shutdown(): void;
31
+ restoreHibernatingRequests(actorId: string, metaEntries: HibernatingWebSocketMetadata[]): Promise<void>;
32
+ addRequestToActor(gatewayId: GatewayId, requestId: RequestId, actorId: string): void;
33
+ getRequestActor(gatewayId: GatewayId, requestId: RequestId): RunnerActor | undefined;
34
+ getAndWaitForRequestActor(gatewayId: GatewayId, requestId: RequestId): Promise<RunnerActor | undefined>;
35
+ closeActiveRequests(actor: RunnerActor): void;
36
+ handleTunnelMessage(message: protocol.ToClientTunnelMessage): Promise<void>;
37
+ sendHibernatableWebSocketMessageAck(gatewayId: ArrayBuffer, requestId: ArrayBuffer, clientMessageIndex: number): void;
38
+ }
39
+
40
+ /**
41
+ * Polyfill for Promise.withResolvers().
42
+ *
43
+ * This is specifically for Cloudflare Workers. Their implementation of Promise.withResolvers does not work correctly.
44
+ */
45
+ declare function promiseWithResolvers<T>(): {
46
+ promise: Promise<T>;
47
+ resolve: (value: T | PromiseLike<T>) => void;
48
+ reject: (reason?: any) => void;
49
+ };
50
+ declare function idToStr(id: ArrayBuffer): string;
51
+
52
+ declare const HIBERNATABLE_SYMBOL: unique symbol;
53
+ declare class WebSocketTunnelAdapter {
54
+ #private;
55
+ readonly request: Request;
56
+ get [HIBERNATABLE_SYMBOL](): boolean;
57
+ constructor(tunnel: Tunnel, actorId: string, requestId: string, serverMessageIndex: number, hibernatable: boolean, isRestoringHibernatable: boolean, request: Request, sendCallback: (data: ArrayBuffer | string, isBinary: boolean) => void, closeCallback: (code?: number, reason?: string) => void);
58
+ get websocket(): UniversalWebSocket;
59
+ _handleOpen(requestId: ArrayBuffer): void;
60
+ _handleMessage(requestId: ArrayBuffer, data: string | Uint8Array, serverMessageIndex: number, isBinary: boolean): boolean;
61
+ _handleClose(_requestId: ArrayBuffer, code?: number, reason?: string): void;
62
+ _closeWithoutCallback(code?: number, reason?: string): void;
63
+ close(code?: number, reason?: string): void;
64
+ }
65
+
66
+ interface ActorConfig {
67
+ name: string;
68
+ key: string | null;
69
+ createTs: bigint;
70
+ input: Uint8Array | null;
71
+ }
72
+ declare class RunnerActor {
73
+ /**
74
+ * List of hibernating requests provided by the gateway on actor start.
75
+ * This represents the WebSocket connections that the gateway knows about.
76
+ **/
77
+ hibernatingRequests: readonly protocol.HibernatingRequest[];
78
+ actorId: string;
79
+ generation: number;
80
+ config: ActorConfig;
81
+ pendingRequests: Array<{
82
+ gatewayId: protocol.GatewayId;
83
+ requestId: protocol.RequestId;
84
+ request: PendingRequest;
85
+ }>;
86
+ webSockets: Array<{
87
+ gatewayId: protocol.GatewayId;
88
+ requestId: protocol.RequestId;
89
+ ws: WebSocketTunnelAdapter;
90
+ }>;
91
+ actorStartPromise: ReturnType<typeof promiseWithResolvers<void>>;
92
+ lastCommandIdx: bigint;
93
+ nextEventIdx: bigint;
94
+ eventHistory: protocol.EventWrapper[];
95
+ /**
96
+ * If restoreHibernatingRequests has been called. This is used to assert
97
+ * that the caller is implemented correctly.
98
+ **/
99
+ hibernationRestored: boolean;
100
+ constructor(actorId: string, generation: number, config: ActorConfig,
101
+ /**
102
+ * List of hibernating requests provided by the gateway on actor start.
103
+ * This represents the WebSocket connections that the gateway knows about.
104
+ **/
105
+ hibernatingRequests: readonly protocol.HibernatingRequest[]);
106
+ getPendingRequest(gatewayId: protocol.GatewayId, requestId: protocol.RequestId): PendingRequest | undefined;
107
+ createPendingRequest(gatewayId: protocol.GatewayId, requestId: protocol.RequestId, clientMessageIndex: number): void;
108
+ createPendingRequestWithStreamController(gatewayId: protocol.GatewayId, requestId: protocol.RequestId, clientMessageIndex: number, streamController: ReadableStreamDefaultController<Uint8Array>): void;
109
+ deletePendingRequest(gatewayId: protocol.GatewayId, requestId: protocol.RequestId): void;
110
+ getWebSocket(gatewayId: protocol.GatewayId, requestId: protocol.RequestId): WebSocketTunnelAdapter | undefined;
111
+ setWebSocket(gatewayId: protocol.GatewayId, requestId: protocol.RequestId, ws: WebSocketTunnelAdapter): void;
112
+ deleteWebSocket(gatewayId: protocol.GatewayId, requestId: protocol.RequestId): void;
113
+ handleAckEvents(lastEventIdx: bigint): void;
114
+ recordEvent(eventWrapper: protocol.EventWrapper): void;
115
+ }
116
+
117
+ declare class RunnerShutdownError extends Error {
118
+ constructor();
119
+ }
120
+ interface RunnerConfig {
121
+ logger?: Logger;
122
+ version: number;
123
+ endpoint: string;
124
+ token?: string;
125
+ pegboardEndpoint?: string;
126
+ pegboardRelayEndpoint?: string;
127
+ namespace: string;
128
+ totalSlots: number;
129
+ runnerName: string;
130
+ runnerKey: string;
131
+ prepopulateActorNames: Record<string, {
132
+ metadata: Record<string, any>;
133
+ }>;
134
+ metadata?: Record<string, any>;
135
+ onConnected: () => void;
136
+ onDisconnected: (code: number, reason: string) => void;
137
+ onShutdown: () => void;
138
+ /** Called when receiving a network request. */
139
+ fetch: (runner: Runner, actorId: string, gatewayId: protocol.GatewayId, requestId: protocol.RequestId, request: Request) => Promise<Response>;
140
+ /**
141
+ * Called when receiving a WebSocket connection.
142
+ *
143
+ * All event listeners must be added synchronously inside this function or
144
+ * else events may be missed. The open event will fire immediately after
145
+ * this function finishes.
146
+ *
147
+ * Any errors thrown here will disconnect the WebSocket immediately.
148
+ *
149
+ * While `path` and `headers` are partially redundant to the data in the
150
+ * `Request`, they may vary slightly from the actual content of `Request`.
151
+ * Prefer to persist the `path` and `headers` properties instead of the
152
+ * `Request` itself.
153
+ *
154
+ * ## Hibernating Web Sockets
155
+ *
156
+ * ### Implementation Requirements
157
+ *
158
+ * **Requirement 1: Persist HWS Immediately**
159
+ *
160
+ * This is responsible for persisting hibernatable WebSockets immediately
161
+ * (do not wait for open event). It is not time sensitive to flush the
162
+ * connection state. If this fails to persist the HWS, the client's
163
+ * WebSocket will be disconnected on next wake in the call to
164
+ * `Tunnel::restoreHibernatingRequests` since the connection entry will not
165
+ * exist.
166
+ *
167
+ * **Requirement 2: Persist Message Index On `message`**
168
+ *
169
+ * In the `message` event listener, this handler must persist the message
170
+ * index from the event. The request ID is available at
171
+ * `event.rivetRequestId` and message index at `event.rivetMessageIndex`.
172
+ *
173
+ * The message index should not be flushed immediately. Instead, this
174
+ * should:
175
+ *
176
+ * - Debounce calls to persist the message index
177
+ * - After each persist, call
178
+ * `Runner::sendHibernatableWebSocketMessageAck` to acknowledge the
179
+ * message
180
+ *
181
+ * This mechanism allows us to buffer messages on the gateway so we can
182
+ * batch-persist events on our end on a given interval.
183
+ *
184
+ * If this fails to persist, then the gateway will replay unacked
185
+ * messages when the actor starts again.
186
+ *
187
+ * **Requirement 3: Remove HWS From Storage On `close`**
188
+ *
189
+ * This handler should add an event listener for `close` to remove the
190
+ * connection from storage.
191
+ *
192
+ * If the connection remove fails to persist, the close event will be
193
+ * called again on the next actor start in
194
+ * `Tunnel::restoreHibernatingRequests` since there will be no request for
195
+ * the given connection.
196
+ *
197
+ * ### Restoring Connections
198
+ *
199
+ * The user of this library is responsible for:
200
+ * 1. Loading all persisted hibernatable WebSocket metadata for an actor
201
+ * 2. Calling `Runner::restoreHibernatingRequests` with this metadata at
202
+ * the end of `onActorStart`
203
+ *
204
+ * `restoreHibernatingRequests` will restore all connections and attach
205
+ * the appropriate event listeners.
206
+ *
207
+ * ### No Open Event On Restoration
208
+ *
209
+ * When restoring a HWS, the open event will not be called again. It will
210
+ * go straight to the message or close event.
211
+ */
212
+ websocket: (runner: Runner, actorId: string, ws: any, gatewayId: protocol.GatewayId, requestId: protocol.RequestId, request: Request, path: string, headers: Record<string, string>, isHibernatable: boolean, isRestoringHibernatable: boolean) => Promise<void>;
213
+ hibernatableWebSocket: {
214
+ /**
215
+ * Determines if a WebSocket can continue to live while an actor goes to
216
+ * sleep.
217
+ */
218
+ canHibernate: (actorId: string, gatewayId: ArrayBuffer, requestId: ArrayBuffer, request: Request) => boolean;
219
+ };
220
+ /**
221
+ * Called when an actor starts.
222
+ *
223
+ * This callback is responsible for:
224
+ * 1. Initializing the actor instance
225
+ * 2. Loading all persisted hibernatable WebSocket metadata for this actor
226
+ * 3. Calling `Runner::restoreHibernatingRequests` with the loaded metadata
227
+ * to restore hibernatable WebSocket connections
228
+ *
229
+ * The actor should not be marked as "ready" until after
230
+ * `restoreHibernatingRequests` completes to ensure all hibernatable
231
+ * connections are fully restored before the actor processes new requests.
232
+ */
233
+ onActorStart: (actorId: string, generation: number, config: ActorConfig) => Promise<void>;
234
+ onActorStop: (actorId: string, generation: number) => Promise<void>;
235
+ noAutoShutdown?: boolean;
236
+ }
237
+ interface KvListOptions {
238
+ reverse?: boolean;
239
+ limit?: number;
240
+ }
241
+ declare class Runner {
242
+ #private;
243
+ get config(): RunnerConfig;
244
+ runnerId?: string;
245
+ get log(): Logger | undefined;
246
+ constructor(config: RunnerConfig);
247
+ sleepActor(actorId: string, generation?: number): void;
248
+ stopActor(actorId: string, generation?: number): Promise<void>;
249
+ forceStopActor(actorId: string, generation?: number): Promise<void>;
250
+ getActor(actorId: string, generation?: number): RunnerActor | undefined;
251
+ getAndWaitForActor(actorId: string, generation?: number): Promise<RunnerActor | undefined>;
252
+ hasActor(actorId: string, generation?: number): boolean;
253
+ get actors(): Map<string, RunnerActor>;
254
+ start(): Promise<void>;
255
+ shutdown(immediate: boolean, exit?: boolean): Promise<void>;
256
+ get pegboardEndpoint(): string;
257
+ get pegboardUrl(): string;
258
+ kvGet(actorId: string, keys: Uint8Array[]): Promise<(Uint8Array | null)[]>;
259
+ kvListAll(actorId: string, options?: KvListOptions): Promise<[Uint8Array, Uint8Array][]>;
260
+ kvListRange(actorId: string, start: Uint8Array, end: Uint8Array, exclusive?: boolean, options?: KvListOptions): Promise<[Uint8Array, Uint8Array][]>;
261
+ kvListPrefix(actorId: string, prefix: Uint8Array, options?: KvListOptions): Promise<[Uint8Array, Uint8Array][]>;
262
+ kvPut(actorId: string, entries: [Uint8Array, Uint8Array][]): Promise<void>;
263
+ kvDelete(actorId: string, keys: Uint8Array[]): Promise<void>;
264
+ kvDrop(actorId: string): Promise<void>;
265
+ setAlarm(actorId: string, alarmTs: number | null, generation?: number): void;
266
+ clearAlarm(actorId: string, generation?: number): void;
267
+ /** Asserts WebSocket exists and is ready. */
268
+ getPegboardWebSocketIfReady(): WebSocket | undefined;
269
+ __sendToServer(message: protocol.ToServer): void;
270
+ sendHibernatableWebSocketMessageAck(gatewayId: ArrayBuffer, requestId: ArrayBuffer, index: number): void;
271
+ /**
272
+ * Restores hibernatable WebSocket connections for an actor.
273
+ *
274
+ * This method should be called at the end of `onActorStart` after the
275
+ * actor instance is fully initialized.
276
+ *
277
+ * This method will:
278
+ * - Restore all provided hibernatable WebSocket connections
279
+ * - Attach event listeners to the restored WebSockets
280
+ * - Close any WebSocket connections that failed to restore
281
+ *
282
+ * The provided metadata list should include all hibernatable WebSockets
283
+ * that were persisted for this actor. The gateway will automatically
284
+ * close any connections that are not restored (i.e., not included in
285
+ * this list).
286
+ *
287
+ * **Important:** This method must be called after `onActorStart` completes
288
+ * and before marking the actor as "ready" to ensure all hibernatable
289
+ * connections are fully restored.
290
+ *
291
+ * @param actorId - The ID of the actor to restore connections for
292
+ * @param metaEntries - Array of hibernatable WebSocket metadata to restore
293
+ */
294
+ restoreHibernatingRequests(actorId: string, metaEntries: HibernatingWebSocketMetadata[]): Promise<void>;
295
+ getServerlessInitPacket(): string | undefined;
296
+ }
297
+
298
+ export { type ActorConfig, type HibernatingWebSocketMetadata, type KvListOptions, Runner, RunnerActor, type RunnerConfig, RunnerShutdownError, idToStr };