import { accessorSlot } from '../lib/accessor_path.ts'; import { ConnectionId, ProductBuilder, ProductType } from '../index.ts'; import { AlgebraicType, type ComparablePrimitive } from '../index.ts'; import BinaryReader from '../lib/binary_reader.ts'; import BinaryWriter from '../lib/binary_writer.ts'; import { BsatnRowList, ClientMessage, QueryRows, QuerySetUpdate, ServerMessage, TableUpdateRows, UnsubscribeFlags, type SubscribeBatchApplied, type SubscribeBatch, } from './client_api/types.ts'; import { ClientCache } from './client_cache.ts'; import { DbConnectionBuilder } from './db_connection_builder.ts'; import { INTERNAL_REMOTE_MODULE } from './internal.ts'; import { type DbContext } from './db_context.ts'; import type { Event } from './event.ts'; import { type ErrorContextInterface, type EventContextInterface, type ReducerEventContextInterface, type SubscriptionEventContextInterface, } from './event_context.ts'; import { EventEmitter } from './event_emitter.ts'; import type { Deserializer, Identity, InferTypeOfParams, Serializer, } from '../index.ts'; import type { ProcedureResultMessage, ReducerResultMessage, } from './message_types.ts'; import type { ReducerEvent } from './reducer_event.ts'; import { type UntypedRemoteModule } from './spacetime_module.ts'; import { makeFromBuilder, type NamespacedQueryBuilder } from '../lib/query.ts'; import { type TableCache, type Operation, type PendingCallback, type TableUpdate as CacheTableUpdate, } from './table_cache.ts'; import { SubscriptionBuilderImpl, SubscriptionHandleImpl, SubscriptionManager, type SubscribeEvent, } from './subscription_builder_impl.ts'; import { stdbLogger, stringify } from './logger.ts'; import { fromByteArray } from 'base64-js'; import type { ReducerEventInfo, ReducersView, SubscriptionEventCallback, } from './reducers.ts'; import type { ClientDbView } from './db_view.ts'; import type { RowType, UntypedTableDef } from '../lib/table.ts'; import type { UntypedSchemaDef } from '../lib/schema.ts'; import type { ProceduresView } from './procedures.ts'; import type { Values } from '../lib/type_util.ts'; import type { TransactionUpdate } from './client_api/types.ts'; import type { SubscriptionEntry } from './subscription_builder_impl.ts'; import { DisconnectedError, IdentityChangedError, InternalError, SenderError, UnknownCallResultError, } from '../lib/errors.ts'; import { WebSocketTokenError, type WebSocketAdapter, type WebSocketFactory, } from './ws.ts'; import { normalizeWsProtocol, PREFERRED_WS_PROTOCOLS, V2_WS_PROTOCOL, V3_WS_PROTOCOL, type NegotiatedWsProtocol, } from './websocket_protocols.ts'; import { countClientMessagesForV3Frame, encodeClientMessagesV3, forEachServerMessageV3, } from './websocket_v3_frames.ts'; export { DbConnectionBuilder, SubscriptionBuilderImpl, SubscriptionHandleImpl, type TableCache, type Event, }; export type RemoteModuleOf = C extends DbConnectionImpl ? RM : never; export type { DbContext, EventContextInterface, ReducerEventContextInterface, SubscriptionEventContextInterface, ErrorContextInterface, ReducerEvent, }; export type ConnectionEventArgs = { connect: [identity: Identity, token: string]; automaticReconnect: [identity: Identity, token: string]; disconnect: [ error?: Error, nextReconnectAttempt?: number, nextReconnectDelayMs?: number, ]; connectError: [ error: Error, nextReconnectAttempt?: number, nextReconnectDelayMs?: number, ]; }; export type ConnectionEvent = keyof ConnectionEventArgs; export type DbConnectionConfig = { uri: URL; nameOrAddress: string; identity?: Identity; token?: string; emitter: EventEmitter; createWSFn: WebSocketFactory; compression: 'gzip' | 'brotli' | 'none'; lightMode: boolean; confirmedReads?: boolean; remoteModule: RemoteModule; /** * Whether the connection reconnects on its own after losing its socket. * Set by {@link DbConnectionBuilder.withAutomaticReconnect}. */ automaticReconnect?: boolean; /** * Supplies a fresh token for a reconnect attempt. * Set by {@link DbConnectionBuilder.withTokenProvider}. */ tokenProvider?: TokenProvider; /** * Backoff bounds for reconnect attempts. * Set by {@link DbConnectionBuilder.withAutomaticReconnect}. */ reconnectPolicy?: ReconnectPolicy; }; /** * Supplies an authentication token, called before a reconnect attempt whose * retained token is close to expiring. */ export type TokenProvider = () => Promise; /** The default delay before the first reconnect attempt. */ export const RECONNECT_INITIAL_DELAY_MS = 1_000; /** The default upper bound on the delay between reconnect attempts. */ export const RECONNECT_MAX_DELAY_MS = 30_000; /** The random spread applied to each reconnect delay. */ export const RECONNECT_JITTER = 0.5; /** The lowest `minDelayMs` accepted; smaller values are raised to this. */ export const RECONNECT_MIN_DELAY_FLOOR_MS = 500; /** The lowest `maxDelayMs` accepted; smaller values are raised to this. */ export const RECONNECT_MAX_DELAY_FLOOR_MS = 1_000; /** Options for {@link DbConnectionBuilder.withAutomaticReconnect}. */ export type AutomaticReconnectOptions = { /** * The delay before the first reconnect attempt, and the floor for every * later one. Defaults to 1000 ms; values below 500 ms are raised to 500 ms. */ minDelayMs?: number; /** * The cap on the delay between reconnect attempts. Defaults to 30000 ms; * values below 1000 ms (or below `minDelayMs`) are raised to that bound. */ maxDelayMs?: number; }; export type ReconnectPolicy = Required; export const DEFAULT_RECONNECT_POLICY: ReconnectPolicy = { minDelayMs: RECONNECT_INITIAL_DELAY_MS, maxDelayMs: RECONNECT_MAX_DELAY_MS, }; /** Fill in defaults and enforce the floors, warning when a value is raised. */ export function resolveReconnectPolicy( options: AutomaticReconnectOptions = {} ): ReconnectPolicy { let { minDelayMs = RECONNECT_INITIAL_DELAY_MS, maxDelayMs = RECONNECT_MAX_DELAY_MS, } = options; // Floors protect the database from clients that retry too aggressively. if (!(minDelayMs >= RECONNECT_MIN_DELAY_FLOOR_MS)) { stdbLogger( 'warn', `Reconnect minDelayMs ${minDelayMs} is below the ${RECONNECT_MIN_DELAY_FLOOR_MS} ms floor; using ${RECONNECT_MIN_DELAY_FLOOR_MS} ms.` ); minDelayMs = RECONNECT_MIN_DELAY_FLOOR_MS; } const maxFloor = Math.max(RECONNECT_MAX_DELAY_FLOOR_MS, minDelayMs); if (!(maxDelayMs >= maxFloor)) { stdbLogger( 'warn', `Reconnect maxDelayMs ${maxDelayMs} is below the ${maxFloor} ms floor; using ${maxFloor} ms.` ); maxDelayMs = maxFloor; } return { minDelayMs, maxDelayMs }; } /** * A token is refreshed when its remaining validity falls below this fraction * of its lifetime, or below {@link TOKEN_REFRESH_MIN_MARGIN_MS}, whichever is * larger. */ const TOKEN_REFRESH_MARGIN_FRACTION = 0.05; const TOKEN_REFRESH_MIN_MARGIN_MS = 30_000; /** Exponential backoff with jitter; attempt numbers start at one. */ export function computeReconnectDelayMs( attempt: number, random: () => number = Math.random, { minDelayMs, maxDelayMs }: ReconnectPolicy = DEFAULT_RECONNECT_POLICY ): number { const base = Math.min( minDelayMs * Math.pow(2, Math.max(0, attempt - 1)), maxDelayMs ); const jittered = base * (1 + RECONNECT_JITTER * (2 * random() - 1)); return Math.max(minDelayMs, Math.min(jittered, maxDelayMs)); } /** Refresh unreadable tokens, or tokens within 5% of expiry (at least 30 seconds). */ export function tokenNeedsRefresh( token: string | undefined, nowMs: number = Date.now() ): boolean { if (!token) { return true; } const claims = decodeJwtClaims(token); if (claims === undefined || claims.exp === undefined) { return true; } const expiryMs = claims.exp * 1000; const lifetimeMs = claims.iat !== undefined ? expiryMs - claims.iat * 1000 : undefined; const margin = Math.max( TOKEN_REFRESH_MIN_MARGIN_MS, lifetimeMs !== undefined ? lifetimeMs * TOKEN_REFRESH_MARGIN_FRACTION : 0 ); return expiryMs - nowMs <= margin; } /** Normalize an unknown thrown value or error event into an `Error`. */ function errorFromEvent(value: unknown, fallbackMessage: string): Error { if (value instanceof Error) { return value; } if (typeof value === 'object' && value !== null) { const message = 'message' in value ? value.message : undefined; const error = 'error' in value ? value.error : undefined; if (error instanceof Error) { return error; } if (typeof message === 'string' && message.length > 0) { return new Error(message, { cause: value }); } } return new Error(fallbackMessage, { cause: value }); } /** * Whether a failure to connect is one that retrying cannot fix, so that the * SDK stops rather than looping. */ function isTerminalConnectError(error: Error): boolean { return ( error instanceof IdentityChangedError || error instanceof WebSocketProtocolError ); } /** Whether a failure looks like the server rejecting our credentials. */ function isAuthError(error: Error): boolean { return ( error instanceof WebSocketTokenError && (error.status === 401 || error.status === 403) ); } class WebSocketProtocolError extends Error {} const SESSION_BUSY_CLOSE_CODE = 4000; type JwtClaims = { exp?: number; iat?: number }; function decodeJwtClaims(token: string): JwtClaims | undefined { const parts = token.split('.'); if (parts.length < 2) { return undefined; } try { const payload = parts[1].replace(/-/g, '+').replace(/_/g, '/'); const padded = payload.padEnd( payload.length + ((4 - (payload.length % 4)) % 4), '=' ); const json = typeof atob === 'function' ? atob(padded) : Buffer.from(padded, 'base64').toString('binary'); const claims: unknown = JSON.parse(json); if (typeof claims !== 'object' || claims === null) { return undefined; } const exp = 'exp' in claims ? claims.exp : undefined; const iat = 'iat' in claims ? claims.iat : undefined; return { exp: typeof exp === 'number' && Number.isFinite(exp) ? exp : undefined, iat: typeof iat === 'number' && Number.isFinite(iat) ? iat : undefined, }; } catch { return undefined; } } type ProcedureCallback = (result: ProcedureResultMessage['result']) => void; type Deferred = { promise: Promise; resolve: (value: T | PromiseLike) => void; reject: (reason: Error | string) => void; }; const TEXT_ENCODER = new TextEncoder(); function createDeferred(): Deferred { let resolve!: Deferred['resolve']; let reject!: Deferred['reject']; const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); return { promise, resolve, reject }; } function getClientMessageVariantTag(name: string): number { if (ClientMessage.algebraicType.tag !== 'Sum') { throw new TypeError('ClientMessage must be a sum type'); } const tag = ClientMessage.algebraicType.value.variants.findIndex( variant => variant.name === name ); if (tag === -1) { throw new RangeError(`Unknown ClientMessage variant: ${name}`); } return tag; } const CLIENT_MESSAGE_CALL_REDUCER_TAG = getClientMessageVariantTag('CallReducer'); const CLIENT_MESSAGE_CALL_PROCEDURE_TAG = getClientMessageVariantTag('CallProcedure'); // Keep individual v3 frames bounded so one burst does not monopolize the send // path or create very large websocket writes. const MAX_V3_OUTBOUND_FRAME_BYTES = 256 * 1024; // WebSocket `readyState` values from the WHATWG spec. Uses literals rather than // the `WebSocket` global, which is not defined on earlier Node versions we const WS_READY_STATE_CLOSING = 2; const WS_READY_STATE_CLOSED = 3; export class DbConnectionImpl implements DbContext { /** * Whether or not the connection is active. */ isActive = false; /** * Whether `disconnect()` has been called on this connection. * Once requested, the connection will not be reused: managed environments * (such as the React `SpacetimeDBProvider`) use this to avoid reconnecting * after an intentional disconnect. */ isDisconnectRequested = false; /** * The websocket error that ended an established connection, if any, * normalized to `Error`. Passed to the `disconnect` emit so `onDisconnect` * callbacks receive the documented `error?: Error` shape. */ #connectionError?: Error = undefined; /** * Whether the underlying websocket has entered `CLOSING` (2) or `CLOSED` * (3). This becomes true even when the browser never delivered an * `onclose` event, for example if the socket was torn down while the tab was * frozen or the machine was asleep. The liveness listeners (see * {@link DbConnectionImpl.#installLivenessListeners}) use this to detect * such "zombie" sockets when the page resumes and to force a reconnect. * * Returns false while the socket is still `CONNECTING`/`OPEN`, or before * the socket has been created. */ get isSocketClosed(): boolean { const ws = this.ws; if (!ws) { return false; } return ( ws.readyState === WS_READY_STATE_CLOSING || ws.readyState === WS_READY_STATE_CLOSED ); } /** * This connection's public identity. */ identity?: Identity = undefined; /** * This connection's private authentication token. */ token?: string = undefined; /** @internal */ [INTERNAL_REMOTE_MODULE](): RemoteModule { return this.#remoteModule; } /** * The accessor field to access the tables in the database and associated * callback functions. */ db: ClientDbView; /** * The accessor field to access the reducers in the database. */ reducers: ReducersView; /** * The accessor field to access the procedures in the database. */ procedures: ProceduresView; /** * The `ConnectionId` of the connection to to the database. */ connectionId: ConnectionId = ConnectionId.random(); #connectionIdHex = this.connectionId.toHexString(); // Stable across sockets; each attempt still gets a fresh ConnectionId. #sessionIdHex = ConnectionId.random().toHexString(); #automaticReconnect: boolean; #reconnectPolicy: ReconnectPolicy; #tokenProvider?: TokenProvider; #wsBaseUrl: URL; #nameOrAddress: string; #createWSFn: WebSocketFactory; #compression: 'gzip' | 'brotli' | 'none'; #lightMode: boolean; #confirmedReads?: boolean; // Invalidates events and asynchronous work from discarded sockets. #socketGeneration = 0; #hasEverConnected = false; #connectionEnded = false; #reconnectAttempt = 0; #reconnectTimer?: ReturnType; #forceTokenRefresh = false; #usedFreshToken = false; #livenessCleanup?: () => void; #pendingReplay?: { requestId: number; querySetIds: Set }; #preparingReplay = false; #socketEstablished = false; // These fields are meant to be strictly private. #queryId = 0; #requestId = 0; #eventId = 0; #emitter: EventEmitter; #inboundQueue: Uint8Array[] = []; #inboundQueueOffset = 0; #isDrainingInboundQueue = false; #outboundQueue: Uint8Array[] = []; #isOutboundFlushScheduled = false; #negotiatedWsProtocol: NegotiatedWsProtocol = V2_WS_PROTOCOL; #subscriptionManager = new SubscriptionManager(); #remoteModule: RemoteModule; #reducerCallbacks = new Map< number, (result: ReducerResultMessage['result']) => void >(); #reducerCallInfo = new Map(); #procedureCallbacks = new Map(); /** * Reject pending reducer and procedure calls when the socket drops. */ #pendingCallRejecters = new Map void>(); #rowDeserializers: Record>; #rowIdMetadata: Record< string, { primaryKeyColName?: string; primaryKeyColType?: AlgebraicType } >; #reducerArgsSerializers: Record< string, { serialize: Serializer; deserialize: Deserializer } >; #procedureSerializers: Record< string, { serializeArgs: Serializer; deserializeReturn: Deserializer } >; #reducerNameBytes: Record; #procedureNameBytes: Record; #sourceNameToTableDef: Record>; #messageReader = new BinaryReader(new Uint8Array()); #rowListReader = new BinaryReader(new Uint8Array()); #clientFrameEncoder = new BinaryWriter(1024); #boundSubscriptionBuilder!: () => SubscriptionBuilderImpl; #boundDisconnect!: () => void; // These fields are not part of the public API, but in a pinch you // could use JavaScript to access them by bypassing TypeScript's // private fields. // We use them in testing. private clientCache: ClientCache; private ws?: WebSocketAdapter; private wsPromise: Promise; constructor({ uri, nameOrAddress, identity, token, emitter, remoteModule, createWSFn, compression, lightMode, confirmedReads, automaticReconnect, tokenProvider, reconnectPolicy, }: DbConnectionConfig) { stdbLogger('info', 'Connecting to SpacetimeDB WS...'); // We use .toString() here because some versions of React Native contain a bug where the URL constructor // incorrectly treats a URL instance as a plain string. // This results in an attempt to call .endsWith() on it, leading to an error. const url = new URL(uri.toString()); if (!/^wss?:/.test(uri.protocol)) { url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'; } this.identity = identity; this.token = token; this.#remoteModule = remoteModule; this.#emitter = emitter; this.#boundSubscriptionBuilder = this.subscriptionBuilder.bind(this); this.#boundDisconnect = this.disconnect.bind(this); this.#rowDeserializers = Object.create(null); this.#rowIdMetadata = Object.create(null); this.#sourceNameToTableDef = Object.create(null); for (const table of Object.values(remoteModule.tables)) { this.#rowDeserializers[table.sourceName] = ProductType.makeDeserializer( table.rowType ); this.#sourceNameToTableDef[table.sourceName] = table as Values< RemoteModule['tables'] >; const primaryKeyColumn = Object.entries(table.columns).find( ([, column]) => column.columnMetadata.isPrimaryKey ); this.#rowIdMetadata[table.sourceName] = primaryKeyColumn ? { primaryKeyColName: primaryKeyColumn[0], primaryKeyColType: primaryKeyColumn[1].typeBuilder.algebraicType, } : {}; } this.#reducerArgsSerializers = Object.create(null); this.#reducerNameBytes = Object.create(null); for (const reducer of remoteModule.reducers) { this.#reducerArgsSerializers[reducer.name] = { serialize: ProductType.makeSerializer(reducer.paramsType), deserialize: ProductType.makeDeserializer(reducer.paramsType), }; this.#reducerNameBytes[reducer.name] = TEXT_ENCODER.encode(reducer.name); } this.#procedureSerializers = Object.create(null); this.#procedureNameBytes = Object.create(null); for (const procedure of remoteModule.procedures) { this.#procedureSerializers[procedure.name] = { serializeArgs: ProductType.makeSerializer( new ProductBuilder(procedure.params).algebraicType.value ), deserializeReturn: AlgebraicType.makeDeserializer( procedure.returnType.algebraicType ), }; this.#procedureNameBytes[procedure.name] = TEXT_ENCODER.encode( procedure.name ); } this.clientCache = new ClientCache(); this.db = this.#makeDbView(); this.reducers = this.#makeReducers(remoteModule); this.procedures = this.#makeProcedures(remoteModule); this.#automaticReconnect = automaticReconnect ?? false; this.#preparingReplay = this.#automaticReconnect; this.#reconnectPolicy = reconnectPolicy ?? DEFAULT_RECONNECT_POLICY; this.#tokenProvider = tokenProvider; this.#wsBaseUrl = url; this.#nameOrAddress = nameOrAddress; this.#createWSFn = createWSFn; this.#compression = compression; this.#lightMode = lightMode; this.#confirmedReads = confirmedReads; this.wsPromise = this.#openSocket(); } async #openSocket(): Promise { const generation = ++this.#socketGeneration; if (this.#hasEverConnected) { this.#setConnectionId(ConnectionId.random()); } this.#usedFreshToken = false; const url = new URL(this.#wsBaseUrl.toString()); url.searchParams.set('connection_id', this.#connectionIdHex); try { const authToken = await this.#tokenForAttempt(); if (generation !== this.#socketGeneration || this.#connectionEnded) { return undefined; } this.token = authToken; const ws = await this.#createWSFn({ url, nameOrAddress: this.#nameOrAddress, wsProtocol: [...PREFERRED_WS_PROTOCOLS], authToken, compression: this.#compression, lightMode: this.#lightMode, confirmedReads: this.#confirmedReads, connectionId: this.#connectionIdHex, sessionId: this.#automaticReconnect ? this.#sessionIdHex : undefined, }); if (generation !== this.#socketGeneration || this.#connectionEnded) { // A newer attempt superseded this socket while it was opening, or the // application disconnected in the meantime. ws.close(); return undefined; } this.ws = ws; this.#socketEstablished = false; const isCurrent = (): boolean => generation === this.#socketGeneration && !this.#connectionEnded; const handleLoss = (error: Error, isErrorEvent: boolean): void => { if (!isCurrent()) return; this.isActive = false; if (!this.#automaticReconnect) { this.#emitter.emit( isErrorEvent ? 'connectError' : 'disconnect', this, isErrorEvent ? error : this.#connectionError ); } else if (this.#socketEstablished) { this.#handleConnectionLoss(error); } else { this.#handleAttemptFailure(error); } }; ws.onclose = event => { if (!isCurrent()) return; if ( this.#automaticReconnect && this.#hasEverConnected && !this.#socketEstablished && event.code === SESSION_BUSY_CLOSE_CODE ) { // The server is tearing down the previous session holder. this.#discardSocket(); const delayMs = this.#reconnectDelayMs(1); this.#emitter.emit( 'connectError', this, new Error('Session busy'), this.#reconnectAttempt, delayMs ); this.#scheduleReconnect(this.#reconnectAttempt, delayMs); return; } const message = `WebSocket closed (code ${event.code}${event.reason ? `: ${event.reason}` : ''})`; const error = [1002, 1003, 1007, 1008].includes(event.code) ? new WebSocketProtocolError(message) : new Error(message); handleLoss(error, false); }; ws.onerror = event => { if (!isCurrent()) return; const error = errorFromEvent(event, 'WebSocket error'); if (!this.#automaticReconnect && this.#hasEverConnected) { this.isActive = false; this.#connectionError = error; ws.close(); return; } handleLoss(error, true); }; ws.onopen = () => { if (isCurrent()) this.#handleOnOpen(); }; ws.onmessage = message => { if (isCurrent()) this.#handleOnMessage(message); }; return ws; } catch (e) { if (generation !== this.#socketGeneration || this.#connectionEnded) { return undefined; } stdbLogger('error', 'Error connecting to SpacetimeDB WS'); this.isActive = false; this.#handleAttemptFailure(errorFromEvent(e, 'Failed to connect')); return undefined; } } async #tokenForAttempt(): Promise { // The initial connection uses the token the application configured. if (!this.#tokenProvider || !this.#hasEverConnected) { return this.token; } if (!this.#forceTokenRefresh && !tokenNeedsRefresh(this.token)) { return this.token; } const token = await this.#tokenProvider(); this.#forceTokenRefresh = false; this.#usedFreshToken = true; return token; } #handleConnectionLoss(error: Error): void { if (this.#connectionEnded) { return; } this.#discardSocket(); this.#failInFlightCalls(new UnknownCallResultError()); const willReconnect = this.#automaticReconnect && !this.isDisconnectRequested && !(error instanceof WebSocketProtocolError); if (!willReconnect) { this.#endConnection(error); return; } const attempt = this.#reconnectAttempt + 1; const delayMs = this.#reconnectDelayMs(attempt); try { this.#emitter.emit('disconnect', this, error, attempt, delayMs); } finally { this.#scheduleReconnect(attempt, delayMs); } } #handleAttemptFailure(error: Error): void { if (this.#connectionEnded) { return; } this.#discardSocket(); this.#failInFlightCalls(new UnknownCallResultError()); // A failed *initial* connection is not retried: the cause is usually a // misconfigured URI or database name that no retry will fix. const willReconnect = this.#automaticReconnect && this.#hasEverConnected && !this.isDisconnectRequested && !isTerminalConnectError(error) && !(isAuthError(error) && (!this.#tokenProvider || this.#usedFreshToken)); if (!willReconnect) { this.#endConnection(undefined, { alreadyReported: true }); this.#emitter.emit('connectError', this, error); return; } // A rejected token is worth one forced refresh: the retained token may // have been revoked, or the clock may be skewed. if (this.#tokenProvider && isAuthError(error)) { this.#forceTokenRefresh = true; } const attempt = this.#reconnectAttempt + 1; const delayMs = this.#reconnectDelayMs(attempt); try { this.#emitter.emit('connectError', this, error, attempt, delayMs); } finally { this.#scheduleReconnect(attempt, delayMs); } } #reconnectDelayMs(attempt: number): number { return computeReconnectDelayMs(attempt, Math.random, this.#reconnectPolicy); } #scheduleReconnect(attempt: number, delayMs: number): void { if (this.#connectionEnded || this.isDisconnectRequested) return; this.#reconnectAttempt = attempt; this.#clearReconnectTimer(); this.#reconnectTimer = setTimeout(() => { this.#reconnectTimer = undefined; if (this.#connectionEnded || this.isDisconnectRequested) { return; } this.wsPromise = this.#openSocket(); }, delayMs); } #clearReconnectTimer(): void { if (this.#reconnectTimer !== undefined) { clearTimeout(this.#reconnectTimer); this.#reconnectTimer = undefined; } } #endConnection( disconnectError: Error | undefined, options?: { alreadyReported?: boolean } ): void { if (this.#connectionEnded) { return; } this.#connectionEnded = true; this.isActive = false; this.#clearReconnectTimer(); this.#discardSocket(); this.#removeLivenessListeners(); this.#failInFlightCalls(new UnknownCallResultError()); if (!options?.alreadyReported) { this.#emitter.emit('disconnect', this, disconnectError); } } #failInFlightCalls(error: Error): void { const rejecters = [...this.#pendingCallRejecters.values()]; this.#pendingCallRejecters.clear(); this.#reducerCallbacks.clear(); this.#reducerCallInfo.clear(); this.#procedureCallbacks.clear(); for (const reject of rejecters) { reject(error); } } /** True while the SDK is between a lost connection and a completed reconnect. */ get isReconnecting(): boolean { return ( this.#automaticReconnect && this.#hasEverConnected && !this.isActive && !this.#connectionEnded ); } #discardSocket(): void { this.#socketGeneration += 1; this.isActive = false; this.#socketEstablished = false; this.#pendingReplay = undefined; this.#preparingReplay = this.#hasEverConnected; this.#outboundQueue.length = 0; this.#inboundQueue.length = 0; const ws = this.ws; this.ws = undefined; ws?.close(); for (const [id, entry] of this.#subscriptionManager.subscriptions) { if (entry.unsubscribeRequested) this.#endSubscription(id); } } // Resume events recover sockets that closed silently while the page was frozen. #installLivenessListeners(): void { if (!this.#automaticReconnect || this.#livenessCleanup) { return; } // React Native defines `window` without the DOM event API. const hasEvents = (target: unknown): boolean => typeof (target as EventTarget | undefined)?.addEventListener === 'function' && typeof (target as EventTarget).removeEventListener === 'function'; const doc = typeof document !== 'undefined' && hasEvents(document) ? document : undefined; const win = typeof window !== 'undefined' && hasEvents(window) ? window : undefined; if (!doc && !win) { return; } const onResume = (): void => this.#handleLivenessResume(); const onVisibilityChange = (): void => { if (doc?.visibilityState === 'visible') { onResume(); } }; doc?.addEventListener('visibilitychange', onVisibilityChange); win?.addEventListener('focus', onResume); win?.addEventListener('online', onResume); win?.addEventListener('pageshow', onResume); this.#livenessCleanup = () => { doc?.removeEventListener('visibilitychange', onVisibilityChange); win?.removeEventListener('focus', onResume); win?.removeEventListener('online', onResume); win?.removeEventListener('pageshow', onResume); this.#livenessCleanup = undefined; }; } #removeLivenessListeners(): void { this.#livenessCleanup?.(); } #handleLivenessResume(): void { if (this.#connectionEnded || this.isDisconnectRequested) { return; } if (this.isSocketClosed) { const error = new Error('WebSocket closed while suspended'); if (this.#socketEstablished) this.#handleConnectionLoss(error); else this.#handleAttemptFailure(error); return; } if (this.#reconnectTimer !== undefined) { // Retry now rather than waiting out a backoff computed before the pause. this.#clearReconnectTimer(); this.wsPromise = this.#openSocket(); } } #getNextQueryId = () => { const queryId = this.#queryId; this.#queryId += 1; return queryId; }; #getNextRequestId = () => this.#requestId++; #makeDbView(): ClientDbView { const view = Object.create(null) as ClientDbView; for (const tbl of Object.values(this.#sourceNameToTableDef)) { const [target, key] = accessorSlot(view, tbl.accessorName); Object.defineProperty(target, key, { enumerable: true, configurable: false, get: () => this.clientCache.getOrCreateTable(tbl), }); } return view; } #makeReducers(def: RemoteModule): ReducersView { const out: Record = {}; for (const reducer of def.reducers) { const reducerName = reducer.name; const encodedReducerName = this.#reducerNameBytes[reducerName]; const [target, key] = accessorSlot(out, reducer.accessorName); const { serialize: serializeArgs } = this.#reducerArgsSerializers[reducerName]; target[key] = (params: InferTypeOfParams) => { const writer = this.#reducerArgsEncoder; writer.clear(); serializeArgs(writer, params); const argsBuffer = writer.getBuffer(); return this.#callReducerWithEncodedName( reducerName, encodedReducerName, argsBuffer, params ); }; } return out as ReducersView; } #makeProcedures(def: RemoteModule): ProceduresView { const out: Record = {}; const writer = new BinaryWriter(1024); for (const procedure of def.procedures) { const procedureName = procedure.name; const encodedProcedureName = this.#procedureNameBytes[procedureName]; const [target, key] = accessorSlot(out, procedure.accessorName); const { serializeArgs, deserializeReturn } = this.#procedureSerializers[procedureName]; target[key] = ( params: InferTypeOfParams ): Promise => { writer.clear(); serializeArgs(writer, params); const argsBuffer = writer.getBuffer(); return this.#callProcedureWithEncodedName( procedureName, encodedProcedureName, argsBuffer ).then(returnBuf => { return deserializeReturn(new BinaryReader(returnBuf)); }); }; } return out as ProceduresView; } #makeEventContext( event: Event< ReducerEventInfo< RemoteModule['reducers'][number]['name'], InferTypeOfParams > > ): EventContextInterface { return { db: this.db, reducers: this.reducers, isActive: this.isActive, subscriptionBuilder: this.#boundSubscriptionBuilder, disconnect: this.#boundDisconnect, event, }; } // NOTE: This is very important!!! This is the actual function that // gets called when you call `connection.subscriptionBuilder()`. // The `subscriptionBuilder` function which is generated, just shadows // this function in the type system, but not the actual implementation! // Do not remove this function, or shoot yourself in the foot please. // It's not clear what would be a better way to do this at this exact // moment. subscriptionBuilder = (): SubscriptionBuilderImpl => { return new SubscriptionBuilderImpl(this); }; getFromBuilder< SchemaDef extends UntypedSchemaDef, >(): NamespacedQueryBuilder { return makeFromBuilder( this.#remoteModule.tables as SchemaDef['tables'] ); } registerSubscription( handle: SubscriptionHandleImpl, handleEmitter: EventEmitter< SubscribeEvent, SubscriptionEventCallback >, querySql: string[] ): number { const querySetId = this.#getNextQueryId(); this.#subscriptionManager.subscriptions.set(querySetId, { handle, emitter: handleEmitter, // Retained so the subscription can be replayed after a reconnect. querySql: [...querySql], }); if (!this.#preparingReplay) this.#sendSubscription(querySetId, querySql); return querySetId; } #sendSubscription(querySetId: number, querySql: string[]): void { const requestId = this.#getNextRequestId(); this.#sendMessage( ClientMessage.Subscribe({ queryStrings: querySql, querySetId: { id: querySetId }, requestId, }) ); } #replaySubscriptions(): void { const entries = [...this.#subscriptionManager.subscriptions.entries()]; const sets: SubscribeBatch['sets'] = []; const replayed = new Map>(); for (const [, entry] of entries) { const querySetId = this.#getNextQueryId(); entry.handle.rebindQuerySetId(querySetId); replayed.set(querySetId, entry); sets.push({ querySetId: { id: querySetId }, queryStrings: entry.querySql, }); } this.#subscriptionManager.subscriptions = replayed; const requestId = this.#getNextRequestId(); this.#pendingReplay = { requestId, querySetIds: new Set(replayed.keys()), }; this.#preparingReplay = false; if (sets.length === 0) { this.#applyReplayBatch({ requestId, results: [] }); return; } this.#sendMessage( ClientMessage.SubscribeBatch({ requestId, sets, }) ); } #applyReplayBatch(applied: SubscribeBatchApplied): void { const pending = this.#pendingReplay; const resultIds = new Set( applied.results.map(result => result.querySetId.id) ); if ( !pending || pending.requestId !== applied.requestId || resultIds.size !== applied.results.length || resultIds.size !== pending.querySetIds.size || [...resultIds].some(id => !pending.querySetIds.has(id)) ) { this.#handleProtocolError( new Error('Unexpected subscription replay response') ); return; } this.#pendingReplay = undefined; const event: Event = { id: this.#nextEventId(), tag: 'SubscribeApplied', }; const eventContext = this.#makeEventContext(event); // The removal half: every row the cache holds from the old connection. // Only tables which have been populated exist in the cache. The cache is // keyed by accessor name, but table updates carry the source name. const tableUpdates: CacheTableUpdate[] = []; for (const tableDef of Object.values(this.#sourceNameToTableDef)) { const table = this.clientCache.tables.get(tableDef.accessorName); const operations = table?.snapshotDeleteOperations() ?? []; if (operations.length > 0) { tableUpdates.push({ tableName: tableDef.sourceName, operations }); } } // The addition half: the rows of every set which applied. const failures: { entry: SubscriptionEntry; error: string; }[] = []; for (const result of applied.results) { const entry = this.#subscriptionManager.subscriptions.get( result.querySetId.id ); if (!entry) { continue; } if (result.outcome.tag === 'Error') { // The set is not registered, so drop it and report it below. this.#subscriptionManager.subscriptions.delete(result.querySetId.id); failures.push({ entry, error: result.outcome.value }); continue; } tableUpdates.push( ...this.#queryRowsToTableUpdates(result.outcome.value, 'insert') ); } const merged = this.#mergeTableUpdates(tableUpdates); const callbacks = this.#applyTableUpdates(merged, eventContext, { // A row which is unchanged across the outage appears as a // delete/insert pair and must produce no callback. skipIdenticalUpdates: true, }); const { event: _, ...subscriptionEventContext } = eventContext; for (const [querySetId, entry] of this.#subscriptionManager.subscriptions) { if (pending.querySetIds.has(querySetId)) { entry.emitter.emit('applied', subscriptionEventContext); } } for (const { entry, error: message } of failures) { const error = Error(message); const errorEventContext = this.#makeEventContext({ id: this.#nextEventId(), tag: 'Error', value: error, }); entry.emitter.emit( 'error', { ...errorEventContext, event: error }, error ); } this.#dispatchPendingCallbacks(callbacks); } #endSubscription(querySetId: number): void { const entry = this.#subscriptionManager.subscriptions.get(querySetId); this.#subscriptionManager.subscriptions.delete(querySetId); const { event: _, ...ctx } = this.#makeEventContext({ id: this.#nextEventId(), tag: 'UnsubscribeApplied', }); entry?.emitter.emit('end', ctx); } unregisterSubscription(querySetId: number): void { const entry = this.#subscriptionManager.subscriptions.get(querySetId); if (!entry) return; entry.unsubscribeRequested = true; if (this.#automaticReconnect && (!this.isActive || this.#preparingReplay)) { this.#endSubscription(querySetId); return; } const requestId = this.#getNextRequestId(); this.#sendMessage( ClientMessage.Unsubscribe({ querySetId: { id: querySetId }, requestId, flags: UnsubscribeFlags.SendDroppedRows, }) ); } #parseRowList( type: 'insert' | 'delete', tableName: string, rowList: BsatnRowList ): Operation[] { const buffer = rowList.rowsData; const reader = this.#rowListReader; const rows: Operation[] = []; const deserializeRow = this.#rowDeserializers[tableName]; const { primaryKeyColName, primaryKeyColType } = this.#rowIdMetadata[tableName]; // Decode each row from its own slice, using the boundaries the server // sends. A module can add columns to the end of a table without breaking // clients built against the old schema: their bindings read the columns // they know, and the rest of the row is skipped. const sizeHint = rowList.sizeHint; if (sizeHint.tag === 'FixedSize' && sizeHint.value === 0) { throw new Error('Fixed-size BSATN row list cannot have zero-sized rows'); } const rowCount = sizeHint.tag === 'RowOffsets' ? sizeHint.value.length : Math.floor(buffer.length / sizeHint.value); const rowStart = (i: number) => sizeHint.tag === 'RowOffsets' ? Number(sizeHint.value[i]) : i * sizeHint.value; for (let i = 0; i < rowCount; i++) { const end = i + 1 < rowCount ? rowStart(i + 1) : buffer.length; const rowBytes = buffer.subarray(rowStart(i), end); reader.reset(rowBytes); const row = deserializeRow(reader); let rowId: ComparablePrimitive | undefined = undefined; if (primaryKeyColName !== undefined && primaryKeyColType !== undefined) { rowId = AlgebraicType.intoMapKey( primaryKeyColType, row[primaryKeyColName] ); } else { // Convert the row's bytes to a base64 string, so we can use it as a map key. rowId = fromByteArray(rowBytes); } rows.push({ type, rowId, row }); } return rows; } // Take a bunch of table updates and ensure that there is at most one update per table. #mergeTableUpdates( updates: CacheTableUpdate[] ): CacheTableUpdate[] { const merged = new Map(); for (const update of updates) { const ops = merged.get(update.tableName); if (ops) { for (const op of update.operations) ops.push(op); } else { merged.set(update.tableName, update.operations.slice()); } } return Array.from(merged, ([tableName, operations]) => ({ tableName, operations, })); } #queryRowsToTableUpdates( rows: QueryRows, opType: 'insert' | 'delete' ): CacheTableUpdate[] { const updates: CacheTableUpdate[] = []; for (const tableRows of rows.tables) { updates.push({ tableName: tableRows.table, operations: this.#parseRowList(opType, tableRows.table, tableRows.rows), }); } return this.#mergeTableUpdates(updates); } #tableUpdateRowsToOperations( tableName: string, rows: TableUpdateRows ): Operation[] { if (rows.tag === 'PersistentTable') { const inserts = this.#parseRowList( 'insert', tableName, rows.value.inserts ); const deletes = this.#parseRowList( 'delete', tableName, rows.value.deletes ); return inserts.concat(deletes); } if (rows.tag === 'EventTable') { // Event table rows are insert-only. The table cache handles skipping // storage for event tables and only firing on_insert callbacks. return this.#parseRowList('insert', tableName, rows.value.events); } return []; } #querySetUpdateToTableUpdates( querySetUpdate: QuerySetUpdate ): CacheTableUpdate[] { const updates: CacheTableUpdate[] = []; for (const tableUpdate of querySetUpdate.tables) { let operations: Operation[] = []; for (const rows of tableUpdate.rows) { operations = operations.concat( this.#tableUpdateRowsToOperations(tableUpdate.tableName, rows) ); } updates.push({ tableName: tableUpdate.tableName, operations, }); } return this.#mergeTableUpdates(updates); } #flushOutboundQueue(wsResolved: WebSocketAdapter): void { if (this.#negotiatedWsProtocol === V3_WS_PROTOCOL) { this.#flushOutboundQueueV3(wsResolved); return; } this.#flushOutboundQueueV2(wsResolved); } #flushOutboundQueueV2(wsResolved: WebSocketAdapter): void { const pending = this.#outboundQueue.splice(0); for (const message of pending) { wsResolved.send(message); } } #flushOutboundQueueV3(wsResolved: WebSocketAdapter): void { if (this.#outboundQueue.length === 0) { return; } // Emit at most one bounded frame per flush. If more encoded v2 messages // remain in the queue, they are sent by a later scheduled flush so inbound // traffic and other tasks get a chance to run between websocket writes. const batchSize = countClientMessagesForV3Frame( this.#outboundQueue, MAX_V3_OUTBOUND_FRAME_BYTES ); wsResolved.send( encodeClientMessagesV3( this.#clientFrameEncoder, this.#outboundQueue, batchSize ) ); if (batchSize === this.#outboundQueue.length) { this.#outboundQueue.length = 0; return; } this.#outboundQueue.copyWithin(0, batchSize); this.#outboundQueue.length -= batchSize; if (this.#outboundQueue.length > 0) { this.#scheduleDeferredOutboundFlush(); } } #scheduleOutboundFlush(): void { this.#scheduleOutboundFlushWith('microtask'); } #scheduleDeferredOutboundFlush(): void { this.#scheduleOutboundFlushWith('next-task'); } #scheduleOutboundFlushWith(schedule: 'microtask' | 'next-task'): void { if (this.#isOutboundFlushScheduled) { return; } this.#isOutboundFlushScheduled = true; const flush = () => { this.#isOutboundFlushScheduled = false; if (this.ws && this.isActive) { this.#flushOutboundQueue(this.ws); } }; // The first v3 flush stays on the current turn so same-tick sends coalesce. // Follow-up flushes after a size-capped frame yield to the next task so we // do not sit in a tight send loop while inbound websocket work is waiting. if (schedule === 'next-task') { setTimeout(flush, 0); } else { queueMicrotask(flush); } } #reducerArgsEncoder = new BinaryWriter(1024); #clientMessageEncoder = new BinaryWriter(1024); #sendEncodedMessage( encoded: Uint8Array, describe: () => string ): void { stdbLogger('trace', describe); if (this.ws && this.isActive) { if (this.#negotiatedWsProtocol === V2_WS_PROTOCOL) { if (this.#outboundQueue.length) this.#flushOutboundQueue(this.ws); this.ws.send(encoded); return; } this.#outboundQueue.push(encoded.slice()); this.#scheduleOutboundFlush(); } else { // Use slice() to copy, in case the clientMessageEncoder's buffer gets reused // before the connection opens or before a v3 microbatch flush runs. this.#outboundQueue.push(encoded.slice()); } } #rejectCallIfDisconnected(): DisconnectedError | undefined { return this.#automaticReconnect && !this.isActive ? new DisconnectedError() : undefined; } #sendMessage(message: ClientMessage): void { const writer = this.#clientMessageEncoder; writer.clear(); ClientMessage.serialize(writer, message); const encoded = writer.getBuffer(); const isLive = !!(this.ws && this.isActive); this.#sendEncodedMessage(encoded, () => isLive ? `Sending message to server: ${stringify(message)}` : `Queuing message to server: ${stringify(message)}` ); } #sendCallReducerMessage( requestId: number, reducerNameBytes: Uint8Array, argsBuffer: Uint8Array ): void { const writer = this.#clientMessageEncoder; writer.clear(); writer.writeByte(CLIENT_MESSAGE_CALL_REDUCER_TAG); writer.writeU32(requestId); writer.writeU8(0); writer.writeUInt8Array(reducerNameBytes); writer.writeUInt8Array(argsBuffer); const encoded = writer.getBuffer(); this.#sendEncodedMessage( encoded, () => `Sending reducer call message to server: requestId=${requestId}` ); } #sendCallProcedureMessage( requestId: number, procedureNameBytes: Uint8Array, argsBuffer: Uint8Array ): void { const writer = this.#clientMessageEncoder; writer.clear(); writer.writeByte(CLIENT_MESSAGE_CALL_PROCEDURE_TAG); writer.writeU32(requestId); writer.writeU8(0); writer.writeUInt8Array(procedureNameBytes); writer.writeUInt8Array(argsBuffer); const encoded = writer.getBuffer(); this.#sendEncodedMessage( encoded, () => `Sending procedure call message to server: requestId=${requestId}` ); } #setConnectionId(connectionId: ConnectionId): void { this.connectionId = connectionId; this.#connectionIdHex = connectionId.toHexString(); } #nextEventId(): string { this.#eventId += 1; return `${this.#connectionIdHex}:${this.#eventId}`; } /** * Handles WebSocket onOpen event. */ #handleOnOpen(): void { if (this.ws) { this.#negotiatedWsProtocol = normalizeWsProtocol(this.ws.protocol); } this.isActive = !this.#automaticReconnect; this.#installLivenessListeners(); if (this.ws && this.isActive) { this.#flushOutboundQueue(this.ws); } } #applyTableUpdates( tableUpdates: CacheTableUpdate[], eventContext: EventContextInterface, options?: { skipIdenticalUpdates?: boolean } ): PendingCallback[] { const pendingCallbacks: PendingCallback[] = []; for (const tableUpdate of tableUpdates) { // Get table information for the table being updated const tableName = tableUpdate.tableName; const tableDef = this.#sourceNameToTableDef[tableName]; const table = this.clientCache.getOrCreateTable(tableDef); const newCallbacks = table.applyOperations( tableUpdate.operations as Operation< RowType> >[], eventContext, options ); for (const callback of newCallbacks) { pendingCallbacks.push(callback); } } return pendingCallbacks; } #applyTransactionUpdates( eventContext: EventContextInterface, tu: TransactionUpdate ): PendingCallback[] { const allUpdates: CacheTableUpdate[] = []; for (const querySetUpdate of tu.querySets) { const tableUpdates = this.#querySetUpdateToTableUpdates(querySetUpdate); for (const update of tableUpdates) { allUpdates.push(update); } // TODO: When we have per-query storage, we will want to apply the per-query events here. } return this.#applyTableUpdates( this.#mergeTableUpdates(allUpdates), eventContext ); } #dispatchPendingCallbacks(callbacks: readonly PendingCallback[]): void { stdbLogger( 'trace', () => `Calling ${callbacks.length} triggered row callbacks` ); for (const callback of callbacks) { callback.cb(); } } #processServerMessage(serverMessage: ServerMessage): void { stdbLogger( 'trace', () => `Processing server message: ${stringify(serverMessage)}` ); if ( this.#automaticReconnect && (serverMessage.tag === 'InitialConnection') === this.#socketEstablished ) { this.#handleProtocolError( new Error('Unexpected message during connection handshake') ); return; } switch (serverMessage.tag) { case 'InitialConnection': { const isReconnect = this.#hasEverConnected; if ( isReconnect && this.identity && !this.identity.isEqual(serverMessage.value.identity) ) { // Retrying cannot recover the old identity, so stop here rather // than serving the application someone else's data. const error = new IdentityChangedError(); this.#endConnection(undefined, { alreadyReported: true }); this.#emitter.emit('connectError', this, error); break; } this.identity = serverMessage.value.identity; // The server issues a token on the first connection; retain it so // reconnects present the same identity. if (!this.token && serverMessage.value.token) { this.token = serverMessage.value.token; } this.#setConnectionId(serverMessage.value.connectionId); this.isActive = true; this.#hasEverConnected = true; this.#socketEstablished = true; // A connection was established, so the backoff schedule starts over. this.#reconnectAttempt = 0; this.#emitter.emit( isReconnect ? 'automaticReconnect' : 'connect', this, this.identity, this.token ); if (this.#connectionEnded) break; if (isReconnect) { this.#replaySubscriptions(); } else if (this.#preparingReplay) { this.#preparingReplay = false; for (const [id, entry] of this.#subscriptionManager.subscriptions) { this.#sendSubscription(id, entry.querySql); } } if (this.ws) this.#flushOutboundQueue(this.ws); break; } case 'SubscribeApplied': { const querySetId = serverMessage.value.querySetId.id; const subscription = this.#subscriptionManager.subscriptions.get(querySetId); if (!subscription) { stdbLogger( 'error', `Received SubscribeApplied for unknown querySetId ${querySetId}.` ); return; } const event: Event = { id: this.#nextEventId(), tag: 'SubscribeApplied', }; const eventContext = this.#makeEventContext(event); const tableUpdates = this.#queryRowsToTableUpdates( serverMessage.value.rows, 'insert' ); const callbacks = this.#applyTableUpdates(tableUpdates, eventContext); const { event: _, ...subscriptionEventContext } = eventContext; subscription.emitter.emit('applied', subscriptionEventContext); this.#dispatchPendingCallbacks(callbacks); break; } case 'UnsubscribeApplied': { const querySetId = serverMessage.value.querySetId.id; const subscription = this.#subscriptionManager.subscriptions.get(querySetId); if (!subscription) { stdbLogger( 'error', `Received UnsubscribeApplied for unknown querySetId ${querySetId}.` ); return; } const event: Event = { id: this.#nextEventId(), tag: 'UnsubscribeApplied', }; const eventContext = this.#makeEventContext(event); const tableUpdates = serverMessage.value.rows ? this.#queryRowsToTableUpdates(serverMessage.value.rows, 'delete') : []; const callbacks = this.#applyTableUpdates(tableUpdates, eventContext); const { event: _, ...subscriptionEventContext } = eventContext; subscription.emitter.emit('end', subscriptionEventContext); this.#subscriptionManager.subscriptions.delete(querySetId); this.#dispatchPendingCallbacks(callbacks); break; } case 'SubscriptionError': { const querySetId = serverMessage.value.querySetId.id; const requestId = serverMessage.value.requestId; const error = Error(serverMessage.value.error); const event: Event = { id: this.#nextEventId(), tag: 'Error', value: error, }; const eventContext = this.#makeEventContext(event); const errorContext = { ...eventContext, event: error, }; // If the requestId isn't set, that means we already applied the subscription. // Since we don't know how to remove the relevant rows from our table cache, we need // to kill the connection. Once we have per-query storage, this won't be fatal. if (requestId == null) { stdbLogger( 'error', `Disconnecting due to error for a previously applied subscription: ${serverMessage.value.error}` ); this.disconnect(); break; } const subscription = this.#subscriptionManager.subscriptions.get(querySetId); if (subscription) { subscription.emitter.emit('error', errorContext, error); this.#subscriptionManager.subscriptions.delete(querySetId); } else { stdbLogger( 'error', `Received SubscriptionError for unknown querySetId ${querySetId}:`, error ); } break; } case 'TransactionUpdate': { const event: Event = { id: this.#nextEventId(), tag: 'Transaction', }; const eventContext = this.#makeEventContext(event); const callbacks = this.#applyTransactionUpdates( eventContext, serverMessage.value ); this.#dispatchPendingCallbacks(callbacks); break; } case 'ReducerResult': { const { requestId, result } = serverMessage.value; if (result.tag === 'Ok') { const reducerInfo = this.#reducerCallInfo.get(requestId); const eventId: string = this.#nextEventId(); const event: Event = reducerInfo ? { id: eventId, tag: 'Reducer', value: { timestamp: serverMessage.value.timestamp, outcome: result, reducer: { name: reducerInfo.name, args: reducerInfo.args, }, }, } : { id: eventId, tag: 'Transaction', }; const eventContext = this.#makeEventContext(event as any); const callbacks = this.#applyTransactionUpdates( eventContext, result.value.transactionUpdate ); this.#dispatchPendingCallbacks(callbacks); } this.#reducerCallInfo.delete(requestId); const cb = this.#reducerCallbacks.get(requestId); this.#reducerCallbacks.delete(requestId); cb?.(result); break; } case 'ProcedureResult': { const { status, requestId } = serverMessage.value; const result: ProcedureResultMessage['result'] = status.tag === 'Returned' ? { tag: 'Ok', value: status.value } : { tag: 'Err', value: status.value }; const cb = this.#procedureCallbacks.get(requestId); this.#procedureCallbacks.delete(requestId); cb?.(result); break; } case 'OneOffQueryResult': { stdbLogger( 'warn', 'Received OneOffQueryResult but SDK does not expose one-off query APIs yet.' ); break; } case 'SubscribeBatchApplied': { this.#applyReplayBatch(serverMessage.value); break; } } } #processV2Message(data: Uint8Array): void { const reader = this.#messageReader; reader.reset(data); let message: ServerMessage; try { message = ServerMessage.deserialize(reader); } catch (cause) { this.#handleProtocolError(cause); return; } this.#processServerMessage(message); } #processMessage(data: Uint8Array): void { if (this.#negotiatedWsProtocol !== V3_WS_PROTOCOL) { this.#processV2Message(data); return; } let dispatching = false; const generation = this.#socketGeneration; try { forEachServerMessageV3(this.#messageReader, data, serverMessage => { if (generation !== this.#socketGeneration) return; dispatching = true; this.#processServerMessage(serverMessage); dispatching = false; }); } catch (cause) { if (dispatching) throw cause; this.#handleProtocolError(cause); } } /** * End the connection over a server message that could not be decoded or * applied. A retry would not fix it, so this never reconnects. The error * goes to `onConnectError` if the connection was not yet established, and * to `onDisconnect` otherwise. */ #handleProtocolError(cause: unknown): void { stdbLogger('error', 'Failed to process a server message', cause); const error = new WebSocketProtocolError('Invalid server message', { cause, }); if (this.#socketEstablished) this.#handleConnectionLoss(error); else this.#handleAttemptFailure(error); } /** * Handles WebSocket onMessage event. * @param wsMessage MessageEvent object. */ #handleOnMessage(wsMessage: { data: Uint8Array }): void { // Queue inbound messages so they are processed strictly in arrival order. // We deliberately drain synchronously instead of promise-chaining each // message, but this still guarantees that we do not begin processing the // next message until the current message has been fully handled. this.#inboundQueue.push(wsMessage.data); if (this.#isDrainingInboundQueue) { return; } this.#isDrainingInboundQueue = true; try { // TODO: If this loop starts monopolizing the event loop under sustained // inbound traffic, switch to a chunked drain that periodically yields. while (this.#inboundQueueOffset < this.#inboundQueue.length) { const data = this.#inboundQueue[this.#inboundQueueOffset]; this.#inboundQueueOffset += 1; if (data) { this.#processMessage(data); } } } catch (e) { // A message that could not be applied leaves the client cache // inconsistent, and rethrowing from a WebSocket listener crashes Node // hosts. Handle it like a message that could not be decoded: end the // connection, which drops what is queued and settles calls in flight. // (Callback errors never get here; `EventEmitter` logs them.) this.#handleProtocolError(e); } finally { if (this.#inboundQueueOffset >= this.#inboundQueue.length) { this.#inboundQueue.length = 0; } else if (this.#inboundQueueOffset > 0) { this.#inboundQueue = this.#inboundQueue.slice(this.#inboundQueueOffset); } this.#inboundQueueOffset = 0; this.#isDrainingInboundQueue = false; } } /** * Call a reducer on your SpacetimeDB module. * * @param reducerName The name of the reducer to call * @param argsSerializer The arguments to pass to the reducer */ callReducer( reducerName: string, argsBuffer: Uint8Array, reducerArgs?: object ): Promise { const encodedReducerName = this.#reducerNameBytes[reducerName]; if (encodedReducerName) { return this.#callReducerWithEncodedName( reducerName, encodedReducerName, argsBuffer, reducerArgs ); } return this.#callReducerGeneric(reducerName, argsBuffer, reducerArgs); } #callReducerWithEncodedName( reducerName: string, encodedReducerName: Uint8Array, argsBuffer: Uint8Array, reducerArgs?: object ): Promise { const rejected = this.#rejectCallIfDisconnected(); if (rejected) { return Promise.reject(rejected); } const { promise, resolve, reject } = createDeferred(); const requestId = this.#getNextRequestId(); this.#sendCallReducerMessage(requestId, encodedReducerName, argsBuffer); if (reducerArgs) { this.#reducerCallInfo.set(requestId, { name: reducerName, args: reducerArgs, }); } this.#pendingCallRejecters.set(requestId, reject); this.#reducerCallbacks.set(requestId, result => { this.#pendingCallRejecters.delete(requestId); if (result.tag === 'Ok' || result.tag === 'OkEmpty') { resolve(); } else { if (result.tag === 'Err') { /// Interpret the user-returned error as a string. const reader = new BinaryReader(result.value); const errorString = reader.readString(); reject(new SenderError(errorString)); } else if (result.tag === 'InternalError') { reject(new InternalError(result.value)); } else { const unreachable: never = result; reject(new Error('Unexpected reducer result')); void unreachable; } } }); return promise; } #callReducerGeneric( reducerName: string, argsBuffer: Uint8Array, reducerArgs?: object ): Promise { const rejected = this.#rejectCallIfDisconnected(); if (rejected) { return Promise.reject(rejected); } const { promise, resolve, reject } = createDeferred(); const requestId = this.#getNextRequestId(); const message = ClientMessage.CallReducer({ reducer: reducerName, args: argsBuffer, requestId, flags: 0, }); this.#sendMessage(message); if (reducerArgs) { this.#reducerCallInfo.set(requestId, { name: reducerName, args: reducerArgs, }); } this.#pendingCallRejecters.set(requestId, reject); this.#reducerCallbacks.set(requestId, result => { this.#pendingCallRejecters.delete(requestId); if (result.tag === 'Ok' || result.tag === 'OkEmpty') { resolve(); } else { if (result.tag === 'Err') { /// Interpret the user-returned error as a string. const reader = new BinaryReader(result.value); const errorString = reader.readString(); reject(new SenderError(errorString)); } else if (result.tag === 'InternalError') { reject(new InternalError(result.value)); } else { const unreachable: never = result; reject(new Error('Unexpected reducer result')); void unreachable; } } }); return promise; } /** * Call a reducer on your SpacetimeDB module with typed arguments. * @param reducerSchema The schema of the reducer to call * @param callReducerFlags The flags for the reducer call * @param params The arguments to pass to the reducer */ callReducerWithParams( reducerName: string, // TODO: remove _paramsType: ProductType, params: object ): Promise { const writer = this.#reducerArgsEncoder; writer.clear(); this.#reducerArgsSerializers[reducerName].serialize(writer, params); const argsBuffer = writer.getBuffer(); return this.callReducer(reducerName, argsBuffer, params); } /** * Call a reducer on your SpacetimeDB module. * * @param procedureName The name of the reducer to call * @param argsBuffer The arguments to pass to the reducer */ callProcedure( procedureName: string, argsBuffer: Uint8Array ): Promise { const encodedProcedureName = this.#procedureNameBytes[procedureName]; if (encodedProcedureName) { return this.#callProcedureWithEncodedName( procedureName, encodedProcedureName, argsBuffer ); } return this.#callProcedureGeneric(procedureName, argsBuffer); } #callProcedureWithEncodedName( procedureName: string, encodedProcedureName: Uint8Array, argsBuffer: Uint8Array ): Promise { const rejected = this.#rejectCallIfDisconnected(); if (rejected) { return Promise.reject(rejected); } const { promise, resolve, reject } = createDeferred(); const requestId = this.#getNextRequestId(); this.#sendCallProcedureMessage(requestId, encodedProcedureName, argsBuffer); this.#pendingCallRejecters.set(requestId, reject); this.#procedureCallbacks.set(requestId, result => { this.#pendingCallRejecters.delete(requestId); if (result.tag === 'Ok') { resolve(result.value); } else { reject(result.value); } }); return promise; } #callProcedureGeneric( procedureName: string, argsBuffer: Uint8Array ): Promise { const rejected = this.#rejectCallIfDisconnected(); if (rejected) { return Promise.reject(rejected); } const { promise, resolve, reject } = createDeferred(); const requestId = this.#getNextRequestId(); const message = ClientMessage.CallProcedure({ procedure: procedureName, args: argsBuffer, requestId, // reserved for future use - 0 is the only valid value flags: 0, }); this.#sendMessage(message); this.#pendingCallRejecters.set(requestId, reject); this.#procedureCallbacks.set(requestId, result => { this.#pendingCallRejecters.delete(requestId); if (result.tag === 'Ok') { resolve(result.value); } else { reject(result.value); } }); return promise; } /** * Call a reducer on your SpacetimeDB module with typed arguments. * @param reducerSchema The schema of the reducer to call * @param callReducerFlags The flags for the reducer call * @param params The arguments to pass to the reducer */ callProcedureWithParams( procedureName: string, // TODO: remove _paramsType: ProductType, params: object, // TODO: remove _returnType: AlgebraicType ): Promise { const writer = new BinaryWriter(1024); const { serializeArgs, deserializeReturn } = this.#procedureSerializers[procedureName]; serializeArgs(writer, params); const argsBuffer = writer.getBuffer(); return this.callProcedure(procedureName, argsBuffer).then(returnBuf => { return deserializeReturn(new BinaryReader(returnBuf)); }); } /** * Close the current connection. * * @example * * ```ts * const connection = DbConnection.builder().build(); * connection.disconnect() * ``` */ disconnect(): void { this.isDisconnectRequested = true; if (this.#automaticReconnect) { if (this.#connectionEnded) { this.#emitter.emit('disconnect', this); } else { this.#endConnection(undefined); } } else { this.wsPromise.then(ws => ws?.close()); } } private on( eventName: E, callback: ( ctx: DbConnectionImpl, ...args: ConnectionEventArgs[E] ) => void ): void { this.#emitter.on(eventName, callback); } private off( eventName: E, callback: ( ctx: DbConnectionImpl, ...args: ConnectionEventArgs[E] ) => void ): void { this.#emitter.off(eventName, callback); } private onConnect( callback: ( ctx: DbConnectionImpl, ...args: ConnectionEventArgs['connect'] ) => void ): void { this.#emitter.on('connect', callback); } private onAutomaticReconnect( callback: ( ctx: DbConnectionImpl, ...args: ConnectionEventArgs['automaticReconnect'] ) => void ): void { this.#emitter.on('automaticReconnect', callback); } private onDisconnect( callback: ( ctx: DbConnectionImpl, ...args: ConnectionEventArgs['disconnect'] ) => void ): void { this.#emitter.on('disconnect', callback); } private onConnectError( callback: ( ctx: DbConnectionImpl, ...args: ConnectionEventArgs['connectError'] ) => void ): void { this.#emitter.on('connectError', callback); } removeOnConnect( callback: ( ctx: DbConnectionImpl, ...args: ConnectionEventArgs['connect'] ) => void ): void { this.#emitter.off('connect', callback); } removeOnAutomaticReconnect( callback: ( ctx: DbConnectionImpl, ...args: ConnectionEventArgs['automaticReconnect'] ) => void ): void { this.#emitter.off('automaticReconnect', callback); } removeOnDisconnect( callback: ( ctx: DbConnectionImpl, ...args: ConnectionEventArgs['disconnect'] ) => void ): void { this.#emitter.off('disconnect', callback); } removeOnConnectError( callback: ( ctx: DbConnectionImpl, ...args: ConnectionEventArgs['connectError'] ) => void ): void { this.#emitter.off('connectError', callback); } }