/
ws_transport.ts
299 lines (275 loc) · 7.38 KB
/
ws_transport.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
/*
* Copyright 2020-2023 The NATS Authors
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type {
ConnectionOptions,
Deferred,
Server,
ServerInfo,
Transport,
} from "https://raw.githubusercontent.com/nats-io/nats.deno/v1.20.1/nats-base-client/internal_mod.ts";
import {
checkOptions,
DataBuffer,
deferred,
delay,
ErrorCode,
extractProtocolMessage,
INFO,
NatsError,
render,
} from "https://raw.githubusercontent.com/nats-io/nats.deno/v1.20.1/nats-base-client/internal_mod.ts";
const VERSION = "1.22.0";
const LANG = "nats.ws";
export type WsSocketFactory = (u: string, opts: ConnectionOptions) => Promise<{
socket: WebSocket;
encrypted: boolean;
}>;
interface WsConnectionOptions extends ConnectionOptions {
wsFactory?: WsSocketFactory;
}
export class WsTransport implements Transport {
version: string;
lang: string;
closeError?: Error;
connected: boolean;
private done: boolean;
// @ts-ignore: expecting global WebSocket
private socket: WebSocket;
private options!: WsConnectionOptions;
socketClosed: boolean;
encrypted: boolean;
peeked: boolean;
yields: Uint8Array[];
signal: Deferred<void>;
closedNotification: Deferred<void | Error>;
constructor() {
this.version = VERSION;
this.lang = LANG;
this.connected = false;
this.done = false;
this.socketClosed = false;
this.encrypted = false;
this.peeked = false;
this.yields = [];
this.signal = deferred();
this.closedNotification = deferred();
}
async connect(
server: Server,
options: WsConnectionOptions,
): Promise<void> {
const connected = false;
const connLock = deferred<void>();
// ws client doesn't support TLS setting
if (options.tls) {
connLock.reject(new NatsError("tls", ErrorCode.InvalidOption));
return connLock;
}
this.options = options;
const u = server.src;
if (options.wsFactory) {
const { socket, encrypted } = await options.wsFactory(
server.src,
options,
);
this.socket = socket;
this.encrypted = encrypted;
} else {
this.encrypted = u.indexOf("wss://") === 0;
this.socket = new WebSocket(u);
}
this.socket.binaryType = "arraybuffer";
this.socket.onopen = () => {
if (this.isDiscarded()) {
return;
}
// we don't do anything here...
};
this.socket.onmessage = (me: MessageEvent) => {
if (this.isDiscarded()) {
return;
}
this.yields.push(new Uint8Array(me.data));
if (this.peeked) {
this.signal.resolve();
return;
}
const t = DataBuffer.concat(...this.yields);
const pm = extractProtocolMessage(t);
if (pm !== "") {
const m = INFO.exec(pm);
if (!m) {
if (options.debug) {
console.error("!!!", render(t));
}
connLock.reject(new Error("unexpected response from server"));
return;
}
try {
const info = JSON.parse(m[1]) as ServerInfo;
checkOptions(info, this.options);
this.peeked = true;
this.connected = true;
this.signal.resolve();
connLock.resolve();
} catch (err) {
connLock.reject(err);
return;
}
}
};
// @ts-ignore: CloseEvent is provided in browsers
this.socket.onclose = (evt: CloseEvent) => {
if (this.isDiscarded()) {
return;
}
this.socketClosed = true;
let reason: Error | undefined;
if (this.done) return;
if (!evt.wasClean) {
reason = new Error(evt.reason);
}
this._closed(reason);
};
// @ts-ignore: signature can be any
this.socket.onerror = (e: ErrorEvent | Event): void => {
if (this.isDiscarded()) {
return;
}
const evt = e as ErrorEvent;
const err = new NatsError(
evt.message,
ErrorCode.Unknown,
new Error(evt.error),
);
if (!connected) {
connLock.reject(err);
} else {
this._closed(err);
}
};
return connLock;
}
disconnect(): void {
this._closed(undefined, true);
}
private async _closed(err?: Error, internal = true): Promise<void> {
if (this.isDiscarded()) {
return;
}
if (!this.connected) return;
if (this.done) return;
this.closeError = err;
if (!err) {
while (!this.socketClosed && this.socket.bufferedAmount > 0) {
await delay(100);
}
}
this.done = true;
try {
// 1002 endpoint error, 1000 is clean
this.socket.close(err ? 1002 : 1000, err ? err.message : undefined);
} catch (err) {
// ignore this
}
if (internal) {
this.closedNotification.resolve(err);
}
}
get isClosed(): boolean {
return this.done;
}
[Symbol.asyncIterator]() {
return this.iterate();
}
async *iterate(): AsyncIterableIterator<Uint8Array> {
while (true) {
if (this.isDiscarded()) {
return;
}
if (this.yields.length === 0) {
await this.signal;
}
const yields = this.yields;
this.yields = [];
for (let i = 0; i < yields.length; i++) {
if (this.options.debug) {
console.info(`> ${render(yields[i])}`);
}
yield yields[i];
}
// yielding could have paused and microtask
// could have added messages. Prevent allocations
// if possible
if (this.done) {
break;
} else if (this.yields.length === 0) {
yields.length = 0;
this.yields = yields;
this.signal = deferred();
}
}
}
isEncrypted(): boolean {
return this.connected && this.encrypted;
}
send(frame: Uint8Array): void {
if (this.isDiscarded()) {
return;
}
try {
this.socket.send(frame.buffer);
if (this.options.debug) {
console.info(`< ${render(frame)}`);
}
return;
} catch (err) {
// we ignore write errors because client will
// fail on a read or when the heartbeat timer
// detects a stale connection
if (this.options.debug) {
console.error(`!!! ${render(frame)}: ${err}`);
}
}
}
close(err?: Error | undefined): Promise<void> {
return this._closed(err, false);
}
closed(): Promise<void | Error> {
return this.closedNotification;
}
// check to see if we are discarded, as the connection
// may not have been closed, we attempt it here as well.
isDiscarded(): boolean {
if (this.done) {
this.discard();
return true;
}
return false;
}
// this is to allow a force discard on a connection
// if the connection fails during the handshake protocol.
// Firefox for example, will keep connections going,
// so eventually if it succeeds, the client will have
// an additional transport running. With this
discard() {
this.done = true;
try {
this.socket?.close();
} catch (_err) {
// ignored
}
}
}