Skip to content

Commit

Permalink
fix: websocket message handling, Buffer, onConnect (#107)
Browse files Browse the repository at this point in the history
* Push

* Buffer.from

* Format

* Add changeset
  • Loading branch information
PuruVJ authored Oct 8, 2024
1 parent b9db9b6 commit 2f6c82c
Show file tree
Hide file tree
Showing 13 changed files with 80 additions and 41 deletions.
5 changes: 5 additions & 0 deletions .changeset/dull-mangos-appear.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clockworklabs/spacetimedb-sdk': patch
---

fix: websocket message handling, Buffer, onConnect
10 changes: 3 additions & 7 deletions packages/sdk/src/db_connection_impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { TableCache, type Operation, type TableUpdate } from './table_cache.ts';
import { deepEqual, toPascalCase } from './utils.ts';
import { WebsocketDecompressAdapter } from './websocket_decompress_adapter.ts';
import type { WebsocketTestAdapter } from './websocket_test_adapter.ts';
import { Buffer } from 'buffer';

export {
AlgebraicType,
Expand Down Expand Up @@ -146,7 +147,7 @@ export class DBConnectionImpl<DBView = any, Reducers = any>
for (const update of rawTableUpdate.updates) {
let decompressed: ws.QueryUpdate;
if (update.tag === 'Brotli') {
const decompressedBuffer = decompress(new Buffer(update.value));
const decompressedBuffer = decompress(Buffer.from(update.value));
decompressed = ws.QueryUpdate.deserialize(
new BinaryReader(decompressedBuffer)
);
Expand Down Expand Up @@ -390,12 +391,7 @@ export class DBConnectionImpl<DBView = any, Reducers = any>
this.token = message.token;
}
this.clientAddress = message.address;
this.#emitter.emit(
'connect',
this.token,
this.identity,
this.clientAddress
);
this.#emitter.emit('connect', this, this.identity, this.token);
}
});
}
Expand Down
4 changes: 2 additions & 2 deletions packages/sdk/src/websocket_decompress_adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ export class WebsocketDecompressAdapter {
let decompressed: Uint8Array;
switch (buffer[0]) {
case 0:
decompressed = msg.data.slice(1);
decompressed = buffer.slice(1);
break;
case 1:
decompressed = decompress(new Buffer(buffer.slice(1)));
decompressed = decompress(Buffer.from(buffer.slice(1)));
break;
default:
throw new Error('Invalid message type');
Expand Down
6 changes: 5 additions & 1 deletion packages/test-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
"preview": "vite preview",
"spacetime:generate-bindings": "spacetime generate --lang typescript --out-dir src/module_bindings --project-path server",
"spacetime:start": "spacetime start server",
"spacetime:publish:local": "spacetime publish game --project-path server --server local",
"spacetime:publish": "spacetime publish game --project-path server --server testnet"
},
"workspaces": [
"packages/*"
Expand Down
10 changes: 7 additions & 3 deletions packages/test-app/server/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use spacetimedb::{reducer, table, Identity, ReducerContext, SpacetimeType, Table};

#[table(name = player)]
#[table(name = player, public)]
pub struct Player {
#[primary_key]
owner_id: String,
Expand All @@ -14,7 +14,7 @@ pub struct Point {
pub y: u16,
}

#[table(name = user)]
#[table(name = user, public)]
pub struct User {
#[primary_key]
pub identity: Identity,
Expand All @@ -23,5 +23,9 @@ pub struct User {

#[reducer]
pub fn create_player(ctx: &ReducerContext, name: String, location: Point) {
ctx.db.player().insert(Player { owner_id: ctx.sender.to_hex().to_string(), name, location });
ctx.db.player().insert(Player {
owner_id: ctx.sender.to_hex().to_string(),
name,
location,
});
}
32 changes: 26 additions & 6 deletions packages/test-app/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,38 +1,58 @@
import { DBConnection } from './module_bindings';
import { useState } from 'react';
import { useEffect, useState } from 'react';
import './App.css';
import { Identity } from '@clockworklabs/spacetimedb-sdk';

function App() {
const [connection] = useState<DBConnection>(
const [connection] = useState(() =>
DBConnection.builder()
.withUri('ws://localhost:3000')
.withModuleName('goldbreezycanid')
.withModuleName('game')
.onDisconnect(() => {
console.log('disconnected');
})
.onConnectError(() => {
console.log('client_error');
})
.onConnect((_, identity, _token) => {
.onConnect((conn, identity, _token) => {
console.log(
'Connected to SpacetimeDB with identity:',
identity.toHexString()
);

conn.subscriptionBuilder().subscribe(['SELECT * FROM player']);
})
.withCredentials([
Identity.fromString(
'49f2d472cabfbc7ded52ac1f93316750dc8ea162aac97cc52a340aed221b7ff3'
'93dda09db9a56d8fa6c024d843e805d8262191db3b4ba84c5efcd1ad451fed4e'
),
'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJoZXhfaWRlbnRpdHkiOiI0OWYyZDQ3MmNhYmZiYzdkZWQ1MmFjMWY5MzMxNjc1MGRjOGVhMTYyYWFjOTdjYzUyYTM0MGFlZDIyMWI3ZmYzIiwiaWF0IjoxNjgwMTkwNDc5fQ.KPz0DjrWb6I5c51wa71FGTgWz0Nh6CiNycM0ynmDDNkGjRxsci5cmiEjHQdYKyIeaG9MizSVPGlaDJ2Z7uctcg',
'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJoZXhfaWRlbnRpdHkiOiI5M2RkYTA5ZGI5YTU2ZDhmYTZjMDI0ZDg0M2U4MDVkODI2MjE5MWRiM2I0YmE4NGM1ZWZjZDFhZDQ1MWZlZDRlIiwiaWF0IjoxNzI4MzY3NDk0LCJleHAiOm51bGx9.ua3DQaiXo5i3Ye0okughs84PV9uZLCnov26zvCMG-3ibqGg6vH0uDDY6L-zDf8XiFgUqEIcvnJvuKLThPDipjQ',
])
.build()
);

useEffect(() => {
connection.db.player.onInsert(player => {
console.log(player);
});

setTimeout(() => {
console.log(Array.from(connection.db.player.iter()));
}, 5000);
}, [connection]);

return (
<div className="App">
<h1>Typescript SDK Test!</h1>
<p>{connection.identity?.toHexString()}</p>

<button
onClick={() =>
connection.reducers.createPlayer('Hello', { x: 10, y: 40 })
}
>
Update
</button>
</div>
);
}
Expand Down
10 changes: 6 additions & 4 deletions packages/test-app/src/module_bindings/create_player_reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ import {
SumTypeVariant,
// @ts-ignore
TableCache,
// @ts-ignore
deepEqual,
} from '@clockworklabs/spacetimedb-sdk';

// @ts-ignore
Expand All @@ -52,18 +54,18 @@ export namespace CreatePlayer {
* A function which returns this type represented as an AlgebraicType.
* This function is derived from the AlgebraicType used to generate this type.
*/
export function getAlgebraicType(): AlgebraicType {
export function getTypeScriptAlgebraicType(): AlgebraicType {
return AlgebraicType.createProductType([
new ProductTypeElement('name', AlgebraicType.createStringType()),
new ProductTypeElement('location', __Point.getAlgebraicType()),
new ProductTypeElement('location', __Point.getTypeScriptAlgebraicType()),
]);
}

export function serialize(writer: BinaryWriter, value: CreatePlayer): void {
CreatePlayer.getAlgebraicType().serialize(writer, value);
CreatePlayer.getTypeScriptAlgebraicType().serialize(writer, value);
}

export function deserialize(reader: BinaryReader): CreatePlayer {
return CreatePlayer.getAlgebraicType().deserialize(reader);
return CreatePlayer.getTypeScriptAlgebraicType().deserialize(reader);
}
}
10 changes: 6 additions & 4 deletions packages/test-app/src/module_bindings/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ import {
SumTypeVariant,
// @ts-ignore
TableCache,
// @ts-ignore
deepEqual,
} from '@clockworklabs/spacetimedb-sdk';

// Import and reexport all reducer arg types
Expand All @@ -58,19 +60,19 @@ const REMOTE_MODULE = {
tables: {
player: {
tableName: 'player',
rowType: Player.getAlgebraicType(),
rowType: Player.getTypeScriptAlgebraicType(),
primaryKey: 'owner_id',
},
user: {
tableName: 'user',
rowType: User.getAlgebraicType(),
rowType: User.getTypeScriptAlgebraicType(),
primaryKey: 'identity',
},
},
reducers: {
create_player: {
reducerName: 'create_player',
argsType: CreatePlayer.getAlgebraicType(),
argsType: CreatePlayer.getTypeScriptAlgebraicType(),
},
},
// Constructors which are used by the DBConnectionImpl to
Expand Down Expand Up @@ -98,7 +100,7 @@ export class RemoteReducers {
createPlayer(name: string, location: Point) {
const __args = { name, location };
let __writer = new BinaryWriter(1024);
CreatePlayer.getAlgebraicType().serialize(__writer, __args);
CreatePlayer.getTypeScriptAlgebraicType().serialize(__writer, __args);
let __argsBuffer = __writer.getBuffer();
this.connection.callReducer('create_player', __argsBuffer);
}
Expand Down
4 changes: 2 additions & 2 deletions packages/test-app/src/module_bindings/player_table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
// WILL NOT BE SAVED. MODIFY TABLES IN RUST INSTEAD.

import {
// @ts-ignore
deepEqual,
// @ts-ignore
Address,
// @ts-ignore
Expand Down Expand Up @@ -36,6 +34,8 @@ import {
SumTypeVariant,
// @ts-ignore
TableCache,
// @ts-ignore
deepEqual,
} from '@clockworklabs/spacetimedb-sdk';
import { Player } from './player_type';
// @ts-ignore
Expand Down
10 changes: 6 additions & 4 deletions packages/test-app/src/module_bindings/player_type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ import {
SumTypeVariant,
// @ts-ignore
TableCache,
// @ts-ignore
deepEqual,
} from '@clockworklabs/spacetimedb-sdk';
// @ts-ignore
import { Point as __Point } from './point_type';
Expand All @@ -52,19 +54,19 @@ export namespace Player {
* A function which returns this type represented as an AlgebraicType.
* This function is derived from the AlgebraicType used to generate this type.
*/
export function getAlgebraicType(): AlgebraicType {
export function getTypeScriptAlgebraicType(): AlgebraicType {
return AlgebraicType.createProductType([
new ProductTypeElement('ownerId', AlgebraicType.createStringType()),
new ProductTypeElement('name', AlgebraicType.createStringType()),
new ProductTypeElement('location', __Point.getAlgebraicType()),
new ProductTypeElement('location', __Point.getTypeScriptAlgebraicType()),
]);
}

export function serialize(writer: BinaryWriter, value: Player): void {
Player.getAlgebraicType().serialize(writer, value);
Player.getTypeScriptAlgebraicType().serialize(writer, value);
}

export function deserialize(reader: BinaryReader): Player {
return Player.getAlgebraicType().deserialize(reader);
return Player.getTypeScriptAlgebraicType().deserialize(reader);
}
}
8 changes: 5 additions & 3 deletions packages/test-app/src/module_bindings/point_type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ import {
SumTypeVariant,
// @ts-ignore
TableCache,
// @ts-ignore
deepEqual,
} from '@clockworklabs/spacetimedb-sdk';
export type Point = {
x: number;
Expand All @@ -48,18 +50,18 @@ export namespace Point {
* A function which returns this type represented as an AlgebraicType.
* This function is derived from the AlgebraicType used to generate this type.
*/
export function getAlgebraicType(): AlgebraicType {
export function getTypeScriptAlgebraicType(): AlgebraicType {
return AlgebraicType.createProductType([
new ProductTypeElement('x', AlgebraicType.createU16Type()),
new ProductTypeElement('y', AlgebraicType.createU16Type()),
]);
}

export function serialize(writer: BinaryWriter, value: Point): void {
Point.getAlgebraicType().serialize(writer, value);
Point.getTypeScriptAlgebraicType().serialize(writer, value);
}

export function deserialize(reader: BinaryReader): Point {
return Point.getAlgebraicType().deserialize(reader);
return Point.getTypeScriptAlgebraicType().deserialize(reader);
}
}
4 changes: 2 additions & 2 deletions packages/test-app/src/module_bindings/user_table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
// WILL NOT BE SAVED. MODIFY TABLES IN RUST INSTEAD.

import {
// @ts-ignore
deepEqual,
// @ts-ignore
Address,
// @ts-ignore
Expand Down Expand Up @@ -36,6 +34,8 @@ import {
SumTypeVariant,
// @ts-ignore
TableCache,
// @ts-ignore
deepEqual,
} from '@clockworklabs/spacetimedb-sdk';
import { User } from './user_type';
// @ts-ignore
Expand Down
8 changes: 5 additions & 3 deletions packages/test-app/src/module_bindings/user_type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ import {
SumTypeVariant,
// @ts-ignore
TableCache,
// @ts-ignore
deepEqual,
} from '@clockworklabs/spacetimedb-sdk';
export type User = {
identity: Identity;
Expand All @@ -48,18 +50,18 @@ export namespace User {
* A function which returns this type represented as an AlgebraicType.
* This function is derived from the AlgebraicType used to generate this type.
*/
export function getAlgebraicType(): AlgebraicType {
export function getTypeScriptAlgebraicType(): AlgebraicType {
return AlgebraicType.createProductType([
new ProductTypeElement('identity', AlgebraicType.createIdentityType()),
new ProductTypeElement('username', AlgebraicType.createStringType()),
]);
}

export function serialize(writer: BinaryWriter, value: User): void {
User.getAlgebraicType().serialize(writer, value);
User.getTypeScriptAlgebraicType().serialize(writer, value);
}

export function deserialize(reader: BinaryReader): User {
return User.getAlgebraicType().deserialize(reader);
return User.getTypeScriptAlgebraicType().deserialize(reader);
}
}

0 comments on commit 2f6c82c

Please sign in to comment.