Skip to content
Closed
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
43 changes: 19 additions & 24 deletions crates/bindings-typescript/src/sdk/db_connection_impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1271,27 +1271,19 @@ export class DbConnectionImpl<RemoteModule extends UntypedRemoteModule>
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');
}
let previousOffset = 0;
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);
rowList.sizeHint.tag === 'RowOffsets'
? rowList.sizeHint.value.length
: rowList.sizeHint.value > 0
? Math.floor(buffer.length / rowList.sizeHint.value)
: undefined;

for (
let i = 0;
rowCount === undefined ? reader.remaining > 0 : i < rowCount;
i++
) {
const row = deserializeRow(reader);
let rowId: ComparablePrimitive | undefined = undefined;
if (primaryKeyColName !== undefined && primaryKeyColType !== undefined) {
Expand All @@ -1300,11 +1292,14 @@ export class DbConnectionImpl<RemoteModule extends UntypedRemoteModule>
row[primaryKeyColName]
);
} else {
// Convert the row's bytes to a base64 string, so we can use it as a map key.
rowId = fromByteArray(rowBytes);
const rowBytes = buffer.subarray(previousOffset, reader.offset);
const asBase64 = fromByteArray(rowBytes);
rowId = asBase64;

}
rows.push({ type, rowId, row });
}

return rows;
}

Expand Down Expand Up @@ -2110,7 +2105,7 @@ export class DbConnectionImpl<RemoteModule extends UntypedRemoteModule>
if (result.tag === 'Ok') {
resolve(result.value);
} else {
reject(result.value);
reject(new InternalError(result.value));
}
});
return promise;
Expand Down Expand Up @@ -2140,7 +2135,7 @@ export class DbConnectionImpl<RemoteModule extends UntypedRemoteModule>
if (result.tag === 'Ok') {
resolve(result.value);
} else {
reject(result.value);
reject(new InternalError(result.value));
}
});
return promise;
Expand Down
38 changes: 38 additions & 0 deletions crates/bindings-typescript/tests/binary_read_write.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,46 @@ describe('BinaryReader/Writer', () => {
const deserializedTransactionUpdate = ServerMessage.deserialize(
new BinaryReader(rawBytes)
);

expect(deserializedTransactionUpdate).toEqual(transactionUpdate);
});

test('round-trips a zero-sized row list encoded with row offsets', () => {
const rowList = {
sizeHint: RowSizeHint.RowOffsets([0n]),
rowsData: new Uint8Array([]),
};

const transactionUpdate = ServerMessage.TransactionUpdate({
querySets: [
{
querySetId: { id: 0 },
tables: [
{
tableName: 'empty',
rows: [
TableUpdateRows.PersistentTable({
inserts: rowList,
deletes: {
sizeHint: RowSizeHint.RowOffsets([]),
rowsData: new Uint8Array([]),
},
}),
],
},
],
},
],
});

const writer = new BinaryWriter(1024);
ServerMessage.serialize(writer, transactionUpdate);
const rawBytes = writer.getBuffer();
const deserialized = ServerMessage.deserialize(new BinaryReader(rawBytes));

expect(deserialized.tag).toBe('TransactionUpdate');
expect(deserialized).toEqual(transactionUpdate);
});
});

describe('readUInt8Array buffer ownership', () => {
Expand Down
60 changes: 60 additions & 0 deletions crates/bindings-typescript/tests/db_connection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
InternalError,
SenderError,
Timestamp,
TimeDuration,
type Infer,
} from '../src';
import { ServerMessage } from '../src/sdk/client_api/types';
Expand Down Expand Up @@ -83,6 +84,18 @@ function getLastCallReducerRequestId(wsAdapter: WebsocketTestAdapter): number {
throw new Error('No CallReducer message found in messageQueue.');
}

function getLastCallProcedureRequestId(
wsAdapter: WebsocketTestAdapter
): number {
for (let i = wsAdapter.outgoingMessages.length - 1; i >= 0; i--) {
const message = wsAdapter.outgoingMessages[i];
if (message.tag === 'CallProcedure') {
return message.value.requestId;
}
}
throw new Error('No CallProcedure message found in messageQueue.');
}

function getLastSubscribeMessageInfo(wsAdapter: WebsocketTestAdapter): {
requestId: number;
querySetId: number;
Expand Down Expand Up @@ -835,6 +848,53 @@ describe('DbConnection', () => {
);
});

test('procedure internal error rejects with InternalError', async () => {
const wsAdapter = new WebsocketTestAdapter();
const onConnectPromise = new Deferred<void>();
const client = DbConnection.builder()
.withUri('ws://127.0.0.1:1234')
.withDatabaseName('db')
.withWSFn(wsAdapter.openWebSocket)
.onConnect(() => {
onConnectPromise.resolve();
})
.build();

await client['wsPromise'];
wsAdapter.acceptConnection();
wsAdapter.sendToClient(
ServerMessage.InitialConnection({
identity: anIdentity,
token: 'a-token',
connectionId: ConnectionId.random(),
})
);
await onConnectPromise.promise;

const procedurePromise = client.callProcedure(
'test_procedure',
new Uint8Array()
);
await Promise.resolve();
const requestId = getLastCallProcedureRequestId(wsAdapter);
wsAdapter.sendToClient(
ServerMessage.ProcedureResult({
requestId,
timestamp: new Timestamp(0n),
totalHostExecutionDuration: new TimeDuration(0n),
status: {
tag: 'InternalError',
value: 'internal procedure test error',
},
})
);

await expect(procedurePromise).rejects.toBeInstanceOf(InternalError);
await expect(procedurePromise).rejects.toThrow(
'internal procedure test error'
);
});

/*
test('it calls onInsert callback when a record is added with a subscription update and then with a transaction update', async () => {
const wsAdapter = new WebsocketTestAdapter();
Expand Down