message_stream.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.MessageStream = void 0;
  4. const stream_1 = require("stream");
  5. const error_1 = require("../error");
  6. const utils_1 = require("../utils");
  7. const commands_1 = require("./commands");
  8. const compression_1 = require("./wire_protocol/compression");
  9. const constants_1 = require("./wire_protocol/constants");
  10. const MESSAGE_HEADER_SIZE = 16;
  11. const COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID
  12. const kDefaultMaxBsonMessageSize = 1024 * 1024 * 16 * 4;
  13. /** @internal */
  14. const kBuffer = Symbol('buffer');
  15. /**
  16. * A duplex stream that is capable of reading and writing raw wire protocol messages, with
  17. * support for optional compression
  18. * @internal
  19. */
  20. class MessageStream extends stream_1.Duplex {
  21. constructor(options = {}) {
  22. super(options);
  23. /** @internal */
  24. this.isMonitoringConnection = false;
  25. this.maxBsonMessageSize = options.maxBsonMessageSize || kDefaultMaxBsonMessageSize;
  26. this[kBuffer] = new utils_1.BufferPool();
  27. }
  28. get buffer() {
  29. return this[kBuffer];
  30. }
  31. _write(chunk, _, callback) {
  32. this[kBuffer].append(chunk);
  33. processIncomingData(this, callback);
  34. }
  35. _read( /* size */) {
  36. // NOTE: This implementation is empty because we explicitly push data to be read
  37. // when `writeMessage` is called.
  38. return;
  39. }
  40. writeCommand(command, operationDescription) {
  41. const agreedCompressor = operationDescription.agreedCompressor ?? 'none';
  42. if (agreedCompressor === 'none' || !canCompress(command)) {
  43. const data = command.toBin();
  44. this.push(Array.isArray(data) ? Buffer.concat(data) : data);
  45. return;
  46. }
  47. // otherwise, compress the message
  48. const concatenatedOriginalCommandBuffer = Buffer.concat(command.toBin());
  49. const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE);
  50. // Extract information needed for OP_COMPRESSED from the uncompressed message
  51. const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12);
  52. const options = {
  53. agreedCompressor,
  54. zlibCompressionLevel: operationDescription.zlibCompressionLevel ?? 0
  55. };
  56. // Compress the message body
  57. (0, compression_1.compress)(options, messageToBeCompressed).then(compressedMessage => {
  58. // Create the msgHeader of OP_COMPRESSED
  59. const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE);
  60. msgHeader.writeInt32LE(MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, 0); // messageLength
  61. msgHeader.writeInt32LE(command.requestId, 4); // requestID
  62. msgHeader.writeInt32LE(0, 8); // responseTo (zero)
  63. msgHeader.writeInt32LE(constants_1.OP_COMPRESSED, 12); // opCode
  64. // Create the compression details of OP_COMPRESSED
  65. const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE);
  66. compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode
  67. compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader
  68. compressionDetails.writeUInt8(compression_1.Compressor[agreedCompressor], 8); // compressorID
  69. this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage]));
  70. }, error => {
  71. operationDescription.cb(error);
  72. });
  73. }
  74. }
  75. exports.MessageStream = MessageStream;
  76. // Return whether a command contains an uncompressible command term
  77. // Will return true if command contains no uncompressible command terms
  78. function canCompress(command) {
  79. const commandDoc = command instanceof commands_1.Msg ? command.command : command.query;
  80. const commandName = Object.keys(commandDoc)[0];
  81. return !compression_1.uncompressibleCommands.has(commandName);
  82. }
  83. function processIncomingData(stream, callback) {
  84. const buffer = stream[kBuffer];
  85. const sizeOfMessage = buffer.getInt32();
  86. if (sizeOfMessage == null) {
  87. return callback();
  88. }
  89. if (sizeOfMessage < 0) {
  90. return callback(new error_1.MongoParseError(`Invalid message size: ${sizeOfMessage}`));
  91. }
  92. if (sizeOfMessage > stream.maxBsonMessageSize) {
  93. return callback(new error_1.MongoParseError(`Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}`));
  94. }
  95. if (sizeOfMessage > buffer.length) {
  96. return callback();
  97. }
  98. const message = buffer.read(sizeOfMessage);
  99. const messageHeader = {
  100. length: message.readInt32LE(0),
  101. requestId: message.readInt32LE(4),
  102. responseTo: message.readInt32LE(8),
  103. opCode: message.readInt32LE(12)
  104. };
  105. const monitorHasAnotherHello = () => {
  106. if (stream.isMonitoringConnection) {
  107. // Can we read the next message size?
  108. const sizeOfMessage = buffer.getInt32();
  109. if (sizeOfMessage != null && sizeOfMessage <= buffer.length) {
  110. return true;
  111. }
  112. }
  113. return false;
  114. };
  115. let ResponseType = messageHeader.opCode === constants_1.OP_MSG ? commands_1.BinMsg : commands_1.Response;
  116. if (messageHeader.opCode !== constants_1.OP_COMPRESSED) {
  117. const messageBody = message.subarray(MESSAGE_HEADER_SIZE);
  118. // If we are a monitoring connection message stream and
  119. // there is more in the buffer that can be read, skip processing since we
  120. // want the last hello command response that is in the buffer.
  121. if (monitorHasAnotherHello()) {
  122. return processIncomingData(stream, callback);
  123. }
  124. stream.emit('message', new ResponseType(message, messageHeader, messageBody));
  125. if (buffer.length >= 4) {
  126. return processIncomingData(stream, callback);
  127. }
  128. return callback();
  129. }
  130. messageHeader.fromCompressed = true;
  131. messageHeader.opCode = message.readInt32LE(MESSAGE_HEADER_SIZE);
  132. messageHeader.length = message.readInt32LE(MESSAGE_HEADER_SIZE + 4);
  133. const compressorID = message[MESSAGE_HEADER_SIZE + 8];
  134. const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9);
  135. // recalculate based on wrapped opcode
  136. ResponseType = messageHeader.opCode === constants_1.OP_MSG ? commands_1.BinMsg : commands_1.Response;
  137. (0, compression_1.decompress)(compressorID, compressedBuffer).then(messageBody => {
  138. if (messageBody.length !== messageHeader.length) {
  139. return callback(new error_1.MongoDecompressionError('Message body and message header must be the same length'));
  140. }
  141. // If we are a monitoring connection message stream and
  142. // there is more in the buffer that can be read, skip processing since we
  143. // want the last hello command response that is in the buffer.
  144. if (monitorHasAnotherHello()) {
  145. return processIncomingData(stream, callback);
  146. }
  147. stream.emit('message', new ResponseType(message, messageHeader, messageBody));
  148. if (buffer.length >= 4) {
  149. return processIncomingData(stream, callback);
  150. }
  151. return callback();
  152. }, error => {
  153. return callback(error);
  154. });
  155. }
  156. //# sourceMappingURL=message_stream.js.map