Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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) {
  67. if (!duplex.push(msg)) {
  68. resumeOnReceiverDrain = false;
  69. ws._socket.pause();
  70. }
  71. });
  72. ws.once('error', function error(err) {
  73. if (duplex.destroyed) return;
  74. // Prevent `ws.terminate()` from being called by `duplex._destroy()`.
  75. //
  76. // - If the `'error'` event is emitted before the `'open'` event, then
  77. // `ws.terminate()` is a noop as no socket is assigned.
  78. // - Otherwise, the error is re-emitted by the listener of the `'error'`
  79. // event of the `Receiver` object. The listener already closes the
  80. // connection by calling `ws.close()`. This allows a close frame to be
  81. // sent to the other peer. If `ws.terminate()` is called right after this,
  82. // then the close frame might not be sent.
  83. terminateOnDestroy = false;
  84. duplex.destroy(err);
  85. });
  86. ws.once('close', function close() {
  87. if (duplex.destroyed) return;
  88. duplex.push(null);
  89. });
  90. duplex._destroy = function (err, callback) {
  91. if (ws.readyState === ws.CLOSED) {
  92. callback(err);
  93. process.nextTick(emitClose, duplex);
  94. return;
  95. }
  96. let called = false;
  97. ws.once('error', function error(err) {
  98. called = true;
  99. callback(err);
  100. });
  101. ws.once('close', function close() {
  102. if (!called) callback(err);
  103. process.nextTick(emitClose, duplex);
  104. });
  105. if (terminateOnDestroy) ws.terminate();
  106. };
  107. duplex._final = function (callback) {
  108. if (ws.readyState === ws.CONNECTING) {
  109. ws.once('open', function open() {
  110. duplex._final(callback);
  111. });
  112. return;
  113. }
  114. // If the value of the `_socket` property is `null` it means that `ws` is a
  115. // client websocket and the handshake failed. In fact, when this happens, a
  116. // socket is never assigned to the websocket. Wait for the `'error'` event
  117. // that will be emitted by the websocket.
  118. if (ws._socket === null) return;
  119. if (ws._socket._writableState.finished) {
  120. callback();
  121. if (duplex._readableState.endEmitted) duplex.destroy();
  122. } else {
  123. ws._socket.once('finish', function finish() {
  124. // `duplex` is not destroyed here because the `'end'` event will be
  125. // emitted on `duplex` after this `'finish'` event. The EOF signaling
  126. // `null` chunk is, in fact, pushed when the websocket emits `'close'`.
  127. callback();
  128. });
  129. ws.close();
  130. }
  131. };
  132. duplex._read = function () {
  133. if (
  134. (ws.readyState === ws.OPEN || ws.readyState === ws.CLOSING) &&
  135. !resumeOnReceiverDrain
  136. ) {
  137. resumeOnReceiverDrain = true;
  138. if (!ws._receiver._writableState.needDrain) ws._socket.resume();
  139. }
  140. };
  141. duplex._write = function (chunk, encoding, callback) {
  142. if (ws.readyState === ws.CONNECTING) {
  143. ws.once('open', function open() {
  144. duplex._write(chunk, encoding, callback);
  145. });
  146. return;
  147. }
  148. ws.send(chunk, callback);
  149. };
  150. duplex.on('end', duplexOnEnd);
  151. duplex.on('error', duplexOnError);
  152. return duplex;
  153. }
  154. module.exports = createWebSocketStream;