import type { WorkflowSpan } from "@/actor/config"; import { decodeBridgeRivetError, RivetError } from "@/actor/errors"; import type { ActorInvocationTraceContext } from "@/common/actor-telemetry-context"; import type { WasmRuntimeBindings, WasmRuntimeConfig, WasmRuntimeInitInput, } from "./config"; import type { ActorContextHandle, ActorFactoryHandle, ActorStateTransactionHandle, CancellationTokenHandle, ConnHandle, CoreRuntime, RegistryHandle, RuntimeActorConfig, RuntimeActorKeySegment, RuntimeApplicationListenerConfig, RuntimeBytes, RuntimeCronFire, RuntimeCronJobInfo, RuntimeForkLink, RuntimeHttpRequest, RuntimeInspectorSnapshot, RuntimeKvEntry, RuntimeKvListOptions, RuntimeListenerConfig, RuntimeOutboundCall, RuntimeQueueEnqueueAndWaitOptions, RuntimeQueueInspectMessage, RuntimeQueueMessage, RuntimeQueueNextBatchOptions, RuntimeQueueTryNextBatchOptions, RuntimeQueueWaitOptions, RuntimeRegistryRouteResponse, RuntimeRequestSaveOpts, RuntimeScheduledEventInfo, RuntimeServeConfig, RuntimeServerlessRequest, RuntimeServerlessResponseHead, RuntimeServerlessStreamCallback, RuntimeSqlBatchStatement, RuntimeSqlBindParams, RuntimeSqlDatabase, RuntimeSqlExecResult, RuntimeSqlExecuteResult, RuntimeSqlQueryResult, RuntimeSqlRunResult, RuntimeStateDeltaPayload, RuntimeWebSocketEvent, RuntimeWorkflowKvWrite, SqliteTransactionHandle, WebSocketHandle, } from "./runtime"; import { normalizeRuntimeSqlExecuteResult } from "./runtime"; type WasmBindings = WasmRuntimeBindings; export type WasmInitInput = WasmRuntimeInitInput; type AnyFunction = (...args: unknown[]) => unknown; type WasmRuntimeLoadConfig = Pick; type WasmActorContext = object; type WasmActorFactory = object; type WasmConnHandle = object; type WasmWebSocketHandle = object; interface WasmCancellationToken { aborted(): boolean; cancel(): void; onCancelled(callback: (...args: unknown[]) => unknown): { release(): void; }; } interface WasmCoreRegistry { register(name: string, factory: WasmActorFactory): void; serve(config: RuntimeServeConfig): Promise; shutdown(): Promise; } interface WasmConstructors { CoreRegistry: new () => WasmCoreRegistry; ActorFactory: new ( callbacks: object, config: RuntimeActorConfig | undefined | null, ) => WasmActorFactory; CancellationToken: new () => WasmCancellationToken; } function asWasmConstructors(bindings: WasmBindings): WasmConstructors { return bindings as unknown as WasmConstructors; } function asWasmRegistry(handle: RegistryHandle): WasmCoreRegistry { return handle as unknown as WasmCoreRegistry; } function asWasmFactory(handle: ActorFactoryHandle): WasmActorFactory { return handle as unknown as WasmActorFactory; } function asWasmActorContext(handle: ActorContextHandle): WasmActorContext { return handle as unknown as WasmActorContext; } function asWasmConn(handle: ConnHandle): WasmConnHandle { return handle as unknown as WasmConnHandle; } function asWasmWebSocket(handle: WebSocketHandle): WasmWebSocketHandle { return handle as unknown as WasmWebSocketHandle; } function asWasmCancellationToken( handle: CancellationTokenHandle, ): WasmCancellationToken { return handle as unknown as WasmCancellationToken; } function asRegistryHandle(handle: WasmCoreRegistry): RegistryHandle { return handle as unknown as RegistryHandle; } function asActorFactoryHandle(handle: WasmActorFactory): ActorFactoryHandle { return handle as unknown as ActorFactoryHandle; } function toBytes(value: RuntimeBytes | null | undefined): RuntimeBytes { return value ?? new Uint8Array(0); } function optionalBytes( value: RuntimeBytes | null | undefined, ): RuntimeBytes | null { if (value === null || value === undefined) { return null; } return toBytes(value); } function optionalWasmNumber( value: number | bigint | null | undefined, ): number | null | undefined { if (value === null || value === undefined) { return value; } return typeof value === "bigint" ? Number(value) : value; } function wasmNumber(value: number | bigint): number { return typeof value === "bigint" ? Number(value) : value; } function normalizeKvEntry(entry: RuntimeKvEntry): RuntimeKvEntry { return { key: toBytes(entry.key), value: toBytes(entry.value), }; } function normalizeQueueMessage( message: RuntimeQueueMessage, ): RuntimeQueueMessage { return { id: () => message.id(), name: () => message.name(), body: () => toBytes(message.body()), createdAt: () => message.createdAt(), isCompletable: () => message.isCompletable(), complete: async (response?: RuntimeBytes | undefined | null) => { await callWasm(() => message.complete(response)); }, }; } function normalizeWasmBridgeError(error: unknown): unknown { if (typeof error === "string") { return decodeBridgeRivetError(error) ?? error; } if (error instanceof Error) { const bridged = decodeBridgeRivetError(error.message); if (bridged) { return bridged; } } if ( typeof error === "object" && error !== null && "reason" in error && typeof error.reason === "string" ) { const bridged = decodeBridgeRivetError(error.reason); if (bridged) { return bridged; } } return error; } async function callWasm(invoke: () => Promise): Promise { try { return await invoke(); } catch (error) { throw normalizeWasmBridgeError(error); } } function callWasmSync(invoke: () => T): T { try { return invoke(); } catch (error) { throw normalizeWasmBridgeError(error); } } function unsupportedWasmMethod(method: string): never { throw new RivetError( "runtime", "unsupported", `Unsupported wasm runtime method: ${method}`, { metadata: { runtime: "wasm", method, }, }, ); } function method(target: unknown, name: string): T { if ( typeof target === "object" && target !== null && name in target && typeof target[name as keyof typeof target] === "function" ) { return target[name as keyof typeof target] as T; } return unsupportedWasmMethod(name); } function callHandle(handle: unknown, name: string, ...args: unknown[]): T { return callWasmSync(() => method(handle, name).apply(handle, args) as T); } async function callHandleAsync( handle: unknown, name: string, ...args: unknown[] ): Promise { return await callWasm( async () => (await method(handle, name).apply(handle, args)) as T, ); } function childHandle(handle: unknown, name: string): T { return callHandle(handle, name); } export class WasmCoreRuntime implements CoreRuntime { readonly kind = "wasm"; #constructors: WasmConstructors; #sql = new WeakMap(); constructor(bindings: WasmBindings) { this.#constructors = asWasmConstructors(bindings); } #actorSql(ctx: ActorContextHandle): RuntimeSqlDatabase { const wasmCtx = asWasmActorContext(ctx); let database = this.#sql.get(wasmCtx); if (!database) { database = callHandle(wasmCtx, "sql"); this.#sql.set(wasmCtx, database); } return database; } createRegistry(): RegistryHandle { return callWasmSync(() => asRegistryHandle(new this.#constructors.CoreRegistry()), ); } registerActor( registry: RegistryHandle, name: string, factory: ActorFactoryHandle, ): void { callWasmSync(() => asWasmRegistry(registry).register(name, asWasmFactory(factory)), ); } async serveRegistry( registry: RegistryHandle, config: RuntimeServeConfig, ): Promise { await callWasm(() => asWasmRegistry(registry).serve(config)); } async waitRegistryReady(): Promise { throw new Error( "registry.startAndWait() is not supported by the WASM runtime", ); } async shutdownRegistry(registry: RegistryHandle): Promise { await callWasm(() => asWasmRegistry(registry).shutdown()); } async registryHealth(): Promise { return { status: 200, headers: { "content-type": "application/json" }, body: new TextEncoder().encode( JSON.stringify({ status: "ok", runtime: "rivetkit", version: "wasm", }), ), }; } async handleServerlessRequest( registry: RegistryHandle, req: RuntimeServerlessRequest, onStreamEvent: RuntimeServerlessStreamCallback, cancelToken: CancellationTokenHandle, config: RuntimeServeConfig, ): Promise { return await callHandleAsync( asWasmRegistry(registry), "handleServerlessRequest", req, onStreamEvent, asWasmCancellationToken(cancelToken), config, ); } async serveListener( _registry: RegistryHandle, _listener: RuntimeListenerConfig, _config: RuntimeServeConfig, ): Promise { throw new Error( "registry.listen() is not supported on the wasm runtime; use registry.serve() and mount the handler in your platform's HTTP server instead", ); } async serveApplicationListener( _registry: RegistryHandle, _listener: RuntimeApplicationListenerConfig, _config: RuntimeServeConfig, ): Promise { throw new Error( "registry.listen() is not supported on the wasm runtime; use an application-owned HTTP server instead", ); } createActorFactory( callbacks: object, config?: RuntimeActorConfig | undefined | null, ): ActorFactoryHandle { return callWasmSync(() => asActorFactoryHandle( new this.#constructors.ActorFactory(callbacks, config), ), ); } createCancellationToken(): CancellationTokenHandle { return callWasmSync( () => new this.#constructors.CancellationToken() as unknown as CancellationTokenHandle, ); } cancellationTokenAborted(token: CancellationTokenHandle): boolean { return callWasmSync(() => asWasmCancellationToken(token).aborted()); } cancelCancellationToken(token: CancellationTokenHandle): void { callWasmSync(() => asWasmCancellationToken(token).cancel()); } onCancellationTokenCancelled( token: CancellationTokenHandle, callback: (...args: unknown[]) => unknown, ): () => void { const listener = callWasmSync(() => asWasmCancellationToken(token).onCancelled(callback), ); return () => callWasmSync(() => listener.release()); } actorState(ctx: ActorContextHandle): RuntimeBytes { return toBytes( callHandle( asWasmActorContext(ctx), "state", ), ); } actorBeginOnStateChange(ctx: ActorContextHandle): void { callHandle(asWasmActorContext(ctx), "beginOnStateChange"); } actorEndOnStateChange(ctx: ActorContextHandle): void { callHandle(asWasmActorContext(ctx), "endOnStateChange"); } actorSetAlarm( ctx: ActorContextHandle, timestampMs?: number | bigint | undefined | null, ): void { callHandle( asWasmActorContext(ctx), "setAlarm", optionalWasmNumber(timestampMs), ); } async actorSetRunWakeAt( ctx: ActorContextHandle, timestampMs?: number | undefined | null, ): Promise { await callHandleAsync( asWasmActorContext(ctx), "setRunWakeAt", optionalWasmNumber(timestampMs), ); } actorRequestSave( ctx: ActorContextHandle, opts?: RuntimeRequestSaveOpts | undefined | null, ): void { callHandle(asWasmActorContext(ctx), "requestSave", opts); } async actorRequestSaveAndWait( ctx: ActorContextHandle, opts?: RuntimeRequestSaveOpts | undefined | null, ): Promise { await callHandleAsync( asWasmActorContext(ctx), "requestSaveAndWait", opts, ); } actorInspectorSnapshot(ctx: ActorContextHandle): RuntimeInspectorSnapshot { return callHandle(asWasmActorContext(ctx), "inspectorSnapshot"); } actorDecodeInspectorRequest( ctx: ActorContextHandle, bytes: RuntimeBytes, advertisedVersion: number, ): RuntimeBytes { return toBytes( callHandle( asWasmActorContext(ctx), "decodeInspectorRequest", bytes, advertisedVersion, ), ); } actorEncodeInspectorResponse( ctx: ActorContextHandle, bytes: RuntimeBytes, targetVersion: number, ): RuntimeBytes { return toBytes( callHandle( asWasmActorContext(ctx), "encodeInspectorResponse", bytes, targetVersion, ), ); } async actorVerifyInspectorAuth( ctx: ActorContextHandle, bearerToken?: string | undefined | null, ): Promise { await callHandleAsync( asWasmActorContext(ctx), "verifyInspectorAuth", bearerToken, ); } actorQueueHibernationRemoval( ctx: ActorContextHandle, connId: string, ): void { callHandle(asWasmActorContext(ctx), "queueHibernationRemoval", connId); } actorTakePendingHibernationChanges(ctx: ActorContextHandle): string[] { return callHandle( asWasmActorContext(ctx), "takePendingHibernationChanges", ); } actorDirtyHibernatableConns(ctx: ActorContextHandle): ConnHandle[] { return callHandle(asWasmActorContext(ctx), "dirtyHibernatableConns"); } async actorSaveState( ctx: ActorContextHandle, payload: RuntimeStateDeltaPayload, ): Promise { await callHandleAsync(asWasmActorContext(ctx), "saveState", payload); } async actorSaveStateAndWorkflowBatch( ctx: ActorContextHandle, writes: RuntimeWorkflowKvWrite[], ): Promise { await callHandleAsync( asWasmActorContext(ctx), "saveStateAndWorkflowBatch", writes, ); } actorId(ctx: ActorContextHandle): string { return callHandle(asWasmActorContext(ctx), "actorId"); } runWithActorInvocationContext( _ctx: ActorContextHandle, run: () => T, ): T { return run(); } actorInvocationTraceContext( _ctx: ActorContextHandle, ): ActorInvocationTraceContext | undefined { return undefined; } startCallSpan( _ctx: ActorContextHandle, _actorName: string, _actionName: string, ): RuntimeOutboundCall | undefined { return undefined; } async startWorkflowSpan(_ctx: ActorContextHandle): Promise { return { run: (body) => body(), startStep: () => undefined, finish: async () => {}, }; } runOutsideActorInvocationContext(run: () => T): T { return run(); } currentInvocationScope(): object | undefined { return undefined; } actorName(ctx: ActorContextHandle): string { return callHandle(asWasmActorContext(ctx), "name"); } actorKey(ctx: ActorContextHandle): RuntimeActorKeySegment[] { return callHandle(asWasmActorContext(ctx), "key"); } actorForkChain(ctx: ActorContextHandle): RuntimeForkLink[] { return callHandle(asWasmActorContext(ctx), "forkChain"); } actorRegion(ctx: ActorContextHandle): string { return callHandle(asWasmActorContext(ctx), "region"); } actorNamespace(ctx: ActorContextHandle): string { return callHandle(asWasmActorContext(ctx), "namespace"); } actorSleep(ctx: ActorContextHandle): void { callHandle(asWasmActorContext(ctx), "sleep"); } actorDestroy(ctx: ActorContextHandle): void { callHandle(asWasmActorContext(ctx), "destroy"); } actorAbortSignal(ctx: ActorContextHandle): AbortSignal { return callHandle(asWasmActorContext(ctx), "abortSignal"); } actorConns(ctx: ActorContextHandle): ConnHandle[] { return callHandle(asWasmActorContext(ctx), "conns"); } async actorConnectConn( ctx: ActorContextHandle, params: RuntimeBytes, request?: RuntimeHttpRequest | undefined | null, ): Promise { return await callHandleAsync( asWasmActorContext(ctx), "connectConn", params, request, ); } actorBroadcast( ctx: ActorContextHandle, name: string, args: RuntimeBytes, ): void { callHandle(asWasmActorContext(ctx), "broadcast", name, args); } actorWaitUntil(ctx: ActorContextHandle, promise: Promise): void { callHandle(asWasmActorContext(ctx), "waitUntil", promise); } async actorWaitForTrackedShutdownWork( ctx: ActorContextHandle, ): Promise { return await callHandle>( asWasmActorContext(ctx), "waitForTrackedShutdownWork", ); } async actorWaitForTrackedShutdownWorkUnbounded( ctx: ActorContextHandle, ): Promise { await callHandle>( asWasmActorContext(ctx), "waitForTrackedShutdownWorkUnbounded", ); } actorKeepAwake(ctx: ActorContextHandle, promise: Promise): void { const wasmCtx = asWasmActorContext(ctx); const regionId = callHandle(wasmCtx, "beginKeepAwake"); const trackedPromise = Promise.resolve(promise) .finally(() => { callHandle(wasmCtx, "endKeepAwake", regionId); }) .then(() => null); callHandle(wasmCtx, "registerTask", trackedPromise); } actorBeginKeepAwake(ctx: ActorContextHandle): number { return callHandle(asWasmActorContext(ctx), "beginKeepAwake"); } actorEndKeepAwake(ctx: ActorContextHandle, regionId: number): void { callHandle(asWasmActorContext(ctx), "endKeepAwake", regionId); } actorRegisterTask( ctx: ActorContextHandle, promise: Promise, ): void { callHandle(asWasmActorContext(ctx), "registerTask", promise); } actorRuntimeState(ctx: ActorContextHandle): object { return callHandle(asWasmActorContext(ctx), "runtimeState"); } actorClearRuntimeState(ctx: ActorContextHandle): void { const runtimeState = this.actorRuntimeState(ctx); for (const key of Object.keys(runtimeState)) { delete (runtimeState as Record)[key]; } } actorRestartRunHandler(ctx: ActorContextHandle): void { callHandle(asWasmActorContext(ctx), "restartRunHandler"); } actorBeginWebsocketCallback(ctx: ActorContextHandle): number { return callHandle(asWasmActorContext(ctx), "beginWebsocketCallback"); } actorEndWebsocketCallback(ctx: ActorContextHandle, regionId: number): void { callHandle(asWasmActorContext(ctx), "endWebsocketCallback", regionId); } async actorKvGet( ctx: ActorContextHandle, key: RuntimeBytes, ): Promise { const kv = childHandle(asWasmActorContext(ctx), "kv"); return optionalBytes(await callHandleAsync(kv, "get", key)); } async actorKvPut( ctx: ActorContextHandle, key: RuntimeBytes, value: RuntimeBytes, ): Promise { const kv = childHandle(asWasmActorContext(ctx), "kv"); await callHandleAsync(kv, "put", key, value); } async actorKvDelete( ctx: ActorContextHandle, key: RuntimeBytes, ): Promise { const kv = childHandle(asWasmActorContext(ctx), "kv"); await callHandleAsync(kv, "delete", key); } async actorKvDeleteRange( ctx: ActorContextHandle, start: RuntimeBytes, end: RuntimeBytes, ): Promise { const kv = childHandle(asWasmActorContext(ctx), "kv"); await callHandleAsync(kv, "deleteRange", start, end); } async actorKvListPrefix( ctx: ActorContextHandle, prefix: RuntimeBytes, options?: RuntimeKvListOptions | undefined | null, ): Promise { const kv = childHandle(asWasmActorContext(ctx), "kv"); const entries = await callHandleAsync( kv, "listPrefix", prefix, options, ); return entries.map(normalizeKvEntry); } async actorKvListRange( ctx: ActorContextHandle, start: RuntimeBytes, end: RuntimeBytes, options?: RuntimeKvListOptions | undefined | null, ): Promise { const kv = childHandle(asWasmActorContext(ctx), "kv"); const entries = await callHandleAsync( kv, "listRange", start, end, options, ); return entries.map(normalizeKvEntry); } async actorKvBatchGet( ctx: ActorContextHandle, keys: RuntimeBytes[], ): Promise> { const kv = childHandle(asWasmActorContext(ctx), "kv"); const values = await callHandleAsync< Array >(kv, "batchGet", keys); return values.map((value) => value === undefined ? undefined : optionalBytes(value), ); } async actorKvBatchPut( ctx: ActorContextHandle, entries: RuntimeKvEntry[], ): Promise { const kv = childHandle(asWasmActorContext(ctx), "kv"); await callHandleAsync(kv, "batchPut", entries); } async actorKvBatchDelete( ctx: ActorContextHandle, keys: RuntimeBytes[], ): Promise { const kv = childHandle(asWasmActorContext(ctx), "kv"); await callHandleAsync(kv, "batchDelete", keys); } async actorSqlExec( ctx: ActorContextHandle, sql: string, ): Promise { return await callWasm(() => this.#actorSql(ctx).exec(sql)); } async actorSqlExecute( ctx: ActorContextHandle, sql: string, params?: RuntimeSqlBindParams, ): Promise { const result = await callWasm(() => this.#actorSql(ctx).execute(sql, params), ); return normalizeRuntimeSqlExecuteResult(result); } async actorSqlExecuteBatch( ctx: ActorContextHandle, statements: RuntimeSqlBatchStatement[], ): Promise { const results = await callWasm(() => this.#actorSql(ctx).executeBatch(statements), ); return results.map(normalizeRuntimeSqlExecuteResult); } async actorSqlBeginTransaction( ctx: ActorContextHandle, timeoutMs?: number, name?: string, ): Promise { return (await callWasm(() => this.#actorSql(ctx).beginTransaction(timeoutMs, name), )) as unknown as SqliteTransactionHandle; } async actorSqlTransactionExec( transaction: SqliteTransactionHandle, sql: string, ): Promise { return await callWasm(() => ( transaction as unknown as { exec(sql: string): Promise; } ).exec(sql), ); } async actorSqlTransactionExecute( transaction: SqliteTransactionHandle, sql: string, params?: RuntimeSqlBindParams, ): Promise { const result = await callWasm(() => ( transaction as unknown as { execute( sql: string, params?: RuntimeSqlBindParams, ): Promise; } ).execute(sql, params), ); return normalizeRuntimeSqlExecuteResult(result); } async actorSqlTransactionCommit( transaction: SqliteTransactionHandle, ): Promise { await callWasm(() => (transaction as unknown as { commit(): Promise }).commit(), ); } async actorSqlTransactionRollback( transaction: SqliteTransactionHandle, ): Promise { await callWasm(() => ( transaction as unknown as { rollback(): Promise } ).rollback(), ); } async actorBeginStateTransaction( ctx: ActorContextHandle, timeoutMs?: number, ): Promise { return (await callWasm(() => ( asWasmActorContext(ctx) as unknown as { beginStateTransaction( timeoutMs?: number, ): Promise; } ).beginStateTransaction(timeoutMs), )) as ActorStateTransactionHandle; } async actorStateTransactionExecute( transaction: ActorStateTransactionHandle, sql: string, params?: RuntimeSqlBindParams, ): Promise { const result = await callWasm(() => ( transaction as unknown as { execute( sql: string, params?: RuntimeSqlBindParams, ): Promise; } ).execute(sql, params), ); return normalizeRuntimeSqlExecuteResult(result); } async actorStateTransactionCommit( transaction: ActorStateTransactionHandle, payload: RuntimeStateDeltaPayload, ): Promise { await callWasm(() => ( transaction as unknown as { commit(payload: RuntimeStateDeltaPayload): Promise; } ).commit(payload), ); } async actorStateTransactionRollback( transaction: ActorStateTransactionHandle, ): Promise { await callWasm(() => ( transaction as unknown as { rollback(): Promise } ).rollback(), ); } async actorSqlQuery( ctx: ActorContextHandle, sql: string, params?: RuntimeSqlBindParams, ): Promise { return await callWasm(() => this.#actorSql(ctx).query(sql, params)); } async actorSqlRun( ctx: ActorContextHandle, sql: string, params?: RuntimeSqlBindParams, ): Promise { return await callWasm(() => this.#actorSql(ctx).run(sql, params)); } actorSqlMetrics(ctx: ActorContextHandle) { return this.#actorSql(ctx).metrics?.() ?? null; } actorSqlTakeLastKvError(ctx: ActorContextHandle): string | null { return this.#actorSql(ctx).takeLastKvError?.() ?? null; } async actorSqlClose(ctx: ActorContextHandle): Promise { const wasmCtx = asWasmActorContext(ctx); const database = this.#sql.get(wasmCtx); if (!database) { return; } this.#sql.delete(wasmCtx); await callWasm(() => database.close()); } async actorQueueSend( ctx: ActorContextHandle, name: string, body: RuntimeBytes, ): Promise { const queue = childHandle(asWasmActorContext(ctx), "queue"); return normalizeQueueMessage( await callHandleAsync(queue, "send", name, body), ); } async actorQueueNextBatch( ctx: ActorContextHandle, options?: RuntimeQueueNextBatchOptions | undefined | null, signal?: CancellationTokenHandle | undefined | null, ): Promise { const queue = childHandle(asWasmActorContext(ctx), "queue"); const messages = await callHandleAsync( queue, "nextBatch", options, signal ? asWasmCancellationToken(signal) : signal, ); return messages.map(normalizeQueueMessage); } async actorQueueWaitForNames( ctx: ActorContextHandle, names: string[], options?: RuntimeQueueWaitOptions | undefined | null, signal?: CancellationTokenHandle | undefined | null, ): Promise { const queue = childHandle(asWasmActorContext(ctx), "queue"); return normalizeQueueMessage( await callHandleAsync( queue, "waitForNames", names, options, signal ? asWasmCancellationToken(signal) : signal, ), ); } async actorQueueWaitForNamesAvailable( ctx: ActorContextHandle, names: string[], options?: RuntimeQueueWaitOptions | undefined | null, signal?: CancellationTokenHandle | undefined | null, ): Promise { const queue = childHandle(asWasmActorContext(ctx), "queue"); await callHandleAsync( queue, "waitForNamesAvailable", names, options, signal, ); } async actorQueueCompletePersisted( ctx: ActorContextHandle, messageId: bigint, expectedName: string, response?: RuntimeBytes | undefined | null, ): Promise { const queue = childHandle(asWasmActorContext(ctx), "queue"); return await callHandleAsync( queue, "completePersisted", messageId, expectedName, response, ); } async actorQueueEnqueueAndWait( ctx: ActorContextHandle, name: string, body: RuntimeBytes, options?: RuntimeQueueEnqueueAndWaitOptions | undefined | null, signal?: CancellationTokenHandle | undefined | null, ): Promise { const queue = childHandle(asWasmActorContext(ctx), "queue"); return optionalBytes( await callHandleAsync( queue, "enqueueAndWait", name, body, options, signal ? asWasmCancellationToken(signal) : signal, ), ); } actorQueueTryNextBatch( ctx: ActorContextHandle, options?: RuntimeQueueTryNextBatchOptions | undefined | null, ): RuntimeQueueMessage[] { const queue = childHandle(asWasmActorContext(ctx), "queue"); return callHandle( queue, "tryNextBatch", options, ).map(normalizeQueueMessage); } actorQueueMaxSize(ctx: ActorContextHandle): number { const queue = childHandle(asWasmActorContext(ctx), "queue"); return callHandle(queue, "maxSize"); } async actorQueueInspectMessages( ctx: ActorContextHandle, ): Promise { const queue = childHandle(asWasmActorContext(ctx), "queue"); return await callHandleAsync(queue, "inspectMessages"); } async actorQueueReset(ctx: ActorContextHandle): Promise { const queue = childHandle(asWasmActorContext(ctx), "queue"); await callHandleAsync(queue, "reset"); } async actorScheduleAfter( ctx: ActorContextHandle, durationMs: number | bigint, actionName: string, args: RuntimeBytes, ): Promise { const schedule = childHandle(asWasmActorContext(ctx), "schedule"); return await callHandleAsync( schedule, "after", wasmNumber(durationMs), actionName, args, ); } async actorScheduleAt( ctx: ActorContextHandle, timestampMs: number | bigint, actionName: string, args: RuntimeBytes, ): Promise { const schedule = childHandle(asWasmActorContext(ctx), "schedule"); return await callHandleAsync( schedule, "at", wasmNumber(timestampMs), actionName, args, ); } async actorScheduleCancel(ctx: ActorContextHandle, id: string) { const schedule = childHandle(asWasmActorContext(ctx), "schedule"); return await callHandleAsync(schedule, "cancel", id); } async actorScheduleGet(ctx: ActorContextHandle, id: string) { const schedule = childHandle(asWasmActorContext(ctx), "schedule"); return await callHandleAsync( schedule, "get", id, ); } async actorScheduleList(ctx: ActorContextHandle) { const schedule = childHandle(asWasmActorContext(ctx), "schedule"); return await callHandleAsync( schedule, "list", ); } async actorCronSet( ctx: ActorContextHandle, name: string, expression: string, timezone: string | undefined, actionName: string, args: RuntimeBytes, maxHistory: number | undefined, ) { const schedule = childHandle(asWasmActorContext(ctx), "schedule"); await callHandleAsync( schedule, "cronSet", name, expression, timezone, actionName, args, maxHistory, ); } async actorCronEvery( ctx: ActorContextHandle, name: string, intervalMs: number, actionName: string, args: RuntimeBytes, maxHistory: number | undefined, ) { const schedule = childHandle(asWasmActorContext(ctx), "schedule"); await callHandleAsync( schedule, "cronEvery", name, intervalMs, actionName, args, maxHistory, ); } async actorCronGet(ctx: ActorContextHandle, name: string) { const schedule = childHandle(asWasmActorContext(ctx), "schedule"); return await callHandleAsync( schedule, "cronGet", name, ); } async actorCronList(ctx: ActorContextHandle) { const schedule = childHandle(asWasmActorContext(ctx), "schedule"); return await callHandleAsync( schedule, "cronList", ); } async actorCronDelete(ctx: ActorContextHandle, name: string) { const schedule = childHandle(asWasmActorContext(ctx), "schedule"); return await callHandleAsync(schedule, "cronDelete", name); } async actorCronHistory( ctx: ActorContextHandle, name: string, limit: number | undefined, ) { const schedule = childHandle(asWasmActorContext(ctx), "schedule"); return await callHandleAsync( schedule, "cronHistory", name, limit, ); } connId(conn: ConnHandle): string { return callHandle(asWasmConn(conn), "id"); } connParams(conn: ConnHandle): RuntimeBytes { return toBytes(callHandle(asWasmConn(conn), "params")); } connState(conn: ConnHandle): RuntimeBytes { return toBytes(callHandle(asWasmConn(conn), "state")); } connSetState(conn: ConnHandle, state: RuntimeBytes): void { callHandle(asWasmConn(conn), "setState", state); } connIsHibernatable(conn: ConnHandle): boolean { return callHandle(asWasmConn(conn), "isHibernatable"); } connSend(conn: ConnHandle, name: string, args: RuntimeBytes): void { callHandle(asWasmConn(conn), "send", name, args); } async connDisconnect( conn: ConnHandle, reason?: string | undefined | null, ): Promise { await callHandleAsync(asWasmConn(conn), "disconnect", reason); } webSocketSend( ws: WebSocketHandle, data: RuntimeBytes, binary: boolean, ): void { callHandle(asWasmWebSocket(ws), "send", data, binary); } async webSocketClose( ws: WebSocketHandle, code?: number | undefined | null, reason?: string | undefined | null, ): Promise { await callHandleAsync(asWasmWebSocket(ws), "close", code, reason); } webSocketSetEventCallback( ws: WebSocketHandle, callback: (event: RuntimeWebSocketEvent) => void, ): void { callHandle( asWasmWebSocket(ws), "setEventCallback", (event: RuntimeWebSocketEvent) => { if (event.kind === "message" && event.binary) { callback({ ...event, data: toBytes(event.data as RuntimeBytes | Uint8Array), }); return; } callback(event); }, ); } } export type { WasmBindings }; export async function loadWasmRuntime(config?: WasmRuntimeLoadConfig): Promise<{ bindings: WasmBindings; runtime: WasmCoreRuntime; }> { const bindings = config?.bindings ?? (await import(["@rivetkit", "rivetkit-wasm"].join("/"))); await bindings.default(config?.initInput); return { bindings, runtime: new WasmCoreRuntime(bindings), }; }