stream.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. 'use strict';
  2. const { Duplex } = require('stream');
  3. /**
  4. * Emits the `'close'` event on a stream.
  5. *
  6. * @param {Duplex} stream The stream.
  7. * @private
  8. */
  9. function emitClose(stream) {
  10. stream.emit('close');
  11. }
  12. /**
  13. * The listener of the `'end'` event.
  14. *
  15. * @private
  16. */
  17. function duplexOnEnd() {
  18. if (!this.destroyed && this._writableState.finished) {
  19. this.destroy();
  20. }
  21. }
  22. /**
  23. * The listener of the `'error'` event.
  24. *
  25. * @param {Error} err The error
  26. * @private
  27. */
  28. function duplexOnError(err) {
  29. this.removeListener('error', duplexOnError);
  30. this.destroy();
  31. if (this.listenerCount('error') === 0) {
  32. // Do not suppress the throwing behavior.
  33. this.emit('error', err);
  34. }
  35. }
  36. /**
  37. * Wraps a `WebSocket` in a duplex stream.
  38. *
  39. * @param {WebSocket} ws The `WebSocket` to wrap
  40. * @param {Object} [options] The options for the `Duplex` constructor
  41. * @return {Duplex} The duplex stream
  42. * @public
  43. */
  44. function createWebSocketStream(ws, options) {
  45. let resumeOnReceiverDrain = true;
  46. let terminateOnDestroy = true;
  47. function receiverOnDrain() {
  48. if (resumeOnReceiverDrain) ws._socket.resume();
  49. }
  50. if (ws.readyState === ws.CONNECTING) {
  51. ws.once('open', function open() {
  52. ws._receiver.removeAllListeners('drain');
  53. ws._receiver.on('drain', receiverOnDrain);
  54. });
  55. } else {
  56. ws._receiver.removeAllListeners('drain');
  57. ws._receiver.on('drain', receiverOnDrain);
  58. }
  59. const duplex = new Duplex({
  60. ...options,
  61. autoDestroy: false,
  62. emitClose: false,
  63. objectMode: false,
  64. writableObjectMode: false
  65. });
  66. ws.on('message', function message(msg, isBinary) {
  67. const data =
  68. !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
  69. if (!duplex.push(data)) {
  70. resumeOnReceiverDrain = false;
  71. ws._socket.pause();
  72. }
  73. });
  74. ws.once('error', function error(err) {
  75. if (duplex.destroyed) return;
  76. // Prevent `ws.terminate()` from being called by `duplex._destroy()`.
  77. //
  78. // - If the `'error'` event is emitted before the `'open'` event, then
  79. // `ws.terminate()` is a noop as no socket is assigned.
  80. // - Otherwise, the error is re-emitted by the listener of the `'error'`
  81. // event of the `Receiver` object. The listener already closes the
  82. // connection by calling `ws.close()`. This allows a close frame to be
  83. // sent to the other peer. If `ws.terminate()` is called right after this,
  84. // then the close frame might not be sent.
  85. terminateOnDestroy = false;
  86. duplex.destroy(err);
  87. });
  88. ws.once('close', function close() {
  89. if (duplex.destroyed) return;
  90. duplex.push(null);
  91. });
  92. duplex._destroy = function (err, callback) {
  93. if (ws.readyState === ws.CLOSED) {
  94. callback(err);
  95. process.nextTick(emitClose, duplex);
  96. return;
  97. }
  98. let called = false;
  99. ws.once('error', function error(err) {
  100. called = true;
  101. callback(err);
  102. });
  103. ws.once('close', function close() {
  104. if (!called) callback(err);
  105. process.nextTick(emitClose, duplex);
  106. });
  107. if (terminateOnDestroy) ws.terminate();
  108. };
  109. duplex._final = function (callback) {
  110. if (ws.readyState === ws.CONNECTING) {
  111. ws.once('open', function open() {
  112. duplex._final(callback);
  113. });
  114. return;
  115. }
  116. // If the value of the `_socket` property is `null` it means that `ws` is a
  117. // client websocket and the handshake failed. In fact, when this happens, a
  118. // socket is never assigned to the websocket. Wait for the `'error'` event
  119. // that will be emitted by the websocket.
  120. if (ws._socket === null) return;
  121. if (ws._socket._writableState.finished) {
  122. callback();
  123. if (duplex._readableState.endEmitted) duplex.destroy();
  124. } else {
  125. ws._socket.once('finish', function finish() {
  126. // `duplex` is not destroyed here because the `'end'` event will be
  127. // emitted on `duplex` after this `'finish'` event. The EOF signaling
  128. // `null` chunk is, in fact, pushed when the websocket emits `'close'`.
  129. callback();
  130. });
  131. ws.close();
  132. }
  133. };
  134. duplex._read = function () {
  135. if (ws.readyState === ws.OPEN && !resumeOnReceiverDrain) {
  136. resumeOnReceiverDrain = true;
  137. if (!ws._receiver._writableState.needDrain) ws._socket.resume();
  138. }
  139. };
  140. duplex._write = function (chunk, encoding, callback) {
  141. if (ws.readyState === ws.CONNECTING) {
  142. ws.once('open', function open() {
  143. duplex._write(chunk, encoding, callback);
  144. });
  145. return;
  146. }
  147. ws.send(chunk, callback);
  148. };
  149. duplex.on('end', duplexOnEnd);
  150. duplex.on('error', duplexOnError);
  151. return duplex;
  152. }
  153. module.exports = createWebSocketStream;