connection.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.hasSessionSupport = exports.CryptoConnection = exports.Connection = void 0;
  4. const bson_1 = require("../bson");
  5. const constants_1 = require("../constants");
  6. const error_1 = require("../error");
  7. const mongo_types_1 = require("../mongo_types");
  8. const read_preference_1 = require("../read_preference");
  9. const sessions_1 = require("../sessions");
  10. const utils_1 = require("../utils");
  11. const command_monitoring_events_1 = require("./command_monitoring_events");
  12. const commands_1 = require("./commands");
  13. const message_stream_1 = require("./message_stream");
  14. const stream_description_1 = require("./stream_description");
  15. const shared_1 = require("./wire_protocol/shared");
  16. /** @internal */
  17. const kStream = Symbol('stream');
  18. /** @internal */
  19. const kQueue = Symbol('queue');
  20. /** @internal */
  21. const kMessageStream = Symbol('messageStream');
  22. /** @internal */
  23. const kGeneration = Symbol('generation');
  24. /** @internal */
  25. const kLastUseTime = Symbol('lastUseTime');
  26. /** @internal */
  27. const kClusterTime = Symbol('clusterTime');
  28. /** @internal */
  29. const kDescription = Symbol('description');
  30. /** @internal */
  31. const kHello = Symbol('hello');
  32. /** @internal */
  33. const kAutoEncrypter = Symbol('autoEncrypter');
  34. /** @internal */
  35. const kFullResult = Symbol('fullResult');
  36. /** @internal */
  37. class Connection extends mongo_types_1.TypedEventEmitter {
  38. constructor(stream, options) {
  39. var _a, _b;
  40. super();
  41. this.id = options.id;
  42. this.address = streamIdentifier(stream, options);
  43. this.socketTimeoutMS = (_a = options.socketTimeoutMS) !== null && _a !== void 0 ? _a : 0;
  44. this.monitorCommands = options.monitorCommands;
  45. this.serverApi = options.serverApi;
  46. this.closed = false;
  47. this.destroyed = false;
  48. this[kDescription] = new stream_description_1.StreamDescription(this.address, options);
  49. this[kGeneration] = options.generation;
  50. this[kLastUseTime] = (0, utils_1.now)();
  51. // setup parser stream and message handling
  52. this[kQueue] = new Map();
  53. this[kMessageStream] = new message_stream_1.MessageStream({
  54. ...options,
  55. maxBsonMessageSize: (_b = this.hello) === null || _b === void 0 ? void 0 : _b.maxBsonMessageSize
  56. });
  57. this[kMessageStream].on('message', messageHandler(this));
  58. this[kStream] = stream;
  59. stream.on('error', () => {
  60. /* ignore errors, listen to `close` instead */
  61. });
  62. this[kMessageStream].on('error', error => this.handleIssue({ destroy: error }));
  63. stream.on('close', () => this.handleIssue({ isClose: true }));
  64. stream.on('timeout', () => this.handleIssue({ isTimeout: true, destroy: true }));
  65. // hook the message stream up to the passed in stream
  66. stream.pipe(this[kMessageStream]);
  67. this[kMessageStream].pipe(stream);
  68. }
  69. get description() {
  70. return this[kDescription];
  71. }
  72. get hello() {
  73. return this[kHello];
  74. }
  75. // the `connect` method stores the result of the handshake hello on the connection
  76. set hello(response) {
  77. this[kDescription].receiveResponse(response);
  78. this[kDescription] = Object.freeze(this[kDescription]);
  79. // TODO: remove this, and only use the `StreamDescription` in the future
  80. this[kHello] = response;
  81. }
  82. get serviceId() {
  83. var _a;
  84. return (_a = this.hello) === null || _a === void 0 ? void 0 : _a.serviceId;
  85. }
  86. get loadBalanced() {
  87. return this.description.loadBalanced;
  88. }
  89. get generation() {
  90. return this[kGeneration] || 0;
  91. }
  92. set generation(generation) {
  93. this[kGeneration] = generation;
  94. }
  95. get idleTime() {
  96. return (0, utils_1.calculateDurationInMs)(this[kLastUseTime]);
  97. }
  98. get clusterTime() {
  99. return this[kClusterTime];
  100. }
  101. get stream() {
  102. return this[kStream];
  103. }
  104. markAvailable() {
  105. this[kLastUseTime] = (0, utils_1.now)();
  106. }
  107. handleIssue(issue) {
  108. if (this.closed) {
  109. return;
  110. }
  111. if (issue.destroy) {
  112. this[kStream].destroy(typeof issue.destroy === 'boolean' ? undefined : issue.destroy);
  113. }
  114. this.closed = true;
  115. for (const [, op] of this[kQueue]) {
  116. if (issue.isTimeout) {
  117. op.cb(new error_1.MongoNetworkTimeoutError(`connection ${this.id} to ${this.address} timed out`, {
  118. beforeHandshake: this.hello == null
  119. }));
  120. }
  121. else if (issue.isClose) {
  122. op.cb(new error_1.MongoNetworkError(`connection ${this.id} to ${this.address} closed`));
  123. }
  124. else {
  125. op.cb(typeof issue.destroy === 'boolean' ? undefined : issue.destroy);
  126. }
  127. }
  128. this[kQueue].clear();
  129. this.emit(Connection.CLOSE);
  130. }
  131. destroy(options, callback) {
  132. if (typeof options === 'function') {
  133. callback = options;
  134. options = { force: false };
  135. }
  136. this.removeAllListeners(Connection.PINNED);
  137. this.removeAllListeners(Connection.UNPINNED);
  138. options = Object.assign({ force: false }, options);
  139. if (this[kStream] == null || this.destroyed) {
  140. this.destroyed = true;
  141. if (typeof callback === 'function') {
  142. callback();
  143. }
  144. return;
  145. }
  146. if (options.force) {
  147. this[kStream].destroy();
  148. this.destroyed = true;
  149. if (typeof callback === 'function') {
  150. callback();
  151. }
  152. return;
  153. }
  154. this[kStream].end(() => {
  155. this.destroyed = true;
  156. if (typeof callback === 'function') {
  157. callback();
  158. }
  159. });
  160. }
  161. /** @internal */
  162. command(ns, cmd, options, callback) {
  163. if (!(ns instanceof utils_1.MongoDBNamespace)) {
  164. // TODO(NODE-3483): Replace this with a MongoCommandError
  165. throw new error_1.MongoRuntimeError('Must provide a MongoDBNamespace instance');
  166. }
  167. const readPreference = (0, shared_1.getReadPreference)(cmd, options);
  168. const shouldUseOpMsg = supportsOpMsg(this);
  169. const session = options === null || options === void 0 ? void 0 : options.session;
  170. let clusterTime = this.clusterTime;
  171. let finalCmd = Object.assign({}, cmd);
  172. if (this.serverApi) {
  173. const { version, strict, deprecationErrors } = this.serverApi;
  174. finalCmd.apiVersion = version;
  175. if (strict != null)
  176. finalCmd.apiStrict = strict;
  177. if (deprecationErrors != null)
  178. finalCmd.apiDeprecationErrors = deprecationErrors;
  179. }
  180. if (hasSessionSupport(this) && session) {
  181. if (session.clusterTime &&
  182. clusterTime &&
  183. session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime)) {
  184. clusterTime = session.clusterTime;
  185. }
  186. const err = (0, sessions_1.applySession)(session, finalCmd, options);
  187. if (err) {
  188. return callback(err);
  189. }
  190. }
  191. // if we have a known cluster time, gossip it
  192. if (clusterTime) {
  193. finalCmd.$clusterTime = clusterTime;
  194. }
  195. if ((0, shared_1.isSharded)(this) && !shouldUseOpMsg && readPreference && readPreference.mode !== 'primary') {
  196. finalCmd = {
  197. $query: finalCmd,
  198. $readPreference: readPreference.toJSON()
  199. };
  200. }
  201. const commandOptions = Object.assign({
  202. command: true,
  203. numberToSkip: 0,
  204. numberToReturn: -1,
  205. checkKeys: false,
  206. // This value is not overridable
  207. secondaryOk: readPreference.secondaryOk()
  208. }, options);
  209. const cmdNs = `${ns.db}.$cmd`;
  210. const message = shouldUseOpMsg
  211. ? new commands_1.Msg(cmdNs, finalCmd, commandOptions)
  212. : new commands_1.Query(cmdNs, finalCmd, commandOptions);
  213. try {
  214. write(this, message, commandOptions, callback);
  215. }
  216. catch (err) {
  217. callback(err);
  218. }
  219. }
  220. /** @internal */
  221. query(ns, cmd, options, callback) {
  222. var _a;
  223. const isExplain = cmd.$explain != null;
  224. const readPreference = (_a = options.readPreference) !== null && _a !== void 0 ? _a : read_preference_1.ReadPreference.primary;
  225. const batchSize = options.batchSize || 0;
  226. const limit = options.limit;
  227. const numberToSkip = options.skip || 0;
  228. let numberToReturn = 0;
  229. if (limit &&
  230. (limit < 0 || (limit !== 0 && limit < batchSize) || (limit > 0 && batchSize === 0))) {
  231. numberToReturn = limit;
  232. }
  233. else {
  234. numberToReturn = batchSize;
  235. }
  236. if (isExplain) {
  237. // nToReturn must be 0 (match all) or negative (match N and close cursor)
  238. // nToReturn > 0 will give explain results equivalent to limit(0)
  239. numberToReturn = -Math.abs(limit || 0);
  240. }
  241. const queryOptions = {
  242. numberToSkip,
  243. numberToReturn,
  244. pre32Limit: typeof limit === 'number' ? limit : undefined,
  245. checkKeys: false,
  246. secondaryOk: readPreference.secondaryOk()
  247. };
  248. if (options.projection) {
  249. queryOptions.returnFieldSelector = options.projection;
  250. }
  251. const query = new commands_1.Query(ns.toString(), cmd, queryOptions);
  252. if (typeof options.tailable === 'boolean') {
  253. query.tailable = options.tailable;
  254. }
  255. if (typeof options.oplogReplay === 'boolean') {
  256. query.oplogReplay = options.oplogReplay;
  257. }
  258. if (typeof options.timeout === 'boolean') {
  259. query.noCursorTimeout = !options.timeout;
  260. }
  261. else if (typeof options.noCursorTimeout === 'boolean') {
  262. query.noCursorTimeout = options.noCursorTimeout;
  263. }
  264. if (typeof options.awaitData === 'boolean') {
  265. query.awaitData = options.awaitData;
  266. }
  267. if (typeof options.partial === 'boolean') {
  268. query.partial = options.partial;
  269. }
  270. write(this, query, { [kFullResult]: true, ...(0, bson_1.pluckBSONSerializeOptions)(options) }, (err, result) => {
  271. if (err || !result)
  272. return callback(err, result);
  273. if (isExplain && result.documents && result.documents[0]) {
  274. return callback(undefined, result.documents[0]);
  275. }
  276. callback(undefined, result);
  277. });
  278. }
  279. /** @internal */
  280. getMore(ns, cursorId, options, callback) {
  281. const fullResult = !!options[kFullResult];
  282. const wireVersion = (0, utils_1.maxWireVersion)(this);
  283. if (!cursorId) {
  284. // TODO(NODE-3483): Replace this with a MongoCommandError
  285. callback(new error_1.MongoRuntimeError('Invalid internal cursor state, no known cursor id'));
  286. return;
  287. }
  288. if (wireVersion < 4) {
  289. const getMoreOp = new commands_1.GetMore(ns.toString(), cursorId, { numberToReturn: options.batchSize });
  290. const queryOptions = (0, shared_1.applyCommonQueryOptions)({}, Object.assign(options, { ...(0, bson_1.pluckBSONSerializeOptions)(options) }));
  291. queryOptions[kFullResult] = true;
  292. queryOptions.command = true;
  293. write(this, getMoreOp, queryOptions, (err, response) => {
  294. if (fullResult)
  295. return callback(err, response);
  296. if (err)
  297. return callback(err);
  298. callback(undefined, { cursor: { id: response.cursorId, nextBatch: response.documents } });
  299. });
  300. return;
  301. }
  302. const getMoreCmd = {
  303. getMore: cursorId,
  304. collection: ns.collection
  305. };
  306. if (typeof options.batchSize === 'number') {
  307. getMoreCmd.batchSize = Math.abs(options.batchSize);
  308. }
  309. if (typeof options.maxAwaitTimeMS === 'number') {
  310. getMoreCmd.maxTimeMS = options.maxAwaitTimeMS;
  311. }
  312. const commandOptions = Object.assign({
  313. returnFieldSelector: null,
  314. documentsReturnedIn: 'nextBatch'
  315. }, options);
  316. this.command(ns, getMoreCmd, commandOptions, callback);
  317. }
  318. /** @internal */
  319. killCursors(ns, cursorIds, options, callback) {
  320. if (!cursorIds || !Array.isArray(cursorIds)) {
  321. // TODO(NODE-3483): Replace this with a MongoCommandError
  322. throw new error_1.MongoRuntimeError(`Invalid list of cursor ids provided: ${cursorIds}`);
  323. }
  324. if ((0, utils_1.maxWireVersion)(this) < 4) {
  325. try {
  326. write(this, new commands_1.KillCursor(ns.toString(), cursorIds), { noResponse: true, ...options }, callback);
  327. }
  328. catch (err) {
  329. callback(err);
  330. }
  331. return;
  332. }
  333. this.command(ns, { killCursors: ns.collection, cursors: cursorIds }, { [kFullResult]: true, ...options }, (err, response) => {
  334. if (err || !response)
  335. return callback(err);
  336. if (response.cursorNotFound) {
  337. return callback(new error_1.MongoNetworkError('cursor killed or timed out'), null);
  338. }
  339. if (!Array.isArray(response.documents) || response.documents.length === 0) {
  340. return callback(
  341. // TODO(NODE-3483)
  342. new error_1.MongoRuntimeError(`invalid killCursors result returned for cursor id ${cursorIds[0]}`));
  343. }
  344. callback(undefined, response.documents[0]);
  345. });
  346. }
  347. }
  348. exports.Connection = Connection;
  349. /** @event */
  350. Connection.COMMAND_STARTED = constants_1.COMMAND_STARTED;
  351. /** @event */
  352. Connection.COMMAND_SUCCEEDED = constants_1.COMMAND_SUCCEEDED;
  353. /** @event */
  354. Connection.COMMAND_FAILED = constants_1.COMMAND_FAILED;
  355. /** @event */
  356. Connection.CLUSTER_TIME_RECEIVED = constants_1.CLUSTER_TIME_RECEIVED;
  357. /** @event */
  358. Connection.CLOSE = constants_1.CLOSE;
  359. /** @event */
  360. Connection.MESSAGE = constants_1.MESSAGE;
  361. /** @event */
  362. Connection.PINNED = constants_1.PINNED;
  363. /** @event */
  364. Connection.UNPINNED = constants_1.UNPINNED;
  365. /** @internal */
  366. class CryptoConnection extends Connection {
  367. constructor(stream, options) {
  368. super(stream, options);
  369. this[kAutoEncrypter] = options.autoEncrypter;
  370. }
  371. /** @internal @override */
  372. command(ns, cmd, options, callback) {
  373. const autoEncrypter = this[kAutoEncrypter];
  374. if (!autoEncrypter) {
  375. return callback(new error_1.MongoMissingDependencyError('No AutoEncrypter available for encryption'));
  376. }
  377. const serverWireVersion = (0, utils_1.maxWireVersion)(this);
  378. if (serverWireVersion === 0) {
  379. // This means the initial handshake hasn't happened yet
  380. return super.command(ns, cmd, options, callback);
  381. }
  382. if (serverWireVersion < 8) {
  383. callback(new error_1.MongoCompatibilityError('Auto-encryption requires a minimum MongoDB version of 4.2'));
  384. return;
  385. }
  386. autoEncrypter.encrypt(ns.toString(), cmd, options, (err, encrypted) => {
  387. if (err || encrypted == null) {
  388. callback(err, null);
  389. return;
  390. }
  391. super.command(ns, encrypted, options, (err, response) => {
  392. if (err || response == null) {
  393. callback(err, response);
  394. return;
  395. }
  396. autoEncrypter.decrypt(response, options, callback);
  397. });
  398. });
  399. }
  400. }
  401. exports.CryptoConnection = CryptoConnection;
  402. /** @internal */
  403. function hasSessionSupport(conn) {
  404. const description = conn.description;
  405. return description.logicalSessionTimeoutMinutes != null || !!description.loadBalanced;
  406. }
  407. exports.hasSessionSupport = hasSessionSupport;
  408. function supportsOpMsg(conn) {
  409. const description = conn.description;
  410. if (description == null) {
  411. return false;
  412. }
  413. return (0, utils_1.maxWireVersion)(conn) >= 6 && !description.__nodejs_mock_server__;
  414. }
  415. function messageHandler(conn) {
  416. return function messageHandler(message) {
  417. // always emit the message, in case we are streaming
  418. conn.emit('message', message);
  419. const operationDescription = conn[kQueue].get(message.responseTo);
  420. if (!operationDescription) {
  421. return;
  422. }
  423. const callback = operationDescription.cb;
  424. // SERVER-45775: For exhaust responses we should be able to use the same requestId to
  425. // track response, however the server currently synthetically produces remote requests
  426. // making the `responseTo` change on each response
  427. conn[kQueue].delete(message.responseTo);
  428. if ('moreToCome' in message && message.moreToCome) {
  429. // requeue the callback for next synthetic request
  430. conn[kQueue].set(message.requestId, operationDescription);
  431. }
  432. else if (operationDescription.socketTimeoutOverride) {
  433. conn[kStream].setTimeout(conn.socketTimeoutMS);
  434. }
  435. try {
  436. // Pass in the entire description because it has BSON parsing options
  437. message.parse(operationDescription);
  438. }
  439. catch (err) {
  440. // If this error is generated by our own code, it will already have the correct class applied
  441. // if it is not, then it is coming from a catastrophic data parse failure or the BSON library
  442. // in either case, it should not be wrapped
  443. callback(err);
  444. return;
  445. }
  446. if (message.documents[0]) {
  447. const document = message.documents[0];
  448. const session = operationDescription.session;
  449. if (session) {
  450. (0, sessions_1.updateSessionFromResponse)(session, document);
  451. }
  452. if (document.$clusterTime) {
  453. conn[kClusterTime] = document.$clusterTime;
  454. conn.emit(Connection.CLUSTER_TIME_RECEIVED, document.$clusterTime);
  455. }
  456. if (operationDescription.command) {
  457. if (document.writeConcernError) {
  458. callback(new error_1.MongoWriteConcernError(document.writeConcernError, document));
  459. return;
  460. }
  461. if (document.ok === 0 || document.$err || document.errmsg || document.code) {
  462. callback(new error_1.MongoServerError(document));
  463. return;
  464. }
  465. }
  466. else {
  467. // Pre 3.2 support
  468. if (document.ok === 0 || document.$err || document.errmsg) {
  469. callback(new error_1.MongoServerError(document));
  470. return;
  471. }
  472. }
  473. }
  474. callback(undefined, operationDescription.fullResult ? message : message.documents[0]);
  475. };
  476. }
  477. function streamIdentifier(stream, options) {
  478. if (options.proxyHost) {
  479. // If proxy options are specified, the properties of `stream` itself
  480. // will not accurately reflect what endpoint this is connected to.
  481. return options.hostAddress.toString();
  482. }
  483. if (typeof stream.address === 'function') {
  484. return `${stream.remoteAddress}:${stream.remotePort}`;
  485. }
  486. return (0, utils_1.uuidV4)().toString('hex');
  487. }
  488. function write(conn, command, options, callback) {
  489. if (typeof options === 'function') {
  490. callback = options;
  491. }
  492. options = options !== null && options !== void 0 ? options : {};
  493. const operationDescription = {
  494. requestId: command.requestId,
  495. cb: callback,
  496. session: options.session,
  497. fullResult: !!options[kFullResult],
  498. noResponse: typeof options.noResponse === 'boolean' ? options.noResponse : false,
  499. documentsReturnedIn: options.documentsReturnedIn,
  500. command: !!options.command,
  501. // for BSON parsing
  502. promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true,
  503. promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true,
  504. promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false,
  505. bsonRegExp: typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : false,
  506. enableUtf8Validation: typeof options.enableUtf8Validation === 'boolean' ? options.enableUtf8Validation : true,
  507. raw: typeof options.raw === 'boolean' ? options.raw : false,
  508. started: 0
  509. };
  510. if (conn[kDescription] && conn[kDescription].compressor) {
  511. operationDescription.agreedCompressor = conn[kDescription].compressor;
  512. if (conn[kDescription].zlibCompressionLevel) {
  513. operationDescription.zlibCompressionLevel = conn[kDescription].zlibCompressionLevel;
  514. }
  515. }
  516. if (typeof options.socketTimeoutMS === 'number') {
  517. operationDescription.socketTimeoutOverride = true;
  518. conn[kStream].setTimeout(options.socketTimeoutMS);
  519. }
  520. // if command monitoring is enabled we need to modify the callback here
  521. if (conn.monitorCommands) {
  522. conn.emit(Connection.COMMAND_STARTED, new command_monitoring_events_1.CommandStartedEvent(conn, command));
  523. operationDescription.started = (0, utils_1.now)();
  524. operationDescription.cb = (err, reply) => {
  525. if (err) {
  526. conn.emit(Connection.COMMAND_FAILED, new command_monitoring_events_1.CommandFailedEvent(conn, command, err, operationDescription.started));
  527. }
  528. else {
  529. if (reply && (reply.ok === 0 || reply.$err)) {
  530. conn.emit(Connection.COMMAND_FAILED, new command_monitoring_events_1.CommandFailedEvent(conn, command, reply, operationDescription.started));
  531. }
  532. else {
  533. conn.emit(Connection.COMMAND_SUCCEEDED, new command_monitoring_events_1.CommandSucceededEvent(conn, command, reply, operationDescription.started));
  534. }
  535. }
  536. if (typeof callback === 'function') {
  537. callback(err, reply);
  538. }
  539. };
  540. }
  541. if (!operationDescription.noResponse) {
  542. conn[kQueue].set(operationDescription.requestId, operationDescription);
  543. }
  544. try {
  545. conn[kMessageStream].writeCommand(command, operationDescription);
  546. }
  547. catch (e) {
  548. if (!operationDescription.noResponse) {
  549. conn[kQueue].delete(operationDescription.requestId);
  550. operationDescription.cb(e);
  551. return;
  552. }
  553. }
  554. if (operationDescription.noResponse) {
  555. operationDescription.cb();
  556. }
  557. }
  558. //# sourceMappingURL=connection.js.map