stream.js 4.1 KB

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