wrapper.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. "use strict";
  2. const WebSocketChannel = require("./channel");
  3. class WebSocketWrapper extends WebSocketChannel {
  4. constructor(socket, options) {
  5. // Make `this` a WebSocketChannel
  6. super();
  7. this._wrapper = this;
  8. options = options || {};
  9. if(typeof options.debug === "function") {
  10. this._debug = options.debug;
  11. } else if(options.debug === true) {
  12. this._debug = console.log.bind(console);
  13. } else {
  14. this._debug = () => {}; // no-op
  15. }
  16. if(typeof options.errorToJSON !== "function") {
  17. // Provide default error serialization
  18. this._errorToJSON = (err) => {
  19. if(typeof window === "undefined") {
  20. // Node.js environment only serializes `message`
  21. return JSON.stringify({"message": err.message});
  22. } else {
  23. // Browser serializes all error properties
  24. return JSON.stringify(err,
  25. Object.getOwnPropertyNames(err) );
  26. }
  27. };
  28. } else {
  29. this._errorToJSON = options.errorToJSON;
  30. }
  31. if(options.requestTimeout > 0)
  32. this._requestTimeout = options.requestTimeout | 0;
  33. // Flag set once the socket is opened
  34. this._opened = false;
  35. // Array of data to be sent once the connection is opened
  36. this._pendingSend = [];
  37. // Incrementing request ID counter for this WebSocket
  38. this._lastRequestId = 0;
  39. /* Object of pending requests; keys are the request ID, values are
  40. Objects containing `resolve` and `reject` functions used to
  41. resolve the request's Promise. */
  42. this._pendingRequests = {};
  43. /* Object of WebSocketChannels (except `this` associated with this
  44. WebSocket); keys are the channel name. */
  45. this._channels = {};
  46. // Object containing user-assigned socket data
  47. this._data = {};
  48. // Bind this wrapper to the `socket` passed to the constructor
  49. this._socket = null;
  50. if(socket && socket.constructor) {
  51. this.bind(socket);
  52. }
  53. }
  54. bind(socket) {
  55. // Clean up any event handlers on `this._socket`
  56. if(this._socket) {
  57. var s = this._socket;
  58. s.onopen = s.onmessage = s.onerror = s.onclose = null;
  59. }
  60. // Save the `socket` and add event listeners
  61. this._socket = socket;
  62. socket.onopen = (event) => {
  63. this._opened = true;
  64. this._debug("socket: onopen");
  65. // Send all pending messages
  66. for(var i = 0; i < this._pendingSend.length; i++) {
  67. if(this.isConnected) {
  68. this._debug("wrapper: Sending pending message:",
  69. this._pendingSend[i]);
  70. try {
  71. this._socket.send(this._pendingSend[i]);
  72. } catch(e) {
  73. this._pendingSend = this._pendingSend.slice(i - 1);
  74. throw e;
  75. }
  76. } else {
  77. break;
  78. }
  79. }
  80. this._pendingSend = this._pendingSend.slice(i);
  81. this.emit("open", event);
  82. };
  83. socket.onmessage = (event) => {
  84. this._debug("socket: onmessage", event.data);
  85. this.emit("message", event, event.data);
  86. this._onMessage(event.data);
  87. };
  88. socket.onerror = (event) => {
  89. this._debug("socket: onerror", event);
  90. this.emit("error", event);
  91. };
  92. socket.onclose = (event) => {
  93. var opened = this._opened;
  94. this._opened = false;
  95. this._debug("socket: onclose", event);
  96. this.emit("close", event, opened);
  97. this.emit("disconnect", event, opened);
  98. };
  99. // If the socket is already open, send all pending messages now
  100. if(this.isConnected) {
  101. socket.onopen();
  102. }
  103. return this;
  104. }
  105. get socket() {
  106. return this._socket;
  107. }
  108. set socket(socket) {
  109. this.bind(socket);
  110. }
  111. // Rejects all pending requests and then clears the send queue
  112. abort() {
  113. for(var id in this._pendingRequests) {
  114. this._pendingRequests[id].reject(new Error("Request was aborted") );
  115. }
  116. this._pendingRequests = {};
  117. this._pendingSend = [];
  118. return this;
  119. }
  120. // Returns a channel with the specified `namespace`
  121. of(namespace) {
  122. if(namespace == null) {
  123. return this;
  124. }
  125. if(!this._channels[namespace]) {
  126. this._channels[namespace] = new WebSocketChannel(namespace, this);
  127. }
  128. return this._channels[namespace];
  129. }
  130. get isConnecting() {
  131. return this._socket && this._socket.readyState ===
  132. this._socket.constructor.CONNECTING;
  133. }
  134. get isConnected() {
  135. return this._socket && this._socket.readyState ===
  136. this._socket.constructor.OPEN;
  137. }
  138. send(data, ignoreMaxQueueSize) {
  139. if(this.isConnected) {
  140. this._debug("wrapper: Sending message:", data);
  141. this._socket.send(data);
  142. } else if(ignoreMaxQueueSize ||
  143. this._pendingSend.length < WebSocketWrapper.MAX_SEND_QUEUE_SIZE)
  144. {
  145. this._debug("wrapper: Queuing message:", data);
  146. this._pendingSend.push(data);
  147. } else {
  148. throw new Error("WebSocket is not connected and send queue is full");
  149. }
  150. return this;
  151. }
  152. disconnect() {
  153. if(this._socket)
  154. this._socket.close.apply(this._socket, arguments);
  155. return this;
  156. }
  157. // Called whenever the bound Socket receives a message
  158. _onMessage(msg) {
  159. try {
  160. msg = JSON.parse(msg);
  161. // If `msg` contains special ignore property, we'll ignore it
  162. if(msg["ws-wrapper"] === false)
  163. return;
  164. if(msg.a) {
  165. var argsArray = [];
  166. for(var i in msg.a) {
  167. argsArray[i] = msg.a[i];
  168. }
  169. msg.a = argsArray;
  170. }
  171. /* If `msg` does not have an `a` Array with at least 1 element,
  172. ignore the message because it is not a valid event/request */
  173. if(msg.a instanceof Array && msg.a.length >= 1 &&
  174. (msg.c || WebSocketChannel.NO_WRAP_EVENTS.indexOf(msg.a[0]) < 0) )
  175. {
  176. // Process inbound event/request
  177. var event = {
  178. "name": msg.a.shift(),
  179. "args": msg.a,
  180. "requestId": msg.i
  181. };
  182. var channel = msg.c == null ? this : this._channels[msg.c];
  183. if(!channel) {
  184. if(msg.i >= 0) {
  185. this._sendReject(msg.i, new Error(
  186. `Channel '${msg.c}' does not exist`
  187. ) );
  188. }
  189. this._debug(`wrapper: Event '${event.name}' ignored ` +
  190. `because channel '${msg.c}' does not exist.`);
  191. } else if(channel._emitter.emit(event.name, event) ) {
  192. this._debug(`wrapper: Event '${event.name}' sent to ` +
  193. "event listener");
  194. } else {
  195. if(msg.i >= 0) {
  196. this._sendReject(msg.i, new Error(
  197. "No event listener for '" + event.name + "'" +
  198. (msg.c ? " on channel '" + msg.c + "'" : "")
  199. ) );
  200. }
  201. this._debug(`wrapper: Event '${event.name}' had no ` +
  202. "event listener");
  203. }
  204. } else if(this._pendingRequests[msg.i]) {
  205. this._debug("wrapper: Processing response for request", msg.i);
  206. // Process response to prior request
  207. if(msg.e !== undefined) {
  208. var err = msg.e;
  209. // `msg._` indicates that `msg.e` is an Error
  210. if(msg._ && err) {
  211. err = new Error(err.message);
  212. // Copy other properties to Error
  213. for(var key in msg.e) {
  214. err[key] = msg.e[key];
  215. }
  216. }
  217. this._pendingRequests[msg.i].reject(err);
  218. } else {
  219. this._pendingRequests[msg.i].resolve(msg.d);
  220. }
  221. clearTimeout(this._pendingRequests[msg.i].timer);
  222. delete this._pendingRequests[msg.i];
  223. }
  224. // else ignore the message because it's not valid
  225. } catch(e) {
  226. // Non-JSON messages are ignored
  227. /* Note: It's also possible for uncaught exceptions from event
  228. handlers to end up here. */
  229. }
  230. }
  231. /* The following methods are called by a WebSocketChannel to send data
  232. to the Socket. */
  233. _sendEvent(channel, eventName, args, isRequest) {
  234. // Serialize data for sending over the socket
  235. var data = {"a": args};
  236. if(channel != null) {
  237. data.c = channel;
  238. }
  239. var request;
  240. if(isRequest) {
  241. /* Unless we send petabytes of data using the same socket,
  242. we won't worry about `_lastRequestId` getting too big. */
  243. data.i = ++this._lastRequestId;
  244. // Return a Promise to the caller to be resolved later
  245. request = new Promise((resolve, reject) => {
  246. var pendReq = this._pendingRequests[data.i] = {
  247. "resolve": resolve,
  248. "reject": reject
  249. };
  250. if(this._requestTimeout > 0) {
  251. pendReq.timer = setTimeout(() => {
  252. reject(new Error("Request timed out") );
  253. delete this._pendingRequests[data.i];
  254. }, this._requestTimeout);
  255. }
  256. });
  257. }
  258. // Send the message
  259. this.send(JSON.stringify(data) );
  260. // Return the request, if needed
  261. return request;
  262. }
  263. _sendResolve(id, data) {
  264. this.send(JSON.stringify({
  265. "i": id,
  266. "d": data
  267. }), true /* ignore max queue length */);
  268. }
  269. _sendReject(id, err) {
  270. var isError = err instanceof Error;
  271. if(isError) {
  272. err = JSON.parse(this._errorToJSON(err) );
  273. }
  274. this.send(JSON.stringify({
  275. "i": id,
  276. "e": err,
  277. "_": isError ? 1 : undefined
  278. }), true /* ignore max queue length */);
  279. }
  280. get(key) {
  281. return this._data[key];
  282. }
  283. set(key, value) {
  284. this._data[key] = value;
  285. return this;
  286. }
  287. }
  288. /* Maximum number of items in the send queue. If a user tries to send more
  289. messages than this number while a WebSocket is not connected, errors will
  290. be thrown. */
  291. WebSocketWrapper.MAX_SEND_QUEUE_SIZE = 10;
  292. module.exports = WebSocketWrapper;