Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion crates/bindings-typescript/src/sdk/db_connection_impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1873,8 +1873,14 @@ export class DbConnectionImpl<RemoteModule extends UntypedRemoteModule>
}
}

/**
* 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 {
if (!this.#automaticReconnect) throw cause;
stdbLogger('error', 'Failed to process a server message', cause);
const error = new WebSocketProtocolError('Invalid server message', {
cause,
});
Expand Down Expand Up @@ -1907,6 +1913,13 @@ export class DbConnectionImpl<RemoteModule extends UntypedRemoteModule>
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;
Expand Down
10 changes: 9 additions & 1 deletion crates/bindings-typescript/src/sdk/event_emitter.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { stdbLogger } from './logger.ts';

// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
export class EventEmitter<Key, Callback extends Function = Function> {
#events: Map<Key, Set<Callback>> = new Map();
Expand Down Expand Up @@ -25,8 +27,14 @@ export class EventEmitter<Key, Callback extends Function = Function> {
return;
}

// Like the C# SDK, a throwing callback is logged and does not stop the
// others or escape into the WebSocket listener, which would crash Node.
for (const callback of callbacks) {
callback(...args);
try {
callback(...args);
} catch (e) {
stdbLogger('error', 'A callback threw', e);
}
}
}
}
148 changes: 147 additions & 1 deletion crates/bindings-typescript/tests/db_connection.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { assertType, beforeEach, describe, expect, test } from 'vitest';
import { assertType, beforeEach, describe, expect, test, vi } from 'vitest';
import {
BinaryWriter,
ConnectionId,
Expand Down Expand Up @@ -216,6 +216,152 @@ describe('DbConnection', () => {
expect(client.isActive).toBe(false);
});

test('logs an error thrown by a callback and keeps the connection open', async () => {
const wsAdapter = new WebsocketTestAdapter();
const onDisconnect = vi.fn();
const secondOnConnect = vi.fn();

const client = DbConnection.builder()
.withUri('ws://127.0.0.1:1234')
.withDatabaseName('db')
.withWSFn(wsAdapter.openWebSocket)
.onConnect(() => {
throw new Error('callback failed');
})
.onConnect(secondOnConnect)
.onDisconnect(onDisconnect)
.build();

await client['wsPromise'];
wsAdapter.acceptConnection();
// Node rethrows errors from WebSocket listeners on the next tick, which
// crashes the host process.
expect(() =>
wsAdapter.sendToClient(
ServerMessage.InitialConnection({
identity: anIdentity,
token: 'a-token',
connectionId: ConnectionId.random(),
})
)
).not.toThrow();

expect(secondOnConnect).toHaveBeenCalledOnce();
expect(client.isActive).toBe(true);
expect(wsAdapter.closed).toBe(false);
expect(onDisconnect).not.toHaveBeenCalled();
});

test('reports a row it cannot decode through onDisconnect instead of throwing', async () => {
const onDisconnectPromise = new Deferred<Error | undefined>();
const wsAdapter = new WebsocketTestAdapter();

const client = DbConnection.builder()
.withUri('ws://127.0.0.1:1234')
.withDatabaseName('db')
.withWSFn(wsAdapter.openWebSocket)
.onDisconnect((_ctx, error) => onDisconnectPromise.resolve(error))
.build();

await client['wsPromise'];
wsAdapter.acceptConnection();
wsAdapter.sendToClient(
ServerMessage.InitialConnection({
identity: anIdentity,
token: 'a-token',
connectionId: ConnectionId.random(),
})
);
expect(client.isActive).toBe(true);
const inserted: number[] = [];
client.db.player.onInsert((_ctx, player) => inserted.push(player.id));
const inFlight = client.reducers.createPlayer({
name: 'drogus',
location: { x: 0, y: 0 },
});

// A `player` row one byte short, as when the client's bindings are out of
// step with the module's schema.
const truncatedPlayer = encodePlayer({
id: 1,
userId: anIdentity,
name: 'drogus',
location: { x: 0, y: 0 },
}).slice(0, -1);
expect(() =>
wsAdapter.sendToClient(
ServerMessage.TransactionUpdate({
querySets: [makeQuerySetUpdate(0, 'player', truncatedPlayer)],
})
)
).not.toThrow();

const error = await onDisconnectPromise.promise;
expect(error?.message).toBe('Invalid server message');
expect(error?.cause).toBeInstanceOf(RangeError);
expect(client.isActive).toBe(false);
expect(wsAdapter.closed).toBe(true);

// A call in flight settles, and a message that arrives later is ignored.
await expect(inFlight).rejects.toThrow();
wsAdapter.sendToClient(
ServerMessage.TransactionUpdate({
querySets: [
makeQuerySetUpdate(
0,
'player',
encodePlayer({
id: 2,
userId: anIdentity,
name: 'drogus',
location: { x: 0, y: 0 },
})
),
],
})
);
expect(inserted).toEqual([]);
});

test('reports a message it cannot apply before connecting through onConnectError', async () => {
const onConnectErrorPromise = new Deferred<Error>();
const onDisconnect = vi.fn();
const wsAdapter = new WebsocketTestAdapter();

const client = DbConnection.builder()
.withUri('ws://127.0.0.1:1234')
.withDatabaseName('db')
.withWSFn(wsAdapter.openWebSocket)
.onConnectError((_ctx, error) => onConnectErrorPromise.resolve(error))
.onDisconnect(onDisconnect)
.build();

await client['wsPromise'];
wsAdapter.acceptConnection();
// A truncated row before `InitialConnection` stands in for any first
// message the client cannot process: the connection was never up.
const truncatedPlayer = encodePlayer({
id: 1,
userId: anIdentity,
name: 'drogus',
location: { x: 0, y: 0 },
}).slice(0, -1);
expect(() =>
wsAdapter.sendToClient(
ServerMessage.TransactionUpdate({
querySets: [makeQuerySetUpdate(0, 'player', truncatedPlayer)],
})
)
).not.toThrow();

const error = await onConnectErrorPromise.promise;
expect(error.message).toBe('Invalid server message');
expect(error.cause).toBeInstanceOf(RangeError);
expect(onDisconnect).not.toHaveBeenCalled();
expect(client.isActive).toBe(false);
expect(wsAdapter.closed).toBe(true);
});

test('marks disconnect as requested when disconnect() is called', async () => {
const onDisconnectPromise = new Deferred<void>();
const wsAdapter = new WebsocketTestAdapter();
Expand Down
Loading