spacetimedb 2.0.4 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.txt +2 -2
- package/dist/angular/index.cjs +9 -3
- package/dist/angular/index.cjs.map +1 -1
- package/dist/angular/index.mjs +9 -3
- package/dist/angular/index.mjs.map +1 -1
- package/dist/browser/angular/index.mjs +9 -3
- package/dist/browser/angular/index.mjs.map +1 -1
- package/dist/browser/react/index.mjs +62 -7
- package/dist/browser/react/index.mjs.map +1 -1
- package/dist/browser/svelte/index.mjs +9 -3
- package/dist/browser/svelte/index.mjs.map +1 -1
- package/dist/browser/vue/index.mjs +9 -3
- package/dist/browser/vue/index.mjs.map +1 -1
- package/dist/index.browser.mjs +481 -146
- package/dist/index.browser.mjs.map +1 -1
- package/dist/index.cjs +481 -146
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +481 -146
- package/dist/index.mjs.map +1 -1
- package/dist/lib/algebraic_type.d.ts.map +1 -1
- package/dist/lib/binary_reader.d.ts +1 -1
- package/dist/lib/binary_reader.d.ts.map +1 -1
- package/dist/lib/binary_writer.d.ts +2 -1
- package/dist/lib/binary_writer.d.ts.map +1 -1
- package/dist/lib/filter.d.ts +2 -1
- package/dist/lib/filter.d.ts.map +1 -1
- package/dist/lib/query.d.ts +10 -5
- package/dist/lib/query.d.ts.map +1 -1
- package/dist/lib/table.d.ts +12 -1
- package/dist/lib/table.d.ts.map +1 -1
- package/dist/min/index.browser.mjs +1 -1
- package/dist/min/index.browser.mjs.map +1 -1
- package/dist/min/react/index.mjs +1 -1
- package/dist/min/react/index.mjs.map +1 -1
- package/dist/min/sdk/index.browser.mjs +1 -1
- package/dist/min/sdk/index.browser.mjs.map +1 -1
- package/dist/react/index.cjs +62 -6
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.ts +1 -0
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.mjs +62 -7
- package/dist/react/index.mjs.map +1 -1
- package/dist/react/useProcedure.d.ts +4 -0
- package/dist/react/useProcedure.d.ts.map +1 -0
- package/dist/react/useTable.d.ts +2 -0
- package/dist/react/useTable.d.ts.map +1 -1
- package/dist/sdk/db_connection_builder.d.ts +3 -3
- package/dist/sdk/db_connection_builder.d.ts.map +1 -1
- package/dist/sdk/db_connection_impl.d.ts +3 -3
- package/dist/sdk/db_connection_impl.d.ts.map +1 -1
- package/dist/sdk/decompress.d.ts +1 -1
- package/dist/sdk/decompress.d.ts.map +1 -1
- package/dist/sdk/index.browser.mjs +477 -144
- package/dist/sdk/index.browser.mjs.map +1 -1
- package/dist/sdk/index.cjs +477 -144
- package/dist/sdk/index.cjs.map +1 -1
- package/dist/sdk/index.mjs +477 -144
- package/dist/sdk/index.mjs.map +1 -1
- package/dist/sdk/table_cache.d.ts +1 -0
- package/dist/sdk/table_cache.d.ts.map +1 -1
- package/dist/sdk/type_utils.d.ts +4 -1
- package/dist/sdk/type_utils.d.ts.map +1 -1
- package/dist/sdk/websocket_decompress_adapter.d.ts +5 -21
- package/dist/sdk/websocket_decompress_adapter.d.ts.map +1 -1
- package/dist/sdk/websocket_protocols.d.ts +6 -0
- package/dist/sdk/websocket_protocols.d.ts.map +1 -0
- package/dist/sdk/websocket_test_adapter.d.ts +14 -18
- package/dist/sdk/websocket_test_adapter.d.ts.map +1 -1
- package/dist/sdk/websocket_v3_frames.d.ts +9 -0
- package/dist/sdk/websocket_v3_frames.d.ts.map +1 -0
- package/dist/sdk/ws.d.ts +26 -1
- package/dist/sdk/ws.d.ts.map +1 -1
- package/dist/server/http_internal.d.ts.map +1 -1
- package/dist/server/index.d.ts +2 -1
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.mjs +76 -15
- package/dist/server/index.mjs.map +1 -1
- package/dist/server/runtime.d.ts +29 -2
- package/dist/server/runtime.d.ts.map +1 -1
- package/dist/svelte/index.cjs +9 -3
- package/dist/svelte/index.cjs.map +1 -1
- package/dist/svelte/index.mjs +9 -3
- package/dist/svelte/index.mjs.map +1 -1
- package/dist/tanstack/index.cjs +9 -3
- package/dist/tanstack/index.cjs.map +1 -1
- package/dist/tanstack/index.mjs +9 -3
- package/dist/tanstack/index.mjs.map +1 -1
- package/dist/vue/index.cjs +9 -3
- package/dist/vue/index.cjs.map +1 -1
- package/dist/vue/index.mjs +9 -3
- package/dist/vue/index.mjs.map +1 -1
- package/package.json +2 -2
- package/src/lib/algebraic_type.ts +5 -1
- package/src/lib/binary_reader.ts +5 -2
- package/src/lib/binary_writer.ts +7 -1
- package/src/lib/filter.ts +12 -1
- package/src/lib/query.ts +60 -19
- package/src/lib/table.ts +15 -2
- package/src/react/index.ts +1 -0
- package/src/react/useProcedure.ts +60 -0
- package/src/react/useTable.ts +22 -2
- package/src/sdk/db_connection_builder.ts +16 -7
- package/src/sdk/db_connection_impl.ts +404 -89
- package/src/sdk/decompress.ts +7 -23
- package/src/sdk/table_cache.ts +5 -5
- package/src/sdk/type_utils.ts +10 -1
- package/src/sdk/websocket_decompress_adapter.ts +15 -77
- package/src/sdk/websocket_protocols.ts +25 -0
- package/src/sdk/websocket_test_adapter.ts +65 -29
- package/src/sdk/websocket_v3_frames.ts +126 -0
- package/src/sdk/ws.ts +81 -3
- package/src/server/http_internal.ts +10 -1
- package/src/server/index.ts +2 -1
- package/src/server/runtime.ts +39 -1
- package/src/server/sys.d.ts +4 -0
- package/src/server/view.test-d.ts +4 -0
package/src/sdk/decompress.ts
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
export async function decompress(
|
|
2
|
-
buffer: Uint8Array
|
|
3
|
-
|
|
4
|
-
type: 'gzip',
|
|
2
|
+
buffer: Uint8Array<ArrayBuffer>,
|
|
3
|
+
type: CompressionFormat,
|
|
5
4
|
chunkSize: number = 128 * 1024 // 128KB
|
|
6
5
|
): Promise<Uint8Array> {
|
|
7
6
|
// Create a single ReadableStream to handle chunks
|
|
8
7
|
let offset = 0;
|
|
9
|
-
const readableStream = new ReadableStream({
|
|
8
|
+
const readableStream = new ReadableStream<BufferSource>({
|
|
10
9
|
pull(controller) {
|
|
11
10
|
if (offset < buffer.length) {
|
|
12
11
|
// Slice a chunk of the buffer and enqueue it
|
|
@@ -29,24 +28,9 @@ export async function decompress(
|
|
|
29
28
|
const decompressedStream = readableStream.pipeThrough(decompressionStream);
|
|
30
29
|
|
|
31
30
|
// Collect the decompressed chunks efficiently
|
|
32
|
-
const
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
let result: any;
|
|
36
|
-
|
|
37
|
-
while (!(result = await reader.read()).done) {
|
|
38
|
-
chunks.push(result.value);
|
|
39
|
-
totalLength += result.value.length;
|
|
31
|
+
const chunks = [];
|
|
32
|
+
for await (const chunk of decompressedStream) {
|
|
33
|
+
chunks.push(chunk);
|
|
40
34
|
}
|
|
41
|
-
|
|
42
|
-
// Allocate a single Uint8Array for the decompressed data
|
|
43
|
-
const decompressedArray = new Uint8Array(totalLength);
|
|
44
|
-
let chunkOffset = 0;
|
|
45
|
-
|
|
46
|
-
for (const chunk of chunks) {
|
|
47
|
-
decompressedArray.set(chunk, chunkOffset);
|
|
48
|
-
chunkOffset += chunk.length;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
return decompressedArray;
|
|
35
|
+
return new Blob(chunks).bytes();
|
|
52
36
|
}
|
package/src/sdk/table_cache.ts
CHANGED
|
@@ -66,6 +66,7 @@ export class TableCacheImpl<
|
|
|
66
66
|
TableName extends TableNamesOf<RemoteModule>,
|
|
67
67
|
> implements ClientTableCoreImplementable<RemoteModule, TableName>
|
|
68
68
|
{
|
|
69
|
+
private readonly hasPrimaryKey: boolean;
|
|
69
70
|
private rows: Map<
|
|
70
71
|
ComparablePrimitive,
|
|
71
72
|
[RowType<TableDefForTableName<RemoteModule, TableName>>, number]
|
|
@@ -83,6 +84,9 @@ export class TableCacheImpl<
|
|
|
83
84
|
this.tableDef = tableDef;
|
|
84
85
|
this.rows = new Map();
|
|
85
86
|
this.emitter = new EventEmitter();
|
|
87
|
+
this.hasPrimaryKey = Object.values(this.tableDef.columns).some(
|
|
88
|
+
col => col.columnMetadata.isPrimaryKey === true
|
|
89
|
+
);
|
|
86
90
|
// Build index views from the resolved runtime index metadata.
|
|
87
91
|
//
|
|
88
92
|
// We intentionally use `resolvedIndexes` rather than `indexes`:
|
|
@@ -281,11 +285,7 @@ export class TableCacheImpl<
|
|
|
281
285
|
return pendingCallbacks;
|
|
282
286
|
}
|
|
283
287
|
|
|
284
|
-
|
|
285
|
-
const hasPrimaryKey = Object.values(this.tableDef.columns).some(
|
|
286
|
-
col => col.columnMetadata.isPrimaryKey === true
|
|
287
|
-
);
|
|
288
|
-
if (hasPrimaryKey) {
|
|
288
|
+
if (this.hasPrimaryKey) {
|
|
289
289
|
const insertMap = new Map<
|
|
290
290
|
ComparablePrimitive,
|
|
291
291
|
[
|
package/src/sdk/type_utils.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import type { InferTypeOfRow } from '.';
|
|
1
|
+
import type { Infer, InferTypeOfRow } from '.';
|
|
2
2
|
import type { Prettify } from '../lib/type_util';
|
|
3
|
+
import type { UntypedProcedureDef } from './procedures';
|
|
3
4
|
import type { UntypedReducerDef } from './reducers';
|
|
4
5
|
|
|
5
6
|
export type IsEmptyObject<T> = [keyof T] extends [never] ? true : false;
|
|
@@ -8,3 +9,11 @@ export type MaybeParams<T> = IsEmptyObject<T> extends true ? [] : [params: T];
|
|
|
8
9
|
export type ParamsType<R extends UntypedReducerDef> = MaybeParams<
|
|
9
10
|
Prettify<InferTypeOfRow<R['params']>>
|
|
10
11
|
>;
|
|
12
|
+
|
|
13
|
+
export type ProcedureParamsType<P extends UntypedProcedureDef> = MaybeParams<
|
|
14
|
+
Prettify<InferTypeOfRow<P['params']>>
|
|
15
|
+
>;
|
|
16
|
+
|
|
17
|
+
export type ProcedureReturnType<P extends UntypedProcedureDef> = Infer<
|
|
18
|
+
P['returnType']
|
|
19
|
+
>;
|
|
@@ -1,17 +1,10 @@
|
|
|
1
1
|
import { decompress } from './decompress';
|
|
2
|
-
import {
|
|
2
|
+
import { openWebSocket, type WebSocketAdapter, type WebSocketArgs } from './ws';
|
|
3
3
|
|
|
4
|
-
export
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
set onclose(handler: (ev: CloseEvent) => void);
|
|
9
|
-
set onopen(handler: () => void);
|
|
10
|
-
set onmessage(handler: (msg: { data: Uint8Array }) => void);
|
|
11
|
-
set onerror(handler: (msg: ErrorEvent) => void);
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export class WebsocketDecompressAdapter implements WebsocketAdapter {
|
|
4
|
+
export class WebsocketDecompressAdapter implements WebSocketAdapter {
|
|
5
|
+
get protocol(): string {
|
|
6
|
+
return this.#ws.protocol;
|
|
7
|
+
}
|
|
15
8
|
set onclose(handler: (ev: CloseEvent) => void) {
|
|
16
9
|
this.#ws.onclose = handler;
|
|
17
10
|
}
|
|
@@ -30,16 +23,17 @@ export class WebsocketDecompressAdapter implements WebsocketAdapter {
|
|
|
30
23
|
|
|
31
24
|
#ws: WebSocket;
|
|
32
25
|
|
|
33
|
-
async #decompress(buffer: Uint8Array): Promise<Uint8Array> {
|
|
26
|
+
async #decompress(buffer: Uint8Array<ArrayBuffer>): Promise<Uint8Array> {
|
|
34
27
|
const tag = buffer[0];
|
|
35
28
|
const data = buffer.subarray(1);
|
|
36
29
|
switch (tag) {
|
|
37
30
|
case 0:
|
|
38
31
|
return data;
|
|
39
32
|
case 1:
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
33
|
+
// Some runtimes support brotli, but it's not yet defined in `lib.dom.d.ts`.
|
|
34
|
+
// We assert runtime support in `DbConnectionBuilder.withCompression`, so
|
|
35
|
+
// this cast is safe.
|
|
36
|
+
return await decompress(data, 'brotli' as CompressionFormat);
|
|
43
37
|
case 2:
|
|
44
38
|
return await decompress(data, 'gzip');
|
|
45
39
|
default:
|
|
@@ -49,7 +43,7 @@ export class WebsocketDecompressAdapter implements WebsocketAdapter {
|
|
|
49
43
|
}
|
|
50
44
|
}
|
|
51
45
|
|
|
52
|
-
send(msg: Uint8Array): void {
|
|
46
|
+
send(msg: Uint8Array<ArrayBuffer>): void {
|
|
53
47
|
this.#ws.send(msg);
|
|
54
48
|
}
|
|
55
49
|
|
|
@@ -58,68 +52,12 @@ export class WebsocketDecompressAdapter implements WebsocketAdapter {
|
|
|
58
52
|
}
|
|
59
53
|
|
|
60
54
|
constructor(ws: WebSocket) {
|
|
61
|
-
ws.binaryType = 'arraybuffer';
|
|
62
|
-
|
|
63
55
|
this.#ws = ws;
|
|
64
56
|
}
|
|
65
57
|
|
|
66
|
-
static async
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
authToken,
|
|
71
|
-
compression,
|
|
72
|
-
lightMode,
|
|
73
|
-
confirmedReads,
|
|
74
|
-
}: {
|
|
75
|
-
url: URL;
|
|
76
|
-
wsProtocol: string;
|
|
77
|
-
nameOrAddress: string;
|
|
78
|
-
authToken?: string;
|
|
79
|
-
compression: 'gzip' | 'none';
|
|
80
|
-
lightMode: boolean;
|
|
81
|
-
confirmedReads?: boolean;
|
|
82
|
-
}): Promise<WebsocketDecompressAdapter> {
|
|
83
|
-
const headers = new Headers();
|
|
84
|
-
|
|
85
|
-
const WS = await resolveWS();
|
|
86
|
-
|
|
87
|
-
// We swap our original token to a shorter-lived token
|
|
88
|
-
// to avoid sending the original via query params.
|
|
89
|
-
let temporaryAuthToken: string | undefined = undefined;
|
|
90
|
-
if (authToken) {
|
|
91
|
-
headers.set('Authorization', `Bearer ${authToken}`);
|
|
92
|
-
const tokenUrl = new URL('v1/identity/websocket-token', url);
|
|
93
|
-
tokenUrl.protocol = url.protocol === 'wss:' ? 'https:' : 'http:';
|
|
94
|
-
|
|
95
|
-
const response = await fetch(tokenUrl, { method: 'POST', headers });
|
|
96
|
-
if (response.ok) {
|
|
97
|
-
const { token } = await response.json();
|
|
98
|
-
temporaryAuthToken = token;
|
|
99
|
-
} else {
|
|
100
|
-
return Promise.reject(
|
|
101
|
-
new Error(`Failed to verify token: ${response.statusText}`)
|
|
102
|
-
);
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
const databaseUrl = new URL(`v1/database/${nameOrAddress}/subscribe`, url);
|
|
107
|
-
if (temporaryAuthToken) {
|
|
108
|
-
databaseUrl.searchParams.set('token', temporaryAuthToken);
|
|
109
|
-
}
|
|
110
|
-
databaseUrl.searchParams.set(
|
|
111
|
-
'compression',
|
|
112
|
-
compression === 'gzip' ? 'Gzip' : 'None'
|
|
113
|
-
);
|
|
114
|
-
if (lightMode) {
|
|
115
|
-
databaseUrl.searchParams.set('light', 'true');
|
|
116
|
-
}
|
|
117
|
-
if (confirmedReads !== undefined) {
|
|
118
|
-
databaseUrl.searchParams.set('confirmed', confirmedReads.toString());
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
const ws = new WS(databaseUrl.toString(), wsProtocol);
|
|
122
|
-
|
|
123
|
-
return new WebsocketDecompressAdapter(ws);
|
|
58
|
+
static async openWebSocket(
|
|
59
|
+
args: WebSocketArgs
|
|
60
|
+
): Promise<WebsocketDecompressAdapter> {
|
|
61
|
+
return new WebsocketDecompressAdapter(await openWebSocket(args));
|
|
124
62
|
}
|
|
125
63
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { stdbLogger } from './logger.ts';
|
|
2
|
+
|
|
3
|
+
export const V2_WS_PROTOCOL = 'v2.bsatn.spacetimedb';
|
|
4
|
+
export const V3_WS_PROTOCOL = 'v3.bsatn.spacetimedb';
|
|
5
|
+
export const PREFERRED_WS_PROTOCOLS = [V3_WS_PROTOCOL, V2_WS_PROTOCOL] as const;
|
|
6
|
+
|
|
7
|
+
export type NegotiatedWsProtocol =
|
|
8
|
+
| typeof V2_WS_PROTOCOL
|
|
9
|
+
| typeof V3_WS_PROTOCOL;
|
|
10
|
+
|
|
11
|
+
export function normalizeWsProtocol(protocol: string): NegotiatedWsProtocol {
|
|
12
|
+
if (protocol === V3_WS_PROTOCOL) {
|
|
13
|
+
return V3_WS_PROTOCOL;
|
|
14
|
+
}
|
|
15
|
+
// We treat an empty negotiated subprotocol as legacy v2 for compatibility.
|
|
16
|
+
if (protocol === '' || protocol === V2_WS_PROTOCOL) {
|
|
17
|
+
return V2_WS_PROTOCOL;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
stdbLogger(
|
|
21
|
+
'warn',
|
|
22
|
+
`Unexpected websocket subprotocol "${protocol}", falling back to ${V2_WS_PROTOCOL}.`
|
|
23
|
+
);
|
|
24
|
+
return V2_WS_PROTOCOL;
|
|
25
|
+
}
|
|
@@ -1,64 +1,100 @@
|
|
|
1
|
-
import
|
|
1
|
+
import BinaryReader from '../lib/binary_reader.ts';
|
|
2
|
+
import BinaryWriter from '../lib/binary_writer.ts';
|
|
2
3
|
import { ClientMessage, ServerMessage } from './client_api/types';
|
|
3
|
-
import type {
|
|
4
|
+
import type { WebSocketAdapter, WebSocketFactory } from './ws';
|
|
5
|
+
import { PREFERRED_WS_PROTOCOLS, V3_WS_PROTOCOL } from './websocket_protocols';
|
|
6
|
+
import {
|
|
7
|
+
decodeClientMessagesV3,
|
|
8
|
+
encodeServerMessagesV3,
|
|
9
|
+
} from './websocket_v3_frames.ts';
|
|
4
10
|
|
|
5
|
-
class WebsocketTestAdapter implements
|
|
6
|
-
|
|
7
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
8
|
-
onopen!: () => void;
|
|
9
|
-
onmessage: any;
|
|
10
|
-
onerror: any;
|
|
11
|
+
class WebsocketTestAdapter implements WebSocketAdapter {
|
|
12
|
+
protocol: string = '';
|
|
11
13
|
|
|
12
|
-
messageQueue:
|
|
14
|
+
messageQueue: Uint8Array<ArrayBuffer>[];
|
|
13
15
|
outgoingMessages: ClientMessage[];
|
|
14
16
|
closed: boolean;
|
|
17
|
+
supportedProtocols: string[];
|
|
18
|
+
|
|
19
|
+
#onclose: (ev: CloseEvent) => void = () => {};
|
|
20
|
+
#onopen: () => void = () => {};
|
|
21
|
+
#onmessage: (msg: { data: Uint8Array }) => void = () => {};
|
|
15
22
|
|
|
16
23
|
constructor() {
|
|
17
24
|
this.messageQueue = [];
|
|
18
25
|
this.outgoingMessages = [];
|
|
19
26
|
this.closed = false;
|
|
27
|
+
this.supportedProtocols = [...PREFERRED_WS_PROTOCOLS];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
set onclose(handler: (ev: CloseEvent) => void) {
|
|
31
|
+
this.#onclose = handler;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
set onopen(handler: () => void) {
|
|
35
|
+
this.#onopen = handler;
|
|
20
36
|
}
|
|
21
37
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
38
|
+
set onmessage(handler: (msg: { data: Uint8Array }) => void) {
|
|
39
|
+
this.#onmessage = handler;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
set onerror(_handler: (msg: ErrorEvent) => void) {}
|
|
43
|
+
|
|
44
|
+
send(message: Uint8Array<ArrayBuffer>): void {
|
|
45
|
+
const rawMessage = message.slice();
|
|
46
|
+
const outgoingMessages =
|
|
47
|
+
this.protocol === V3_WS_PROTOCOL
|
|
48
|
+
? decodeClientMessagesV3(rawMessage)
|
|
49
|
+
: [rawMessage];
|
|
50
|
+
|
|
51
|
+
for (const outgoingMessage of outgoingMessages) {
|
|
52
|
+
this.outgoingMessages.push(
|
|
53
|
+
ClientMessage.deserialize(new BinaryReader(outgoingMessage))
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
this.messageQueue.push(rawMessage);
|
|
27
57
|
}
|
|
28
58
|
|
|
29
59
|
close(): void {
|
|
30
60
|
this.closed = true;
|
|
31
|
-
this
|
|
61
|
+
this.#onclose({
|
|
62
|
+
code: 1000,
|
|
63
|
+
reason: 'normal closure',
|
|
64
|
+
wasClean: true,
|
|
65
|
+
} as CloseEvent);
|
|
32
66
|
}
|
|
33
67
|
|
|
34
68
|
acceptConnection(): void {
|
|
35
|
-
this
|
|
69
|
+
this.#onopen();
|
|
36
70
|
}
|
|
37
71
|
|
|
38
72
|
sendToClient(message: ServerMessage): void {
|
|
39
73
|
const writer = new BinaryWriter(1024);
|
|
40
74
|
ServerMessage.serialize(writer, message);
|
|
41
|
-
const rawBytes = writer.getBuffer();
|
|
75
|
+
const rawBytes = writer.getBuffer().slice();
|
|
42
76
|
// The brotli library's `compress` is somehow broken: it returns `null` for some inputs.
|
|
43
77
|
// See https://github.com/foliojs/brotli.js/issues/36, which is closed but not actually fixed.
|
|
44
78
|
// So we send the uncompressed data here, and in `spacetimedb.ts`,
|
|
45
79
|
// if compression fails, we treat the raw message as having been uncompressed all along.
|
|
46
80
|
// const data = compress(rawBytes);
|
|
47
|
-
|
|
81
|
+
const outboundData =
|
|
82
|
+
this.protocol === V3_WS_PROTOCOL
|
|
83
|
+
? encodeServerMessagesV3(writer, [rawBytes]).slice()
|
|
84
|
+
: rawBytes;
|
|
85
|
+
this.#onmessage({ data: outboundData });
|
|
48
86
|
}
|
|
49
87
|
|
|
50
|
-
async
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
}): Promise<WebsocketTestAdapter> {
|
|
88
|
+
openWebSocket: WebSocketFactory = async ({ wsProtocol }) => {
|
|
89
|
+
const negotiatedProtocol = wsProtocol.find(protocol =>
|
|
90
|
+
this.supportedProtocols.includes(protocol)
|
|
91
|
+
);
|
|
92
|
+
if (!negotiatedProtocol) {
|
|
93
|
+
throw new Error('No compatible websocket protocol');
|
|
94
|
+
}
|
|
95
|
+
this.protocol = negotiatedProtocol;
|
|
59
96
|
return this;
|
|
60
|
-
}
|
|
97
|
+
};
|
|
61
98
|
}
|
|
62
99
|
|
|
63
|
-
export type { WebsocketTestAdapter };
|
|
64
100
|
export default WebsocketTestAdapter;
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import BinaryReader from '../lib/binary_reader.ts';
|
|
2
|
+
import BinaryWriter from '../lib/binary_writer.ts';
|
|
3
|
+
import { ClientMessage, ServerMessage } from './client_api/types';
|
|
4
|
+
|
|
5
|
+
// v3 is only a transport framing convention. The payload is one or more
|
|
6
|
+
// already-encoded v2 websocket messages concatenated back-to-back, so these
|
|
7
|
+
// helpers intentionally operate on raw bytes.
|
|
8
|
+
const EMPTY_V3_PAYLOAD_ERR =
|
|
9
|
+
'v3 websocket payloads must contain at least one message';
|
|
10
|
+
|
|
11
|
+
function ensureMessages(messages: readonly Uint8Array[]): void {
|
|
12
|
+
if (messages.length === 0) {
|
|
13
|
+
throw new RangeError(EMPTY_V3_PAYLOAD_ERR);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function ensureMessageCount(
|
|
18
|
+
messages: readonly Uint8Array[],
|
|
19
|
+
messageCount: number
|
|
20
|
+
): void {
|
|
21
|
+
ensureMessages(messages);
|
|
22
|
+
if (messageCount < 1 || messageCount > messages.length) {
|
|
23
|
+
throw new RangeError(
|
|
24
|
+
`v3 websocket payload requested ${messageCount} messages from ${messages.length}`
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function concatenateMessagesV3(
|
|
30
|
+
writer: BinaryWriter,
|
|
31
|
+
messages: readonly Uint8Array<ArrayBuffer>[],
|
|
32
|
+
messageCount: number = messages.length
|
|
33
|
+
): Uint8Array<ArrayBuffer> {
|
|
34
|
+
ensureMessageCount(messages, messageCount);
|
|
35
|
+
writer.clear();
|
|
36
|
+
for (let i = 0; i < messageCount; i++) {
|
|
37
|
+
writer.writeBytes(messages[i]!);
|
|
38
|
+
}
|
|
39
|
+
return writer.getBuffer();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function splitMessagesV3(
|
|
43
|
+
reader: BinaryReader,
|
|
44
|
+
data: Uint8Array<ArrayBuffer>,
|
|
45
|
+
deserialize: (reader: BinaryReader) => unknown
|
|
46
|
+
): Uint8Array<ArrayBuffer>[] {
|
|
47
|
+
reader.reset(data);
|
|
48
|
+
if (reader.remaining === 0) {
|
|
49
|
+
throw new RangeError(EMPTY_V3_PAYLOAD_ERR);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const messages: Uint8Array<ArrayBuffer>[] = [];
|
|
53
|
+
while (reader.remaining > 0) {
|
|
54
|
+
const startOffset = reader.offset;
|
|
55
|
+
deserialize(reader);
|
|
56
|
+
messages.push(data.subarray(startOffset, reader.offset));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return messages;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function countClientMessagesForV3Frame(
|
|
63
|
+
messages: readonly Uint8Array<ArrayBuffer>[],
|
|
64
|
+
maxFrameBytes: number
|
|
65
|
+
): number {
|
|
66
|
+
ensureMessages(messages);
|
|
67
|
+
|
|
68
|
+
const firstMessage = messages[0]!;
|
|
69
|
+
if (firstMessage.length > maxFrameBytes) {
|
|
70
|
+
return 1;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
let count = 1;
|
|
74
|
+
let frameSize = firstMessage.length;
|
|
75
|
+
while (count < messages.length) {
|
|
76
|
+
const nextMessage = messages[count]!;
|
|
77
|
+
const nextFrameSize = frameSize + nextMessage.length;
|
|
78
|
+
if (nextFrameSize > maxFrameBytes) {
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
81
|
+
frameSize = nextFrameSize;
|
|
82
|
+
count += 1;
|
|
83
|
+
}
|
|
84
|
+
return count;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function encodeClientMessagesV3(
|
|
88
|
+
writer: BinaryWriter,
|
|
89
|
+
messages: readonly Uint8Array<ArrayBuffer>[],
|
|
90
|
+
messageCount: number = messages.length
|
|
91
|
+
): Uint8Array<ArrayBuffer> {
|
|
92
|
+
return concatenateMessagesV3(writer, messages, messageCount);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function decodeClientMessagesV3(
|
|
96
|
+
data: Uint8Array<ArrayBuffer>
|
|
97
|
+
): Uint8Array<ArrayBuffer>[] {
|
|
98
|
+
return splitMessagesV3(new BinaryReader(data), data, reader =>
|
|
99
|
+
ClientMessage.deserialize(reader)
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function encodeServerMessagesV3(
|
|
104
|
+
writer: BinaryWriter,
|
|
105
|
+
messages: readonly Uint8Array<ArrayBuffer>[]
|
|
106
|
+
): Uint8Array<ArrayBuffer> {
|
|
107
|
+
return concatenateMessagesV3(writer, messages);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function forEachServerMessageV3(
|
|
111
|
+
reader: BinaryReader,
|
|
112
|
+
data: Uint8Array,
|
|
113
|
+
visit: (message: ServerMessage) => void
|
|
114
|
+
): number {
|
|
115
|
+
reader.reset(data);
|
|
116
|
+
if (reader.remaining === 0) {
|
|
117
|
+
throw new RangeError(EMPTY_V3_PAYLOAD_ERR);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
let count = 0;
|
|
121
|
+
while (reader.remaining > 0) {
|
|
122
|
+
visit(ServerMessage.deserialize(reader));
|
|
123
|
+
count += 1;
|
|
124
|
+
}
|
|
125
|
+
return count;
|
|
126
|
+
}
|
package/src/sdk/ws.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { stdbLogger } from './logger';
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
async function resolveWS(): Promise<typeof WebSocket> {
|
|
4
4
|
// Browser or Node >= 22 (or any env that exposes global WebSocket)
|
|
5
|
-
if (typeof
|
|
6
|
-
return
|
|
5
|
+
if (typeof WebSocket !== 'undefined') {
|
|
6
|
+
return WebSocket;
|
|
7
7
|
}
|
|
8
8
|
|
|
9
9
|
// Node without a global WebSocket: lazily load undici's polyfill.
|
|
@@ -25,3 +25,81 @@ export async function resolveWS(): Promise<typeof WebSocket> {
|
|
|
25
25
|
throw err;
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
|
+
|
|
29
|
+
export interface WebSocketAdapter {
|
|
30
|
+
readonly protocol: string;
|
|
31
|
+
send(msg: Uint8Array<ArrayBuffer>): void;
|
|
32
|
+
close(): void;
|
|
33
|
+
|
|
34
|
+
set onclose(handler: (ev: CloseEvent) => void);
|
|
35
|
+
set onopen(handler: () => void);
|
|
36
|
+
set onmessage(handler: (msg: { data: Uint8Array }) => void);
|
|
37
|
+
set onerror(handler: (msg: ErrorEvent) => void);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface WebSocketArgs {
|
|
41
|
+
url: URL;
|
|
42
|
+
wsProtocol: string[];
|
|
43
|
+
nameOrAddress: string;
|
|
44
|
+
authToken?: string;
|
|
45
|
+
compression: 'gzip' | 'brotli' | 'none';
|
|
46
|
+
lightMode: boolean;
|
|
47
|
+
confirmedReads?: boolean;
|
|
48
|
+
}
|
|
49
|
+
export type WebSocketFactory = (
|
|
50
|
+
args: WebSocketArgs
|
|
51
|
+
) => Promise<WebSocketAdapter>;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Open a WebSocket to the database specified by the given `WebSocketArgs`.
|
|
55
|
+
* @returns a WebSocket with `binaryType` set to `arraybuffer`.
|
|
56
|
+
*/
|
|
57
|
+
export async function openWebSocket({
|
|
58
|
+
url,
|
|
59
|
+
nameOrAddress,
|
|
60
|
+
wsProtocol,
|
|
61
|
+
authToken,
|
|
62
|
+
compression,
|
|
63
|
+
lightMode,
|
|
64
|
+
confirmedReads,
|
|
65
|
+
}: WebSocketArgs): Promise<WebSocket> {
|
|
66
|
+
const headers = new Headers();
|
|
67
|
+
|
|
68
|
+
const WS = await resolveWS();
|
|
69
|
+
|
|
70
|
+
// We swap our original token to a shorter-lived token
|
|
71
|
+
// to avoid sending the original via query params.
|
|
72
|
+
let temporaryAuthToken: string | undefined;
|
|
73
|
+
if (authToken) {
|
|
74
|
+
headers.set('Authorization', `Bearer ${authToken}`);
|
|
75
|
+
const tokenUrl = new URL('v1/identity/websocket-token', url);
|
|
76
|
+
tokenUrl.protocol = url.protocol === 'wss:' ? 'https:' : 'http:';
|
|
77
|
+
|
|
78
|
+
const response = await fetch(tokenUrl, { method: 'POST', headers });
|
|
79
|
+
if (response.ok) {
|
|
80
|
+
const { token } = await response.json();
|
|
81
|
+
temporaryAuthToken = token;
|
|
82
|
+
} else {
|
|
83
|
+
throw new Error(`Failed to verify token: ${response.statusText}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const databaseUrl = new URL(`v1/database/${nameOrAddress}/subscribe`, url);
|
|
88
|
+
if (temporaryAuthToken) {
|
|
89
|
+
databaseUrl.searchParams.set('token', temporaryAuthToken);
|
|
90
|
+
}
|
|
91
|
+
databaseUrl.searchParams.set(
|
|
92
|
+
'compression',
|
|
93
|
+
{ gzip: 'Gzip', brotli: 'Brotli', none: 'None' }[compression] ?? 'None'
|
|
94
|
+
);
|
|
95
|
+
if (lightMode) {
|
|
96
|
+
databaseUrl.searchParams.set('light', 'true');
|
|
97
|
+
}
|
|
98
|
+
if (confirmedReads !== undefined) {
|
|
99
|
+
databaseUrl.searchParams.set('confirmed', confirmedReads.toString());
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const ws = new WS(databaseUrl.toString(), wsProtocol);
|
|
103
|
+
ws.binaryType = 'arraybuffer';
|
|
104
|
+
return ws;
|
|
105
|
+
}
|
|
@@ -27,6 +27,15 @@ export interface ResponseInit {
|
|
|
27
27
|
const textEncoder = new TextEncoder();
|
|
28
28
|
const textDecoder = new TextDecoder('utf-8' /* { fatal: true } */);
|
|
29
29
|
|
|
30
|
+
function deserializeHeaders(headers: HttpHeaders): Headers {
|
|
31
|
+
return new Headers(
|
|
32
|
+
headers.entries.map(({ name, value }): [string, string] => [
|
|
33
|
+
name,
|
|
34
|
+
textDecoder.decode(value),
|
|
35
|
+
])
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
30
39
|
const makeResponse = Symbol('makeResponse');
|
|
31
40
|
|
|
32
41
|
// based on deno's type of the same name
|
|
@@ -187,7 +196,7 @@ function fetch(url: URL | string, init: RequestOptions = {}) {
|
|
|
187
196
|
url: uri,
|
|
188
197
|
status: response.code,
|
|
189
198
|
statusText: status(response.code),
|
|
190
|
-
headers:
|
|
199
|
+
headers: deserializeHeaders(response.headers),
|
|
191
200
|
aborted: false,
|
|
192
201
|
});
|
|
193
202
|
}
|
package/src/server/index.ts
CHANGED
|
@@ -8,7 +8,7 @@ export {
|
|
|
8
8
|
export { CaseConversionPolicy } from '../lib/autogen/types';
|
|
9
9
|
export { table } from '../lib/table';
|
|
10
10
|
export { SenderError, SpacetimeHostError, errors } from './errors';
|
|
11
|
-
export type { Reducer, ReducerCtx } from '../lib/reducers';
|
|
11
|
+
export type { Reducer, ReducerCtx, JwtClaims, AuthCtx } from '../lib/reducers';
|
|
12
12
|
export type { ReducerExport } from './reducers';
|
|
13
13
|
export { type DbView } from './db_view';
|
|
14
14
|
export * from './query';
|
|
@@ -21,5 +21,6 @@ export { toCamelCase } from '../lib/util';
|
|
|
21
21
|
export type { Uuid } from '../lib/uuid';
|
|
22
22
|
export type { Random } from './rng';
|
|
23
23
|
export type { ViewExport, ViewCtx, AnonymousViewCtx } from './views';
|
|
24
|
+
export { Range, type Bound } from './range';
|
|
24
25
|
|
|
25
26
|
import './polyfills'; // Ensure polyfills are loaded
|