From a10fdc37e6ba8d53f6f993cd079a51e64edcf92a Mon Sep 17 00:00:00 2001 From: joshua-spacetime Date: Wed, 8 Apr 2026 13:36:51 -0700 Subject: [PATCH 1/2] Update typescript sdk to use v3 websocket api --- .../src/sdk/client_api/v3.ts | 15 ++ .../src/sdk/db_connection_impl.ts | 162 ++++++++++++++---- .../src/sdk/websocket_decompress_adapter.ts | 7 +- .../src/sdk/websocket_protocols.ts | 25 +++ .../src/sdk/websocket_test_adapter.ts | 88 ++++++++-- .../src/sdk/websocket_v3_frames.ts | 107 ++++++++++++ .../tests/db_connection.test.ts | 70 ++++++++ .../tests/websocket_v3_frames.test.ts | 28 +++ 8 files changed, 447 insertions(+), 55 deletions(-) create mode 100644 crates/bindings-typescript/src/sdk/client_api/v3.ts create mode 100644 crates/bindings-typescript/src/sdk/websocket_protocols.ts create mode 100644 crates/bindings-typescript/src/sdk/websocket_v3_frames.ts create mode 100644 crates/bindings-typescript/tests/websocket_v3_frames.test.ts diff --git a/crates/bindings-typescript/src/sdk/client_api/v3.ts b/crates/bindings-typescript/src/sdk/client_api/v3.ts new file mode 100644 index 00000000000..296080164ad --- /dev/null +++ b/crates/bindings-typescript/src/sdk/client_api/v3.ts @@ -0,0 +1,15 @@ +/* eslint-disable */ +/* tslint:disable */ +import { t as __t, type Infer as __Infer } from '../../lib/type_builders'; + +export const ClientFrame = __t.enum('ClientFrame', { + Single: __t.byteArray(), + Batch: __t.array(__t.byteArray()), +}); +export type ClientFrame = __Infer; + +export const ServerFrame = __t.enum('ServerFrame', { + Single: __t.byteArray(), + Batch: __t.array(__t.byteArray()), +}); +export type ServerFrame = __Infer; diff --git a/crates/bindings-typescript/src/sdk/db_connection_impl.ts b/crates/bindings-typescript/src/sdk/db_connection_impl.ts index b873b30bff6..da73546a6b9 100644 --- a/crates/bindings-typescript/src/sdk/db_connection_impl.ts +++ b/crates/bindings-typescript/src/sdk/db_connection_impl.ts @@ -1,7 +1,7 @@ import { ConnectionId, ProductBuilder, ProductType } from '../'; import { AlgebraicType, type ComparablePrimitive } from '../'; -import { BinaryReader } from '../'; -import { BinaryWriter } from '../'; +import BinaryReader from '../lib/binary_reader.ts'; +import BinaryWriter from '../lib/binary_writer.ts'; import { BsatnRowList, ClientMessage, @@ -60,6 +60,18 @@ import type { ProceduresView } from './procedures.ts'; import type { Values } from '../lib/type_util.ts'; import type { TransactionUpdate } from './client_api/types.ts'; import { InternalError, SenderError } from '../lib/errors.ts'; +import { + normalizeWsProtocol, + PREFERRED_WS_PROTOCOLS, + V2_WS_PROTOCOL, + V3_WS_PROTOCOL, + type NegotiatedWsProtocol, +} from './websocket_protocols'; +import { + countClientMessagesForV3Frame, + decodeServerMessagesV3, + encodeClientMessagesV3, +} from './websocket_v3_frames.ts'; export { DbConnectionBuilder, @@ -117,6 +129,9 @@ 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; export class DbConnectionImpl implements DbContext @@ -172,6 +187,8 @@ export class DbConnectionImpl #inboundQueueOffset = 0; #isDrainingInboundQueue = false; #outboundQueue: Uint8Array[] = []; + #isOutboundFlushScheduled = false; + #negotiatedWsProtocol: NegotiatedWsProtocol = V2_WS_PROTOCOL; #subscriptionManager = new SubscriptionManager(); #remoteModule: RemoteModule; #reducerCallbacks = new Map< @@ -198,6 +215,7 @@ export class DbConnectionImpl #sourceNameToTableDef: Record>; #messageReader = new BinaryReader(new Uint8Array()); #rowListReader = new BinaryReader(new Uint8Array()); + #clientFrameEncoder = new BinaryWriter(1024); #boundSubscriptionBuilder!: () => SubscriptionBuilderImpl; #boundDisconnect!: () => void; @@ -296,7 +314,7 @@ export class DbConnectionImpl this.wsPromise = createWSFn({ url, nameOrAddress, - wsProtocol: 'v2.bsatn.spacetimedb', + wsProtocol: [...PREFERRED_WS_PROTOCOLS], authToken: token, compression: compression, lightMode: lightMode, @@ -595,23 +613,87 @@ export class DbConnectionImpl } #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 + ); + const pending = this.#outboundQueue.splice(0, batchSize); + wsResolved.send(encodeClientMessagesV3(this.#clientFrameEncoder, pending)); + + 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.#outboundQueue.length) this.#flushOutboundQueue(this.ws); + if (this.#negotiatedWsProtocol === V2_WS_PROTOCOL) { + if (this.#outboundQueue.length) this.#flushOutboundQueue(this.ws); + this.ws.send(encoded); + return; + } - stdbLogger('trace', describe); - this.ws.send(encoded); + this.#outboundQueue.push(encoded.slice()); + this.#scheduleOutboundFlush(); } else { - stdbLogger('trace', describe); - // use slice() to copy, in case the clientMessageEncoder's buffer gets used + // 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()); } } @@ -681,6 +763,9 @@ export class DbConnectionImpl * Handles WebSocket onOpen event. */ #handleOnOpen(): void { + if (this.ws) { + this.#negotiatedWsProtocol = normalizeWsProtocol(this.ws.protocol); + } this.isActive = true; if (this.ws) { this.#flushOutboundQueue(this.ws); @@ -728,7 +813,17 @@ export class DbConnectionImpl ); } - #processMessage(data: Uint8Array): void { + #dispatchPendingCallbacks(callbacks: readonly PendingCallback[]): void { + stdbLogger( + 'trace', + () => `Calling ${callbacks.length} triggered row callbacks` + ); + for (const callback of callbacks) { + callback.cb(); + } + } + + #processV2Message(data: Uint8Array): void { const reader = this.#messageReader; reader.reset(data); const serverMessage = ServerMessage.deserialize(reader); @@ -769,13 +864,7 @@ export class DbConnectionImpl const callbacks = this.#applyTableUpdates(tableUpdates, eventContext); const { event: _, ...subscriptionEventContext } = eventContext; subscription.emitter.emit('applied', subscriptionEventContext); - stdbLogger( - 'trace', - () => `Calling ${callbacks.length} triggered row callbacks` - ); - for (const callback of callbacks) { - callback.cb(); - } + this.#dispatchPendingCallbacks(callbacks); break; } case 'UnsubscribeApplied': { @@ -801,13 +890,7 @@ export class DbConnectionImpl const { event: _, ...subscriptionEventContext } = eventContext; subscription.emitter.emit('end', subscriptionEventContext); this.#subscriptionManager.subscriptions.delete(querySetId); - stdbLogger( - 'trace', - () => `Calling ${callbacks.length} triggered row callbacks` - ); - for (const callback of callbacks) { - callback.cb(); - } + this.#dispatchPendingCallbacks(callbacks); break; } case 'SubscriptionError': { @@ -861,13 +944,7 @@ export class DbConnectionImpl eventContext, serverMessage.value ); - stdbLogger( - 'trace', - () => `Calling ${callbacks.length} triggered row callbacks` - ); - for (const callback of callbacks) { - callback.cb(); - } + this.#dispatchPendingCallbacks(callbacks); break; } case 'ReducerResult': { @@ -899,13 +976,7 @@ export class DbConnectionImpl eventContext, result.value.transactionUpdate ); - stdbLogger( - 'trace', - () => `Calling ${callbacks.length} triggered row callbacks` - ); - for (const callback of callbacks) { - callback.cb(); - } + this.#dispatchPendingCallbacks(callbacks); } this.#reducerCallInfo.delete(requestId); const cb = this.#reducerCallbacks.get(requestId); @@ -934,6 +1005,23 @@ export class DbConnectionImpl } } + #processMessage(data: Uint8Array): void { + if (this.#negotiatedWsProtocol !== V3_WS_PROTOCOL) { + this.#processV2Message(data); + return; + } + + const messages = decodeServerMessagesV3(this.#messageReader, data); + stdbLogger( + 'trace', + () => + `Processing server frame: ${messages.length === 1 ? 'single' : `batch(${messages.length})`}` + ); + for (const message of messages) { + this.#processV2Message(message); + } + } + /** * Handles WebSocket onMessage event. * @param wsMessage MessageEvent object. diff --git a/crates/bindings-typescript/src/sdk/websocket_decompress_adapter.ts b/crates/bindings-typescript/src/sdk/websocket_decompress_adapter.ts index 40157393dd1..b5db13a8149 100644 --- a/crates/bindings-typescript/src/sdk/websocket_decompress_adapter.ts +++ b/crates/bindings-typescript/src/sdk/websocket_decompress_adapter.ts @@ -2,6 +2,7 @@ import { decompress } from './decompress'; import { resolveWS } from './ws'; export interface WebsocketAdapter { + readonly protocol: string; send(msg: Uint8Array): void; close(): void; @@ -12,6 +13,10 @@ export interface WebsocketAdapter { } export class WebsocketDecompressAdapter implements WebsocketAdapter { + get protocol(): string { + return this.#ws.protocol; + } + set onclose(handler: (ev: CloseEvent) => void) { this.#ws.onclose = handler; } @@ -73,7 +78,7 @@ export class WebsocketDecompressAdapter implements WebsocketAdapter { confirmedReads, }: { url: URL; - wsProtocol: string; + wsProtocol: string | string[]; nameOrAddress: string; authToken?: string; compression: 'gzip' | 'none'; diff --git a/crates/bindings-typescript/src/sdk/websocket_protocols.ts b/crates/bindings-typescript/src/sdk/websocket_protocols.ts new file mode 100644 index 00000000000..2d6598143e9 --- /dev/null +++ b/crates/bindings-typescript/src/sdk/websocket_protocols.ts @@ -0,0 +1,25 @@ +import { stdbLogger } from './logger.ts'; + +export const V2_WS_PROTOCOL = 'v2.bsatn.spacetimedb'; +export const V3_WS_PROTOCOL = 'v3.bsatn.spacetimedb'; +export const PREFERRED_WS_PROTOCOLS = [V3_WS_PROTOCOL, V2_WS_PROTOCOL] as const; + +export type NegotiatedWsProtocol = + | typeof V2_WS_PROTOCOL + | typeof V3_WS_PROTOCOL; + +export function normalizeWsProtocol(protocol: string): NegotiatedWsProtocol { + if (protocol === V3_WS_PROTOCOL) { + return V3_WS_PROTOCOL; + } + // We treat an empty negotiated subprotocol as legacy v2 for compatibility. + if (protocol === '' || protocol === V2_WS_PROTOCOL) { + return V2_WS_PROTOCOL; + } + + stdbLogger( + 'warn', + `Unexpected websocket subprotocol "${protocol}", falling back to ${V2_WS_PROTOCOL}.` + ); + return V2_WS_PROTOCOL; +} diff --git a/crates/bindings-typescript/src/sdk/websocket_test_adapter.ts b/crates/bindings-typescript/src/sdk/websocket_test_adapter.ts index 6ac15f0e7fe..e8969021796 100644 --- a/crates/bindings-typescript/src/sdk/websocket_test_adapter.ts +++ b/crates/bindings-typescript/src/sdk/websocket_test_adapter.ts @@ -1,61 +1,115 @@ -import { BinaryReader, BinaryWriter } from '../'; +import BinaryReader from '../lib/binary_reader.ts'; +import BinaryWriter from '../lib/binary_writer.ts'; import { ClientMessage, ServerMessage } from './client_api/types'; import type { WebsocketAdapter } from './websocket_decompress_adapter'; +import { + PREFERRED_WS_PROTOCOLS, + V3_WS_PROTOCOL, +} from './websocket_protocols'; +import { + decodeClientMessagesV3, + encodeServerMessagesV3, +} from './websocket_v3_frames.ts'; class WebsocketTestAdapter implements WebsocketAdapter { - onclose: any; - // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type - onopen!: () => void; - onmessage: any; - onerror: any; + protocol: string = ''; - messageQueue: any[]; + messageQueue: Uint8Array[]; outgoingMessages: ClientMessage[]; closed: boolean; + supportedProtocols: string[]; + + #onclose: (ev: CloseEvent) => void = () => {}; + #onopen: () => void = () => {}; + #onmessage: (msg: { data: Uint8Array }) => void = () => {}; + #onerror: (msg: ErrorEvent) => void = () => {}; constructor() { this.messageQueue = []; this.outgoingMessages = []; this.closed = false; + this.supportedProtocols = [...PREFERRED_WS_PROTOCOLS]; + } + + set onclose(handler: (ev: CloseEvent) => void) { + this.#onclose = handler; + } + + set onopen(handler: () => void) { + this.#onopen = handler; } - send(message: any): void { - const parsedMessage = ClientMessage.deserialize(new BinaryReader(message)); - this.outgoingMessages.push(parsedMessage); - // console.ClientMessageSerde.deserialize(message); - this.messageQueue.push(message); + set onmessage(handler: (msg: { data: Uint8Array }) => void) { + this.#onmessage = handler; + } + + set onerror(handler: (msg: ErrorEvent) => void) { + this.#onerror = handler; + } + + send(message: Uint8Array): void { + const rawMessage = message.slice(); + const outgoingMessages = + this.protocol === V3_WS_PROTOCOL + ? decodeClientMessagesV3(rawMessage) + : [rawMessage]; + + for (const outgoingMessage of outgoingMessages) { + this.outgoingMessages.push( + ClientMessage.deserialize(new BinaryReader(outgoingMessage)) + ); + } + this.messageQueue.push(rawMessage); } close(): void { this.closed = true; - this.onclose?.({ code: 1000, reason: 'normal closure', wasClean: true }); + this.#onclose({ + code: 1000, + reason: 'normal closure', + wasClean: true, + } as CloseEvent); } acceptConnection(): void { - this.onopen(); + this.#onopen(); } sendToClient(message: ServerMessage): void { const writer = new BinaryWriter(1024); ServerMessage.serialize(writer, message); - const rawBytes = writer.getBuffer(); + const rawBytes = writer.getBuffer().slice(); // The brotli library's `compress` is somehow broken: it returns `null` for some inputs. // See https://github.com/foliojs/brotli.js/issues/36, which is closed but not actually fixed. // So we send the uncompressed data here, and in `spacetimedb.ts`, // if compression fails, we treat the raw message as having been uncompressed all along. // const data = compress(rawBytes); - this.onmessage({ data: rawBytes }); + const outboundData = + this.protocol === V3_WS_PROTOCOL + ? encodeServerMessagesV3(writer, [rawBytes]).slice() + : rawBytes; + this.#onmessage({ data: outboundData }); } async createWebSocketFn(_args: { url: URL; - wsProtocol: string; + wsProtocol: string | string[]; nameOrAddress: string; authToken?: string; compression: 'gzip' | 'none'; lightMode: boolean; confirmedReads?: boolean; }): Promise { + const requestedProtocols = Array.isArray(_args.wsProtocol) + ? _args.wsProtocol + : [_args.wsProtocol]; + const negotiatedProtocol = requestedProtocols.find(protocol => + this.supportedProtocols.includes(protocol) + ); + if (!negotiatedProtocol) { + return Promise.reject(new Error('No compatible websocket protocol')); + } + this.protocol = negotiatedProtocol; return this; } } diff --git a/crates/bindings-typescript/src/sdk/websocket_v3_frames.ts b/crates/bindings-typescript/src/sdk/websocket_v3_frames.ts new file mode 100644 index 00000000000..d9939b7897c --- /dev/null +++ b/crates/bindings-typescript/src/sdk/websocket_v3_frames.ts @@ -0,0 +1,107 @@ +import BinaryReader from '../lib/binary_reader.ts'; +import BinaryWriter from '../lib/binary_writer.ts'; +import { + ClientFrame, + ServerFrame, + type ClientFrame as ClientFrameValue, + type ServerFrame as ServerFrameValue, +} from './client_api/v3'; + +// v3 is only a transport envelope. The inner payloads are already-encoded v2 +// websocket messages, so these helpers intentionally operate on raw bytes. +type V3FrameValue = ClientFrameValue | ServerFrameValue; + +function flattenFrame(frame: V3FrameValue): Uint8Array[] { + return frame.tag === 'Single' ? [frame.value] : frame.value; +} + +function ensureMessages(messages: readonly Uint8Array[]): void { + if (messages.length === 0) { + throw new RangeError('v3 websocket frames must contain at least one message'); + } +} + +const BSATN_SUM_TAG_BYTES = 1; +const BSATN_LENGTH_PREFIX_BYTES = 4; + +function encodedSingleFrameSize(message: Uint8Array): number { + return BSATN_SUM_TAG_BYTES + BSATN_LENGTH_PREFIX_BYTES + message.length; +} + +function encodedBatchFrameSizeForFirstMessage(message: Uint8Array): number { + return ( + BSATN_SUM_TAG_BYTES + + BSATN_LENGTH_PREFIX_BYTES + + BSATN_LENGTH_PREFIX_BYTES + + message.length + ); +} + +function encodedBatchElementSize(message: Uint8Array): number { + return BSATN_LENGTH_PREFIX_BYTES + message.length; +} + +export function countClientMessagesForV3Frame( + messages: readonly Uint8Array[], + maxFrameBytes: number +): number { + ensureMessages(messages); + + const firstMessage = messages[0]!; + if (encodedSingleFrameSize(firstMessage) > maxFrameBytes) { + return 1; + } + + let count = 1; + let batchSize = encodedBatchFrameSizeForFirstMessage(firstMessage); + while (count < messages.length) { + const nextMessage = messages[count]!; + const nextBatchSize = batchSize + encodedBatchElementSize(nextMessage); + if (nextBatchSize > maxFrameBytes) { + break; + } + batchSize = nextBatchSize; + count += 1; + } + return count; +} + +export function encodeClientMessagesV3( + writer: BinaryWriter, + messages: readonly Uint8Array[] +): Uint8Array { + ensureMessages(messages); + writer.clear(); + if (messages.length === 1) { + ClientFrame.serialize(writer, ClientFrame.Single(messages[0]!)); + } else { + ClientFrame.serialize(writer, ClientFrame.Batch(Array.from(messages))); + } + return writer.getBuffer(); +} + +export function decodeClientMessagesV3(data: Uint8Array): Uint8Array[] { + return flattenFrame(ClientFrame.deserialize(new BinaryReader(data))); +} + +export function encodeServerMessagesV3( + writer: BinaryWriter, + messages: readonly Uint8Array[] +): Uint8Array { + ensureMessages(messages); + writer.clear(); + if (messages.length === 1) { + ServerFrame.serialize(writer, ServerFrame.Single(messages[0]!)); + } else { + ServerFrame.serialize(writer, ServerFrame.Batch(Array.from(messages))); + } + return writer.getBuffer(); +} + +export function decodeServerMessagesV3( + reader: BinaryReader, + data: Uint8Array +): Uint8Array[] { + reader.reset(data); + return flattenFrame(ServerFrame.deserialize(reader)); +} diff --git a/crates/bindings-typescript/tests/db_connection.test.ts b/crates/bindings-typescript/tests/db_connection.test.ts index ec17430e41a..1cd3a428cf8 100644 --- a/crates/bindings-typescript/tests/db_connection.test.ts +++ b/crates/bindings-typescript/tests/db_connection.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, test } from 'vitest'; import { + BinaryReader, BinaryWriter, ConnectionId, Identity, @@ -8,8 +9,13 @@ import { Timestamp, type Infer, } from '../src'; +import { ClientFrame } from '../src/sdk/client_api/v3'; import { ServerMessage } from '../src/sdk/client_api/types'; import WebsocketTestAdapter from '../src/sdk/websocket_test_adapter'; +import { + V2_WS_PROTOCOL, + V3_WS_PROTOCOL, +} from '../src/sdk/websocket_protocols'; import { DbConnection } from '../test-app/src/module_bindings'; import User from '../test-app/src/module_bindings/user_table'; import { @@ -194,6 +200,69 @@ describe('DbConnection', () => { expect(called).toBeTruthy(); }); + test('batches same-tick reducer calls when v3 is negotiated', async () => { + const wsAdapter = new WebsocketTestAdapter(); + const client = DbConnection.builder() + .withUri('ws://127.0.0.1:1234') + .withDatabaseName('db') + .withWSFn(wsAdapter.createWebSocketFn.bind(wsAdapter) as any) + .build(); + + await client['wsPromise']; + wsAdapter.acceptConnection(); + + void client.reducers.createPlayer({ + name: 'Player One', + location: { x: 1, y: 2 }, + }); + void client.reducers.createPlayer({ + name: 'Player Two', + location: { x: 3, y: 4 }, + }); + + await Promise.resolve(); + + expect(wsAdapter.protocol).toEqual(V3_WS_PROTOCOL); + expect(wsAdapter.messageQueue).toHaveLength(1); + expect(wsAdapter.outgoingMessages).toHaveLength(2); + + const outboundFrame = ClientFrame.deserialize( + new BinaryReader(wsAdapter.messageQueue[0]) + ); + expect(outboundFrame.tag).toEqual('Batch'); + if (outboundFrame.tag === 'Batch') { + expect(outboundFrame.value).toHaveLength(2); + } + }); + + test('falls back to v2 and does not batch reducer calls when v3 is unavailable', async () => { + const wsAdapter = new WebsocketTestAdapter(); + wsAdapter.supportedProtocols = [V2_WS_PROTOCOL]; + const client = DbConnection.builder() + .withUri('ws://127.0.0.1:1234') + .withDatabaseName('db') + .withWSFn(wsAdapter.createWebSocketFn.bind(wsAdapter) as any) + .build(); + + await client['wsPromise']; + wsAdapter.acceptConnection(); + + void client.reducers.createPlayer({ + name: 'Player One', + location: { x: 1, y: 2 }, + }); + void client.reducers.createPlayer({ + name: 'Player Two', + location: { x: 3, y: 4 }, + }); + + await Promise.resolve(); + + expect(wsAdapter.protocol).toEqual(V2_WS_PROTOCOL); + expect(wsAdapter.messageQueue).toHaveLength(2); + expect(wsAdapter.outgoingMessages).toHaveLength(2); + }); + test('disconnects when SubscriptionError has no requestId', async () => { const onDisconnectPromise = new Deferred(); const wsAdapter = new WebsocketTestAdapter(); @@ -750,6 +819,7 @@ describe('DbConnection', () => { .withWSFn(wsAdapter.createWebSocketFn.bind(wsAdapter) as any) .build(); await client['wsPromise']; + wsAdapter.acceptConnection(); const user1 = { identity: bobIdentity, username: 'bob' }; const user2 = { identity: sallyIdentity, diff --git a/crates/bindings-typescript/tests/websocket_v3_frames.test.ts b/crates/bindings-typescript/tests/websocket_v3_frames.test.ts new file mode 100644 index 00000000000..4fa23d00c9b --- /dev/null +++ b/crates/bindings-typescript/tests/websocket_v3_frames.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, test } from 'vitest'; +import { countClientMessagesForV3Frame } from '../src/sdk/websocket_v3_frames'; + +describe('websocket_v3_frames', () => { + test('counts as many client messages as fit within the encoded frame limit', () => { + const messages = [ + new Uint8Array(10), + new Uint8Array(20), + new Uint8Array(30), + ]; + + expect(countClientMessagesForV3Frame(messages, 1 + 4 + 10)).toBe(1); + expect(countClientMessagesForV3Frame(messages, 1 + 4 + 4 + 10 + 4 + 20)).toBe( + 2 + ); + expect( + countClientMessagesForV3Frame( + messages, + 1 + 4 + 4 + 10 + 4 + 20 + 4 + 30 + ) + ).toBe(3); + }); + + test('still emits an oversized first message on its own', () => { + const messages = [new Uint8Array(300_000), new Uint8Array(10)]; + expect(countClientMessagesForV3Frame(messages, 256 * 1024)).toBe(1); + }); +}); From 8d2b9b10763ce88a70e050d2239cdc08fa1d75e0 Mon Sep 17 00:00:00 2001 From: joshua-spacetime Date: Wed, 8 Apr 2026 17:09:17 -0700 Subject: [PATCH 2/2] fix lint --- .../src/sdk/websocket_test_adapter.ts | 10 ++-------- .../src/sdk/websocket_v3_frames.ts | 4 +++- .../bindings-typescript/tests/db_connection.test.ts | 5 +---- .../tests/websocket_v3_frames.test.ts | 11 ++++------- 4 files changed, 10 insertions(+), 20 deletions(-) diff --git a/crates/bindings-typescript/src/sdk/websocket_test_adapter.ts b/crates/bindings-typescript/src/sdk/websocket_test_adapter.ts index e8969021796..4c2c48b42f0 100644 --- a/crates/bindings-typescript/src/sdk/websocket_test_adapter.ts +++ b/crates/bindings-typescript/src/sdk/websocket_test_adapter.ts @@ -2,10 +2,7 @@ import BinaryReader from '../lib/binary_reader.ts'; import BinaryWriter from '../lib/binary_writer.ts'; import { ClientMessage, ServerMessage } from './client_api/types'; import type { WebsocketAdapter } from './websocket_decompress_adapter'; -import { - PREFERRED_WS_PROTOCOLS, - V3_WS_PROTOCOL, -} from './websocket_protocols'; +import { PREFERRED_WS_PROTOCOLS, V3_WS_PROTOCOL } from './websocket_protocols'; import { decodeClientMessagesV3, encodeServerMessagesV3, @@ -22,7 +19,6 @@ class WebsocketTestAdapter implements WebsocketAdapter { #onclose: (ev: CloseEvent) => void = () => {}; #onopen: () => void = () => {}; #onmessage: (msg: { data: Uint8Array }) => void = () => {}; - #onerror: (msg: ErrorEvent) => void = () => {}; constructor() { this.messageQueue = []; @@ -43,9 +39,7 @@ class WebsocketTestAdapter implements WebsocketAdapter { this.#onmessage = handler; } - set onerror(handler: (msg: ErrorEvent) => void) { - this.#onerror = handler; - } + set onerror(_handler: (msg: ErrorEvent) => void) {} send(message: Uint8Array): void { const rawMessage = message.slice(); diff --git a/crates/bindings-typescript/src/sdk/websocket_v3_frames.ts b/crates/bindings-typescript/src/sdk/websocket_v3_frames.ts index d9939b7897c..4aa494cb764 100644 --- a/crates/bindings-typescript/src/sdk/websocket_v3_frames.ts +++ b/crates/bindings-typescript/src/sdk/websocket_v3_frames.ts @@ -17,7 +17,9 @@ function flattenFrame(frame: V3FrameValue): Uint8Array[] { function ensureMessages(messages: readonly Uint8Array[]): void { if (messages.length === 0) { - throw new RangeError('v3 websocket frames must contain at least one message'); + throw new RangeError( + 'v3 websocket frames must contain at least one message' + ); } } diff --git a/crates/bindings-typescript/tests/db_connection.test.ts b/crates/bindings-typescript/tests/db_connection.test.ts index 1cd3a428cf8..f4eca70f245 100644 --- a/crates/bindings-typescript/tests/db_connection.test.ts +++ b/crates/bindings-typescript/tests/db_connection.test.ts @@ -12,10 +12,7 @@ import { import { ClientFrame } from '../src/sdk/client_api/v3'; import { ServerMessage } from '../src/sdk/client_api/types'; import WebsocketTestAdapter from '../src/sdk/websocket_test_adapter'; -import { - V2_WS_PROTOCOL, - V3_WS_PROTOCOL, -} from '../src/sdk/websocket_protocols'; +import { V2_WS_PROTOCOL, V3_WS_PROTOCOL } from '../src/sdk/websocket_protocols'; import { DbConnection } from '../test-app/src/module_bindings'; import User from '../test-app/src/module_bindings/user_table'; import { diff --git a/crates/bindings-typescript/tests/websocket_v3_frames.test.ts b/crates/bindings-typescript/tests/websocket_v3_frames.test.ts index 4fa23d00c9b..d0ac7dbe258 100644 --- a/crates/bindings-typescript/tests/websocket_v3_frames.test.ts +++ b/crates/bindings-typescript/tests/websocket_v3_frames.test.ts @@ -10,14 +10,11 @@ describe('websocket_v3_frames', () => { ]; expect(countClientMessagesForV3Frame(messages, 1 + 4 + 10)).toBe(1); - expect(countClientMessagesForV3Frame(messages, 1 + 4 + 4 + 10 + 4 + 20)).toBe( - 2 - ); expect( - countClientMessagesForV3Frame( - messages, - 1 + 4 + 4 + 10 + 4 + 20 + 4 + 30 - ) + countClientMessagesForV3Frame(messages, 1 + 4 + 4 + 10 + 4 + 20) + ).toBe(2); + expect( + countClientMessagesForV3Frame(messages, 1 + 4 + 4 + 10 + 4 + 20 + 4 + 30) ).toBe(3); });