]> git.proxmox.com Git - mirror_novnc.git/blame - core/websock.js
Code comments for how the receieve queue works
[mirror_novnc.git] / core / websock.js
CommitLineData
72f1348b
JM
1/*
2 * Websock: high-performance binary WebSockets
84586c0f 3 * Copyright (C) 2018 The noVNC Authors
1d728ace 4 * Licensed under MPL 2.0 (see LICENSE.txt)
72f1348b 5 *
d2467189
PO
6 * Websock is similar to the standard WebSocket object but with extra
7 * buffer handling.
72f1348b
JM
8 *
9 * Websock has built-in receive queue buffering; the message event
10 * does not contain actual data but is simply a notification that
11 * there is new data available. Several rQ* methods are available to
12 * read binary data off of the receive queue.
13 */
14
6d6f0db0 15import * as Log from './util/logging.js';
ae510306 16
6d6f0db0
SR
17// this has performance issues in some versions Chromium, and
18// doesn't gain a tremendous amount of performance increase in Firefox
19// at the moment. It may be valuable to turn it on in the future.
c90d5356
SM
20// Also copyWithin() for TypedArrays is not supported in IE 11 or
21// Safari 13 (at the moment we want to support Safari 11).
2b5f94fa 22const ENABLE_COPYWITHIN = false;
2b5f94fa 23const MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB
6d6f0db0 24
0e4808bf
JD
25export default class Websock {
26 constructor() {
27 this._websocket = null; // WebSocket object
28
29 this._rQi = 0; // Receive queue index
30 this._rQlen = 0; // Next write position in the receive queue
31 this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB)
0e4808bf
JD
32 // called in init: this._rQ = new Uint8Array(this._rQbufferSize);
33 this._rQ = null; // Receive queue
34
35 this._sQbufferSize = 1024 * 10; // 10 KiB
36 // called in init: this._sQ = new Uint8Array(this._sQbufferSize);
37 this._sQlen = 0;
38 this._sQ = null; // Send queue
39
40 this._eventHandlers = {
41 message: () => {},
42 open: () => {},
43 close: () => {},
44 error: () => {}
45 };
46 }
47
6d6f0db0 48 // Getters and Setters
8a189a62 49 get sQ() {
6d6f0db0 50 return this._sQ;
0e4808bf 51 }
6d6f0db0 52
8a189a62 53 get rQ() {
6d6f0db0 54 return this._rQ;
0e4808bf 55 }
6d6f0db0 56
8a189a62 57 get rQi() {
6d6f0db0 58 return this._rQi;
0e4808bf 59 }
6d6f0db0 60
8a189a62 61 set rQi(val) {
6d6f0db0 62 this._rQi = val;
0e4808bf 63 }
6d6f0db0
SR
64
65 // Receive Queue
8a189a62 66 get rQlen() {
6d6f0db0 67 return this._rQlen - this._rQi;
0e4808bf 68 }
6d6f0db0 69
0e4808bf 70 rQpeek8() {
6d6f0db0 71 return this._rQ[this._rQi];
0e4808bf 72 }
6d6f0db0 73
8a189a62
JD
74 rQskipBytes(bytes) {
75 this._rQi += bytes;
76 }
77
0e4808bf 78 rQshift8() {
879e33ab 79 return this._rQshift(1);
0e4808bf 80 }
6d6f0db0 81
0e4808bf 82 rQshift16() {
879e33ab 83 return this._rQshift(2);
0e4808bf 84 }
6d6f0db0 85
0e4808bf 86 rQshift32() {
879e33ab
JD
87 return this._rQshift(4);
88 }
89
90 // TODO(directxman12): test performance with these vs a DataView
91 _rQshift(bytes) {
92 let res = 0;
93 for (let byte = bytes - 1; byte >= 0; byte--) {
94 res += this._rQ[this._rQi++] << (byte * 8);
95 }
96 return res;
0e4808bf 97 }
6d6f0db0 98
0e4808bf 99 rQshiftStr(len) {
8a189a62 100 if (typeof(len) === 'undefined') { len = this.rQlen; }
db9daa98
SM
101 let str = "";
102 // Handle large arrays in steps to avoid long strings on the stack
103 for (let i = 0; i < len; i += 4096) {
f90c2a6d 104 let part = this.rQshiftBytes(Math.min(4096, len - i));
d9814c06 105 str += String.fromCharCode.apply(null, part);
db9daa98
SM
106 }
107 return str;
0e4808bf 108 }
6d6f0db0 109
0e4808bf 110 rQshiftBytes(len) {
8a189a62 111 if (typeof(len) === 'undefined') { len = this.rQlen; }
6d6f0db0
SR
112 this._rQi += len;
113 return new Uint8Array(this._rQ.buffer, this._rQi - len, len);
0e4808bf 114 }
6d6f0db0 115
0e4808bf 116 rQshiftTo(target, len) {
8a189a62 117 if (len === undefined) { len = this.rQlen; }
6d6f0db0
SR
118 // TODO: make this just use set with views when using a ArrayBuffer to store the rQ
119 target.set(new Uint8Array(this._rQ.buffer, this._rQi, len));
120 this._rQi += len;
0e4808bf 121 }
6d6f0db0 122
8a189a62
JD
123 rQslice(start, end = this.rQlen) {
124 return new Uint8Array(this._rQ.buffer, this._rQi + start, end - start);
0e4808bf 125 }
6d6f0db0
SR
126
127 // Check to see if we must wait for 'num' bytes (default to FBU.bytes)
128 // to be available in the receive queue. Return true if we need to
129 // wait (and possibly print a debug message), otherwise false.
0e4808bf 130 rQwait(msg, num, goback) {
8a189a62 131 if (this.rQlen < num) {
6d6f0db0
SR
132 if (goback) {
133 if (this._rQi < goback) {
134 throw new Error("rQwait cannot backup " + goback + " bytes");
2cccf753 135 }
6d6f0db0 136 this._rQi -= goback;
2cccf753 137 }
6d6f0db0
SR
138 return true; // true means need more data
139 }
140 return false;
0e4808bf 141 }
72f1348b 142
6d6f0db0 143 // Send Queue
72f1348b 144
0e4808bf 145 flush() {
6d6f0db0
SR
146 if (this._sQlen > 0 && this._websocket.readyState === WebSocket.OPEN) {
147 this._websocket.send(this._encode_message());
148 this._sQlen = 0;
149 }
0e4808bf 150 }
6d6f0db0 151
0e4808bf 152 send(arr) {
6d6f0db0
SR
153 this._sQ.set(arr, this._sQlen);
154 this._sQlen += arr.length;
155 this.flush();
0e4808bf 156 }
6d6f0db0 157
0e4808bf 158 send_string(str) {
651c23ec 159 this.send(str.split('').map(chr => chr.charCodeAt(0)));
0e4808bf 160 }
6d6f0db0
SR
161
162 // Event Handlers
0e4808bf 163 off(evt) {
651c23ec 164 this._eventHandlers[evt] = () => {};
0e4808bf 165 }
6d6f0db0 166
0e4808bf 167 on(evt, handler) {
6d6f0db0 168 this._eventHandlers[evt] = handler;
0e4808bf 169 }
6d6f0db0 170
0e4808bf 171 _allocate_buffers() {
6d6f0db0
SR
172 this._rQ = new Uint8Array(this._rQbufferSize);
173 this._sQ = new Uint8Array(this._sQbufferSize);
0e4808bf 174 }
6d6f0db0 175
0e4808bf 176 init() {
6d6f0db0
SR
177 this._allocate_buffers();
178 this._rQi = 0;
179 this._websocket = null;
0e4808bf 180 }
6d6f0db0 181
0e4808bf 182 open(uri, protocols) {
6d6f0db0
SR
183 this.init();
184
185 this._websocket = new WebSocket(uri, protocols);
186 this._websocket.binaryType = 'arraybuffer';
187
188 this._websocket.onmessage = this._recv_message.bind(this);
651c23ec 189 this._websocket.onopen = () => {
6d6f0db0
SR
190 Log.Debug('>> WebSock.onopen');
191 if (this._websocket.protocol) {
192 Log.Info("Server choose sub-protocol: " + this._websocket.protocol);
2cccf753 193 }
2cccf753 194
6d6f0db0
SR
195 this._eventHandlers.open();
196 Log.Debug("<< WebSock.onopen");
651c23ec
JD
197 };
198 this._websocket.onclose = (e) => {
6d6f0db0
SR
199 Log.Debug(">> WebSock.onclose");
200 this._eventHandlers.close(e);
201 Log.Debug("<< WebSock.onclose");
651c23ec
JD
202 };
203 this._websocket.onerror = (e) => {
6d6f0db0
SR
204 Log.Debug(">> WebSock.onerror: " + e);
205 this._eventHandlers.error(e);
206 Log.Debug("<< WebSock.onerror: " + e);
651c23ec 207 };
0e4808bf 208 }
6d6f0db0 209
0e4808bf 210 close() {
6d6f0db0
SR
211 if (this._websocket) {
212 if ((this._websocket.readyState === WebSocket.OPEN) ||
213 (this._websocket.readyState === WebSocket.CONNECTING)) {
214 Log.Info("Closing WebSocket connection");
215 this._websocket.close();
fcff386b 216 }
6d6f0db0 217
651c23ec 218 this._websocket.onmessage = () => {};
6d6f0db0 219 }
0e4808bf 220 }
6d6f0db0
SR
221
222 // private methods
0e4808bf 223 _encode_message() {
6d6f0db0
SR
224 // Put in a binary arraybuffer
225 // according to the spec, you can send ArrayBufferViews with the send method
226 return new Uint8Array(this._sQ.buffer, 0, this._sQlen);
0e4808bf 227 }
6d6f0db0 228
e8614e20
SM
229 // We want to move all the unread data to the start of the queue,
230 // e.g. compacting.
231 // The function also expands the receive que if needed, and for
232 // performance reasons we combine these two actions to avoid
233 // unneccessary copying.
0e4808bf 234 _expand_compact_rQ(min_fit) {
7d755d10
JAD
235 // if we're using less than 1/8th of the buffer even with the incoming bytes, compact in place
236 // instead of resizing
237 const required_buffer_size = (this._rQlen - this._rQi + min_fit) * 8;
238 const resizeNeeded = this._rQbufferSize < required_buffer_size;
239
6d6f0db0 240 if (resizeNeeded) {
7d755d10
JAD
241 // Make sure we always *at least* double the buffer size, and have at least space for 8x
242 // the current amount of data
243 this._rQbufferSize = Math.max(this._rQbufferSize * 2, required_buffer_size);
6d6f0db0 244 }
40037b6a 245
6d6f0db0
SR
246 // we don't want to grow unboundedly
247 if (this._rQbufferSize > MAX_RQ_GROW_SIZE) {
248 this._rQbufferSize = MAX_RQ_GROW_SIZE;
8a189a62 249 if (this._rQbufferSize - this.rQlen < min_fit) {
8727f598 250 throw new Error("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit");
40037b6a 251 }
6d6f0db0 252 }
40037b6a 253
6d6f0db0 254 if (resizeNeeded) {
2b5f94fa 255 const old_rQbuffer = this._rQ.buffer;
6d6f0db0 256 this._rQ = new Uint8Array(this._rQbufferSize);
08567b08 257 this._rQ.set(new Uint8Array(old_rQbuffer, this._rQi, this._rQlen - this._rQi));
6d6f0db0
SR
258 } else {
259 if (ENABLE_COPYWITHIN) {
08567b08 260 this._rQ.copyWithin(0, this._rQi, this._rQlen);
40037b6a 261 } else {
08567b08 262 this._rQ.set(new Uint8Array(this._rQ.buffer, this._rQi, this._rQlen - this._rQi));
40037b6a 263 }
6d6f0db0 264 }
40037b6a 265
6d6f0db0
SR
266 this._rQlen = this._rQlen - this._rQi;
267 this._rQi = 0;
0e4808bf 268 }
40037b6a 269
e8614e20 270 // push arraybuffer values onto the end of the receive que
0e4808bf 271 _decode_message(data) {
2b5f94fa 272 const u8 = new Uint8Array(data);
6d6f0db0
SR
273 if (u8.length > this._rQbufferSize - this._rQlen) {
274 this._expand_compact_rQ(u8.length);
275 }
276 this._rQ.set(u8, this._rQlen);
277 this._rQlen += u8.length;
0e4808bf 278 }
fcff386b 279
0e4808bf 280 _recv_message(e) {
1678bf86 281 this._decode_message(e.data);
8a189a62 282 if (this.rQlen > 0) {
1678bf86 283 this._eventHandlers.message();
1678bf86 284 if (this._rQlen == this._rQi) {
e8614e20
SM
285 // All data has now been processed, this means we
286 // can reset the receive queue.
1678bf86
PO
287 this._rQlen = 0;
288 this._rQi = 0;
2cccf753 289 }
1678bf86
PO
290 } else {
291 Log.Debug("Ignoring empty message");
72f1348b 292 }
6d6f0db0 293 }
0e4808bf 294}