-
Notifications
You must be signed in to change notification settings - Fork 4
/
client.ts
388 lines (335 loc) · 14.4 KB
/
client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import { WebSocket } from "@libsql/isomorphic-ws";
import type { ProtocolVersion, ProtocolEncoding } from "../client.js";
import { Client } from "../client.js";
import {
readJsonObject, writeJsonObject, readProtobufMessage, writeProtobufMessage,
} from "../encoding/index.js";
import {
ClientError, ProtoError, ClosedError, WebSocketError, ProtocolVersionError,
InternalError, MisuseError,
} from "../errors.js";
import { IdAlloc } from "../id_alloc.js";
import { errorFromProto } from "../result.js";
import { Sql, SqlOwner } from "../sql.js";
import { impossible } from "../util.js";
import type * as proto from "./proto.js";
import { WsStream } from "./stream.js";
import { ClientMsg as json_ClientMsg } from "./json_encode.js";
import { ClientMsg as protobuf_ClientMsg } from "./protobuf_encode.js";
import { ServerMsg as json_ServerMsg } from "./json_decode.js";
import { ServerMsg as protobuf_ServerMsg } from "./protobuf_decode.js";
export type Subprotocol = {
version: ProtocolVersion,
encoding: ProtocolEncoding,
};
export const subprotocolsV2: Map<string, Subprotocol> = new Map([
["hrana2", {version: 2, encoding: "json"}],
["hrana1", {version: 1, encoding: "json"}],
]);
export const subprotocolsV3: Map<string, Subprotocol> = new Map([
["hrana3-protobuf", {version: 3, encoding: "protobuf"}],
["hrana3", {version: 3, encoding: "json"}],
["hrana2", {version: 2, encoding: "json"}],
["hrana1", {version: 1, encoding: "json"}],
]);
/** A client for the Hrana protocol over a WebSocket. */
export class WsClient extends Client implements SqlOwner {
#socket: WebSocket;
// List of callbacks that we queue until the socket transitions from the CONNECTING to the OPEN state.
#openCallbacks: Array<OpenCallbacks>;
// Have we already transitioned from CONNECTING to OPEN and fired the callbacks in #openCallbacks?
#opened: boolean;
// Stores the error that caused us to close the client (and the socket). If we are not closed, this is
// `undefined`.
#closed: Error | undefined;
// Have we received a response to our "hello" from the server?
#recvdHello: boolean;
// Subprotocol negotiated with the server. It is only available after the socket transitions to the OPEN
// state.
#subprotocol: Subprotocol | undefined;
// Has the `getVersion()` function been called? This is only used to validate that the API is used
// correctly.
#getVersionCalled: boolean;
// A map from request id to the responses that we expect to receive from the server.
#responseMap: Map<number, ResponseState>;
// An allocator of request ids.
#requestIdAlloc: IdAlloc;
// An allocator of stream ids.
/** @private */
_streamIdAlloc: IdAlloc;
// An allocator of cursor ids.
/** @private */
_cursorIdAlloc: IdAlloc;
// An allocator of SQL text ids.
#sqlIdAlloc: IdAlloc;
/** @private */
constructor(socket: WebSocket, jwt: string | undefined) {
super();
this.#socket = socket;
this.#openCallbacks = [];
this.#opened = false;
this.#closed = undefined;
this.#recvdHello = false;
this.#subprotocol = undefined;
this.#getVersionCalled = false;
this.#responseMap = new Map();
this.#requestIdAlloc = new IdAlloc();
this._streamIdAlloc = new IdAlloc();
this._cursorIdAlloc = new IdAlloc();
this.#sqlIdAlloc = new IdAlloc();
this.#socket.binaryType = "arraybuffer";
this.#socket.addEventListener("open", () => this.#onSocketOpen());
this.#socket.addEventListener("close", (event) => this.#onSocketClose(event));
this.#socket.addEventListener("error", (event) => this.#onSocketError(event));
this.#socket.addEventListener("message", (event) => this.#onSocketMessage(event));
this.#send({type: "hello", jwt});
}
// Send (or enqueue to send) a message to the server.
#send(msg: proto.ClientMsg): void {
if (this.#closed !== undefined) {
throw new InternalError("Trying to send a message on a closed client");
}
if (this.#opened) {
this.#sendToSocket(msg);
} else {
const openCallback = () => this.#sendToSocket(msg);
const errorCallback = () => undefined;
this.#openCallbacks.push({openCallback, errorCallback});
}
}
// The socket transitioned from CONNECTING to OPEN
#onSocketOpen(): void {
const protocol = this.#socket.protocol;
if (protocol === undefined) {
this.#setClosed(new ClientError(
"The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket " +
"implementation provided by the environment is broken. If you are using Miniflare 2, " +
"please update to Miniflare 3, which fixes this problem."
));
return;
} else if (protocol === "") {
this.#subprotocol = {version: 1, encoding: "json"};
} else {
this.#subprotocol = subprotocolsV3.get(protocol);
if (this.#subprotocol === undefined) {
this.#setClosed(new ProtoError(
`Unrecognized WebSocket subprotocol: ${JSON.stringify(protocol)}`,
));
return;
}
}
for (const callbacks of this.#openCallbacks) {
callbacks.openCallback();
}
this.#openCallbacks.length = 0;
this.#opened = true;
}
#sendToSocket(msg: proto.ClientMsg): void {
const encoding = this.#subprotocol!.encoding;
if (encoding === "json") {
const jsonMsg = writeJsonObject(msg, json_ClientMsg);
this.#socket.send(jsonMsg);
} else if (encoding === "protobuf") {
const protobufMsg = writeProtobufMessage(msg, protobuf_ClientMsg);
this.#socket.send(protobufMsg);
} else {
throw impossible(encoding, "Impossible encoding");
}
}
/** Get the protocol version negotiated with the server, possibly waiting until the socket is open. */
override getVersion(): Promise<ProtocolVersion> {
return new Promise((versionCallback, errorCallback) => {
this.#getVersionCalled = true;
if (this.#closed !== undefined) {
errorCallback(this.#closed);
} else if (!this.#opened) {
const openCallback = () => versionCallback(this.#subprotocol!.version);
this.#openCallbacks.push({openCallback, errorCallback});
} else {
versionCallback(this.#subprotocol!.version);
}
});
}
// Make sure that the negotiated version is at least `minVersion`.
/** @private */
override _ensureVersion(minVersion: ProtocolVersion, feature: string): void {
if (this.#subprotocol === undefined || !this.#getVersionCalled) {
throw new ProtocolVersionError(
`${feature} is supported only on protocol version ${minVersion} and higher, ` +
"but the version supported by the WebSocket server is not yet known. " +
"Use Client.getVersion() to wait until the version is available.",
);
} else if (this.#subprotocol.version < minVersion) {
throw new ProtocolVersionError(
`${feature} is supported on protocol version ${minVersion} and higher, ` +
`but the WebSocket server only supports version ${this.#subprotocol.version}`
);
}
}
// Send a request to the server and invoke a callback when we get the response.
/** @private */
_sendRequest(request: proto.Request, callbacks: ResponseCallbacks) {
if (this.#closed !== undefined) {
callbacks.errorCallback(new ClosedError("Client is closed", this.#closed));
return;
}
const requestId = this.#requestIdAlloc.alloc();
this.#responseMap.set(requestId, {...callbacks, type: request.type});
this.#send({type: "request", requestId, request});
}
// The socket encountered an error.
#onSocketError(event: Event | WebSocket.ErrorEvent): void {
const eventMessage = (event as {message?: string}).message;
const message = eventMessage ?? "WebSocket was closed due to an error";
this.#setClosed(new WebSocketError(message));
}
// The socket was closed.
#onSocketClose(event: WebSocket.CloseEvent): void {
let message = `WebSocket was closed with code ${event.code}`;
if (event.reason) {
message += `: ${event.reason}`;
}
this.#setClosed(new WebSocketError(message));
}
// Close the client with the given error.
#setClosed(error: Error): void {
if (this.#closed !== undefined) {
return;
}
this.#closed = error;
for (const callbacks of this.#openCallbacks) {
callbacks.errorCallback(error);
}
this.#openCallbacks.length = 0;
for (const [requestId, responseState] of this.#responseMap.entries()) {
responseState.errorCallback(error);
this.#requestIdAlloc.free(requestId);
}
this.#responseMap.clear();
this.#socket.close();
}
// We received a message from the socket.
#onSocketMessage(event: WebSocket.MessageEvent): void {
if (this.#closed !== undefined) {
return;
}
try {
let msg: proto.ServerMsg;
const encoding = this.#subprotocol!.encoding;
if (encoding === "json") {
if (typeof event.data !== "string") {
this.#socket.close(3003, "Only text messages are accepted with JSON encoding");
this.#setClosed(new ProtoError(
"Received non-text message from server with JSON encoding"))
return;
}
msg = readJsonObject(JSON.parse(event.data), json_ServerMsg);
} else if (encoding === "protobuf") {
if (!(event.data instanceof ArrayBuffer)) {
this.#socket.close(3003, "Only binary messages are accepted with Protobuf encoding");
this.#setClosed(new ProtoError(
"Received non-binary message from server with Protobuf encoding"))
return;
}
msg = readProtobufMessage(new Uint8Array(event.data), protobuf_ServerMsg);
} else {
throw impossible(encoding, "Impossible encoding");
}
this.#handleMsg(msg);
} catch (e) {
this.#socket.close(3007, "Could not handle message");
this.#setClosed(e as Error);
}
}
// Handle a message from the server.
#handleMsg(msg: proto.ServerMsg): void {
if (msg.type === "none") {
throw new ProtoError("Received an unrecognized ServerMsg");
} else if (msg.type === "hello_ok" || msg.type === "hello_error") {
if (this.#recvdHello) {
throw new ProtoError("Received a duplicated hello response");
}
this.#recvdHello = true;
if (msg.type === "hello_error") {
throw errorFromProto(msg.error);
}
return;
} else if (!this.#recvdHello) {
throw new ProtoError("Received a non-hello message before a hello response");
}
if (msg.type === "response_ok") {
const requestId = msg.requestId;
const responseState = this.#responseMap.get(requestId);
this.#responseMap.delete(requestId);
if (responseState === undefined) {
throw new ProtoError("Received unexpected OK response");
}
this.#requestIdAlloc.free(requestId);
try {
if (responseState.type !== msg.response.type) {
console.dir({responseState, msg});
throw new ProtoError("Received unexpected type of response");
}
responseState.responseCallback(msg.response);
} catch (e) {
responseState.errorCallback(e as Error);
throw e;
}
} else if (msg.type === "response_error") {
const requestId = msg.requestId;
const responseState = this.#responseMap.get(requestId);
this.#responseMap.delete(requestId);
if (responseState === undefined) {
throw new ProtoError("Received unexpected error response");
}
this.#requestIdAlloc.free(requestId);
responseState.errorCallback(errorFromProto(msg.error));
} else {
throw impossible(msg, "Impossible ServerMsg type");
}
}
/** Open a {@link WsStream}, a stream for executing SQL statements. */
override openStream(): WsStream {
return WsStream.open(this);
}
/** Cache a SQL text on the server. This requires protocol version 2 or higher. */
storeSql(sql: string): Sql {
this._ensureVersion(2, "storeSql()");
const sqlId = this.#sqlIdAlloc.alloc();
const sqlObj = new Sql(this, sqlId);
const responseCallback = () => undefined;
const errorCallback = (e: Error) => sqlObj._setClosed(e);
const request: proto.StoreSqlReq = {type: "store_sql", sqlId, sql};
this._sendRequest(request, {responseCallback, errorCallback});
return sqlObj;
}
/** @private */
_closeSql(sqlId: number): void {
if (this.#closed !== undefined) {
return;
}
const responseCallback = () => this.#sqlIdAlloc.free(sqlId);
const errorCallback = (e: Error) => this.#setClosed(e);
const request: proto.CloseSqlReq = {type: "close_sql", sqlId};
this._sendRequest(request, {responseCallback, errorCallback});
}
/** Close the client and the WebSocket. */
override close(): void {
this.#setClosed(new ClientError("Client was manually closed"));
}
/** True if the client is closed. */
override get closed(): boolean {
return this.#closed !== undefined;
}
}
export interface OpenCallbacks {
openCallback: () => void;
errorCallback: (_: Error) => void;
}
export interface ResponseCallbacks {
responseCallback: (_: proto.Response) => void;
errorCallback: (_: Error) => void;
}
interface ResponseState extends ResponseCallbacks {
type: string;
}