message_stream.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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. this.maxBsonMessageSize = options.maxBsonMessageSize || kDefaultMaxBsonMessageSize;
  24. this[kBuffer] = new utils_1.BufferPool();
  25. }
  26. _write(chunk, _, callback) {
  27. this[kBuffer].append(chunk);
  28. processIncomingData(this, callback);
  29. }
  30. _read( /* size */) {
  31. // NOTE: This implementation is empty because we explicitly push data to be read
  32. // when `writeMessage` is called.
  33. return;
  34. }
  35. writeCommand(command, operationDescription) {
  36. // TODO: agreed compressor should live in `StreamDescription`
  37. const compressorName = operationDescription && operationDescription.agreedCompressor
  38. ? operationDescription.agreedCompressor
  39. : 'none';
  40. if (compressorName === 'none' || !canCompress(command)) {
  41. const data = command.toBin();
  42. this.push(Array.isArray(data) ? Buffer.concat(data) : data);
  43. return;
  44. }
  45. // otherwise, compress the message
  46. const concatenatedOriginalCommandBuffer = Buffer.concat(command.toBin());
  47. const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE);
  48. // Extract information needed for OP_COMPRESSED from the uncompressed message
  49. const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12);
  50. // Compress the message body
  51. (0, compression_1.compress)({ options: operationDescription }, messageToBeCompressed, (err, compressedMessage) => {
  52. if (err || !compressedMessage) {
  53. operationDescription.cb(err);
  54. return;
  55. }
  56. // Create the msgHeader of OP_COMPRESSED
  57. const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE);
  58. msgHeader.writeInt32LE(MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, 0); // messageLength
  59. msgHeader.writeInt32LE(command.requestId, 4); // requestID
  60. msgHeader.writeInt32LE(0, 8); // responseTo (zero)
  61. msgHeader.writeInt32LE(constants_1.OP_COMPRESSED, 12); // opCode
  62. // Create the compression details of OP_COMPRESSED
  63. const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE);
  64. compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode
  65. compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader
  66. compressionDetails.writeUInt8(compression_1.Compressor[compressorName], 8); // compressorID
  67. this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage]));
  68. });
  69. }
  70. }
  71. exports.MessageStream = MessageStream;
  72. // Return whether a command contains an uncompressible command term
  73. // Will return true if command contains no uncompressible command terms
  74. function canCompress(command) {
  75. const commandDoc = command instanceof commands_1.Msg ? command.command : command.query;
  76. const commandName = Object.keys(commandDoc)[0];
  77. return !compression_1.uncompressibleCommands.has(commandName);
  78. }
  79. function processIncomingData(stream, callback) {
  80. const buffer = stream[kBuffer];
  81. if (buffer.length < 4) {
  82. callback();
  83. return;
  84. }
  85. const sizeOfMessage = buffer.peek(4).readInt32LE();
  86. if (sizeOfMessage < 0) {
  87. callback(new error_1.MongoParseError(`Invalid message size: ${sizeOfMessage}`));
  88. return;
  89. }
  90. if (sizeOfMessage > stream.maxBsonMessageSize) {
  91. callback(new error_1.MongoParseError(`Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}`));
  92. return;
  93. }
  94. if (sizeOfMessage > buffer.length) {
  95. callback();
  96. return;
  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. let ResponseType = messageHeader.opCode === constants_1.OP_MSG ? commands_1.BinMsg : commands_1.Response;
  106. if (messageHeader.opCode !== constants_1.OP_COMPRESSED) {
  107. const messageBody = message.slice(MESSAGE_HEADER_SIZE);
  108. stream.emit('message', new ResponseType(message, messageHeader, messageBody));
  109. if (buffer.length >= 4) {
  110. processIncomingData(stream, callback);
  111. }
  112. else {
  113. callback();
  114. }
  115. return;
  116. }
  117. messageHeader.fromCompressed = true;
  118. messageHeader.opCode = message.readInt32LE(MESSAGE_HEADER_SIZE);
  119. messageHeader.length = message.readInt32LE(MESSAGE_HEADER_SIZE + 4);
  120. const compressorID = message[MESSAGE_HEADER_SIZE + 8];
  121. const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9);
  122. // recalculate based on wrapped opcode
  123. ResponseType = messageHeader.opCode === constants_1.OP_MSG ? commands_1.BinMsg : commands_1.Response;
  124. (0, compression_1.decompress)(compressorID, compressedBuffer, (err, messageBody) => {
  125. if (err || !messageBody) {
  126. callback(err);
  127. return;
  128. }
  129. if (messageBody.length !== messageHeader.length) {
  130. callback(new error_1.MongoDecompressionError('Message body and message header must be the same length'));
  131. return;
  132. }
  133. stream.emit('message', new ResponseType(message, messageHeader, messageBody));
  134. if (buffer.length >= 4) {
  135. processIncomingData(stream, callback);
  136. }
  137. else {
  138. callback();
  139. }
  140. });
  141. }
  142. //# sourceMappingURL=message_stream.js.map