mongo_client.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. import type { TcpNetConnectOpts } from 'net';
  2. import type { ConnectionOptions as TLSConnectionOptions, TLSSocketOptions } from 'tls';
  3. import { promisify } from 'util';
  4. import { type BSONSerializeOptions, type Document, resolveBSONOptions } from './bson';
  5. import { ChangeStream, type ChangeStreamDocument, type ChangeStreamOptions } from './change_stream';
  6. import {
  7. type AuthMechanismProperties,
  8. DEFAULT_ALLOWED_HOSTS,
  9. type MongoCredentials
  10. } from './cmap/auth/mongo_credentials';
  11. import { AuthMechanism } from './cmap/auth/providers';
  12. import type { LEGAL_TCP_SOCKET_OPTIONS, LEGAL_TLS_SOCKET_OPTIONS } from './cmap/connect';
  13. import type { Connection } from './cmap/connection';
  14. import type { ClientMetadata } from './cmap/handshake/client_metadata';
  15. import type { CompressorName } from './cmap/wire_protocol/compression';
  16. import { parseOptions, resolveSRVRecord } from './connection_string';
  17. import { MONGO_CLIENT_EVENTS } from './constants';
  18. import { Db, type DbOptions } from './db';
  19. import type { AutoEncrypter, AutoEncryptionOptions } from './deps';
  20. import type { Encrypter } from './encrypter';
  21. import { MongoInvalidArgumentError } from './error';
  22. import { MongoLogger, type MongoLoggerOptions } from './mongo_logger';
  23. import { TypedEventEmitter } from './mongo_types';
  24. import type { ReadConcern, ReadConcernLevel, ReadConcernLike } from './read_concern';
  25. import { ReadPreference, type ReadPreferenceMode } from './read_preference';
  26. import type { TagSet } from './sdam/server_description';
  27. import { readPreferenceServerSelector } from './sdam/server_selection';
  28. import type { SrvPoller } from './sdam/srv_polling';
  29. import { Topology, type TopologyEvents } from './sdam/topology';
  30. import { ClientSession, type ClientSessionOptions, ServerSessionPool } from './sessions';
  31. import {
  32. type HostAddress,
  33. hostMatchesWildcards,
  34. type MongoDBNamespace,
  35. ns,
  36. resolveOptions
  37. } from './utils';
  38. import type { W, WriteConcern, WriteConcernSettings } from './write_concern';
  39. /** @public */
  40. export const ServerApiVersion = Object.freeze({
  41. v1: '1'
  42. } as const);
  43. /** @public */
  44. export type ServerApiVersion = (typeof ServerApiVersion)[keyof typeof ServerApiVersion];
  45. /** @public */
  46. export interface ServerApi {
  47. version: ServerApiVersion;
  48. strict?: boolean;
  49. deprecationErrors?: boolean;
  50. }
  51. /** @public */
  52. export interface DriverInfo {
  53. name?: string;
  54. version?: string;
  55. platform?: string;
  56. }
  57. /** @public */
  58. export interface Auth {
  59. /** The username for auth */
  60. username?: string;
  61. /** The password for auth */
  62. password?: string;
  63. }
  64. /** @public */
  65. export interface PkFactory {
  66. createPk(): any; // TODO: when js-bson is typed, function should return some BSON type
  67. }
  68. /** @public */
  69. export type SupportedTLSConnectionOptions = Pick<
  70. TLSConnectionOptions,
  71. Extract<keyof TLSConnectionOptions, (typeof LEGAL_TLS_SOCKET_OPTIONS)[number]>
  72. >;
  73. /** @public */
  74. export type SupportedTLSSocketOptions = Pick<
  75. TLSSocketOptions,
  76. Extract<keyof TLSSocketOptions, (typeof LEGAL_TLS_SOCKET_OPTIONS)[number]>
  77. >;
  78. /** @public */
  79. export type SupportedSocketOptions = Pick<
  80. TcpNetConnectOpts,
  81. (typeof LEGAL_TCP_SOCKET_OPTIONS)[number]
  82. >;
  83. /** @public */
  84. export type SupportedNodeConnectionOptions = SupportedTLSConnectionOptions &
  85. SupportedTLSSocketOptions &
  86. SupportedSocketOptions;
  87. /**
  88. * Describes all possible URI query options for the mongo client
  89. * @public
  90. * @see https://www.mongodb.com/docs/manual/reference/connection-string
  91. */
  92. export interface MongoClientOptions extends BSONSerializeOptions, SupportedNodeConnectionOptions {
  93. /** Specifies the name of the replica set, if the mongod is a member of a replica set. */
  94. replicaSet?: string;
  95. /** Enables or disables TLS/SSL for the connection. */
  96. tls?: boolean;
  97. /** A boolean to enable or disables TLS/SSL for the connection. (The ssl option is equivalent to the tls option.) */
  98. ssl?: boolean;
  99. /**
  100. * Specifies the location of a local TLS Certificate
  101. * @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
  102. */
  103. tlsCertificateFile?: string;
  104. /** Specifies the location of a local .pem file that contains either the client's TLS/SSL certificate and key or only the client's TLS/SSL key when tlsCertificateFile is used to provide the certificate. */
  105. tlsCertificateKeyFile?: string;
  106. /** Specifies the password to de-crypt the tlsCertificateKeyFile. */
  107. tlsCertificateKeyFilePassword?: string;
  108. /** Specifies the location of a local .pem file that contains the root certificate chain from the Certificate Authority. This file is used to validate the certificate presented by the mongod/mongos instance. */
  109. tlsCAFile?: string;
  110. /** Bypasses validation of the certificates presented by the mongod/mongos instance */
  111. tlsAllowInvalidCertificates?: boolean;
  112. /** Disables hostname validation of the certificate presented by the mongod/mongos instance. */
  113. tlsAllowInvalidHostnames?: boolean;
  114. /** Disables various certificate validations. */
  115. tlsInsecure?: boolean;
  116. /** The time in milliseconds to attempt a connection before timing out. */
  117. connectTimeoutMS?: number;
  118. /** The time in milliseconds to attempt a send or receive on a socket before the attempt times out. */
  119. socketTimeoutMS?: number;
  120. /** An array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance. */
  121. compressors?: CompressorName[] | string;
  122. /** An integer that specifies the compression level if using zlib for network compression. */
  123. zlibCompressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined;
  124. /** The maximum number of hosts to connect to when using an srv connection string, a setting of `0` means unlimited hosts */
  125. srvMaxHosts?: number;
  126. /**
  127. * Modifies the srv URI to look like:
  128. *
  129. * `_{srvServiceName}._tcp.{hostname}.{domainname}`
  130. *
  131. * Querying this DNS URI is expected to respond with SRV records
  132. */
  133. srvServiceName?: string;
  134. /** The maximum number of connections in the connection pool. */
  135. maxPoolSize?: number;
  136. /** The minimum number of connections in the connection pool. */
  137. minPoolSize?: number;
  138. /** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */
  139. maxConnecting?: number;
  140. /** The maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed. */
  141. maxIdleTimeMS?: number;
  142. /** The maximum time in milliseconds that a thread can wait for a connection to become available. */
  143. waitQueueTimeoutMS?: number;
  144. /** Specify a read concern for the collection (only MongoDB 3.2 or higher supported) */
  145. readConcern?: ReadConcernLike;
  146. /** The level of isolation */
  147. readConcernLevel?: ReadConcernLevel;
  148. /** Specifies the read preferences for this connection */
  149. readPreference?: ReadPreferenceMode | ReadPreference;
  150. /** Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. */
  151. maxStalenessSeconds?: number;
  152. /** Specifies the tags document as a comma-separated list of colon-separated key-value pairs. */
  153. readPreferenceTags?: TagSet[];
  154. /** The auth settings for when connection to server. */
  155. auth?: Auth;
  156. /** Specify the database name associated with the user’s credentials. */
  157. authSource?: string;
  158. /** Specify the authentication mechanism that MongoDB will use to authenticate the connection. */
  159. authMechanism?: AuthMechanism;
  160. /** Specify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs. */
  161. authMechanismProperties?: AuthMechanismProperties;
  162. /** The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. */
  163. localThresholdMS?: number;
  164. /** Specifies how long (in milliseconds) to block for server selection before throwing an exception. */
  165. serverSelectionTimeoutMS?: number;
  166. /** heartbeatFrequencyMS controls when the driver checks the state of the MongoDB deployment. Specify the interval (in milliseconds) between checks, counted from the end of the previous check until the beginning of the next one. */
  167. heartbeatFrequencyMS?: number;
  168. /** Sets the minimum heartbeat frequency. In the event that the driver has to frequently re-check a server's availability, it will wait at least this long since the previous check to avoid wasted effort. */
  169. minHeartbeatFrequencyMS?: number;
  170. /** The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections */
  171. appName?: string;
  172. /** Enables retryable reads. */
  173. retryReads?: boolean;
  174. /** Enable retryable writes. */
  175. retryWrites?: boolean;
  176. /** Allow a driver to force a Single topology type with a connection string containing one host */
  177. directConnection?: boolean;
  178. /** Instruct the driver it is connecting to a load balancer fronting a mongos like service */
  179. loadBalanced?: boolean;
  180. /**
  181. * The write concern w value
  182. * @deprecated Please use the `writeConcern` option instead
  183. */
  184. w?: W;
  185. /**
  186. * The write concern timeout
  187. * @deprecated Please use the `writeConcern` option instead
  188. */
  189. wtimeoutMS?: number;
  190. /**
  191. * The journal write concern
  192. * @deprecated Please use the `writeConcern` option instead
  193. */
  194. journal?: boolean;
  195. /**
  196. * A MongoDB WriteConcern, which describes the level of acknowledgement
  197. * requested from MongoDB for write operations.
  198. *
  199. * @see https://www.mongodb.com/docs/manual/reference/write-concern/
  200. */
  201. writeConcern?: WriteConcern | WriteConcernSettings;
  202. /**
  203. * Validate mongod server certificate against Certificate Authority
  204. * @deprecated Will be removed in the next major version. Please use tlsAllowInvalidCertificates instead.
  205. */
  206. sslValidate?: boolean;
  207. /**
  208. * SSL Certificate file path.
  209. * @deprecated Will be removed in the next major version. Please use tlsCAFile instead.
  210. */
  211. sslCA?: string;
  212. /**
  213. * SSL Certificate file path.
  214. * @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
  215. */
  216. sslCert?: string;
  217. /**
  218. * SSL Key file file path.
  219. * @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
  220. */
  221. sslKey?: string;
  222. /**
  223. * SSL Certificate pass phrase.
  224. * @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFilePassword instead.
  225. */
  226. sslPass?: string;
  227. /**
  228. * SSL Certificate revocation list file path.
  229. * @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
  230. */
  231. sslCRL?: string;
  232. /** TCP Connection no delay */
  233. noDelay?: boolean;
  234. /** @deprecated TCP Connection keep alive enabled. Will not be able to turn off in the future. */
  235. keepAlive?: boolean;
  236. /**
  237. * @deprecated The number of milliseconds to wait before initiating keepAlive on the TCP socket.
  238. * Will not be configurable in the future.
  239. */
  240. keepAliveInitialDelay?: number;
  241. /** Force server to assign `_id` values instead of driver */
  242. forceServerObjectId?: boolean;
  243. /** A primary key factory function for generation of custom `_id` keys */
  244. pkFactory?: PkFactory;
  245. /** Enable command monitoring for this client */
  246. monitorCommands?: boolean;
  247. /** Server API version */
  248. serverApi?: ServerApi | ServerApiVersion;
  249. /**
  250. * Optionally enable in-use auto encryption
  251. *
  252. * @remarks
  253. * Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error
  254. * (see [libmongocrypt: Auto Encryption Allow-List](https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/client-side-encryption.rst#libmongocrypt-auto-encryption-allow-list)). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts.
  255. *
  256. * Automatic encryption requires the authenticated user to have the [listCollections privilege action](https://www.mongodb.com/docs/manual/reference/command/listCollections/#dbcmd.listCollections).
  257. *
  258. * If a MongoClient with a limited connection pool size (i.e a non-zero maxPoolSize) is configured with AutoEncryptionOptions, a separate internal MongoClient is created if any of the following are true:
  259. * - AutoEncryptionOptions.keyVaultClient is not passed.
  260. * - AutoEncryptionOptions.bypassAutomaticEncryption is false.
  261. *
  262. * If an internal MongoClient is created, it is configured with the same options as the parent MongoClient except minPoolSize is set to 0 and AutoEncryptionOptions is omitted.
  263. */
  264. autoEncryption?: AutoEncryptionOptions;
  265. /** Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver */
  266. driverInfo?: DriverInfo;
  267. /** Configures a Socks5 proxy host used for creating TCP connections. */
  268. proxyHost?: string;
  269. /** Configures a Socks5 proxy port used for creating TCP connections. */
  270. proxyPort?: number;
  271. /** Configures a Socks5 proxy username when the proxy in proxyHost requires username/password authentication. */
  272. proxyUsername?: string;
  273. /** Configures a Socks5 proxy password when the proxy in proxyHost requires username/password authentication. */
  274. proxyPassword?: string;
  275. /** @internal */
  276. srvPoller?: SrvPoller;
  277. /** @internal */
  278. connectionType?: typeof Connection;
  279. /** @internal */
  280. [featureFlag: symbol]: any;
  281. }
  282. /** @public */
  283. export type WithSessionCallback = (session: ClientSession) => Promise<any>;
  284. /** @internal */
  285. export interface MongoClientPrivate {
  286. url: string;
  287. bsonOptions: BSONSerializeOptions;
  288. namespace: MongoDBNamespace;
  289. hasBeenClosed: boolean;
  290. /**
  291. * We keep a reference to the sessions that are acquired from the pool.
  292. * - used to track and close all sessions in client.close() (which is non-standard behavior)
  293. * - used to notify the leak checker in our tests if test author forgot to clean up explicit sessions
  294. */
  295. readonly activeSessions: Set<ClientSession>;
  296. readonly sessionPool: ServerSessionPool;
  297. readonly options: MongoOptions;
  298. readonly readConcern?: ReadConcern;
  299. readonly writeConcern?: WriteConcern;
  300. readonly readPreference: ReadPreference;
  301. readonly isMongoClient: true;
  302. }
  303. /** @public */
  304. export type MongoClientEvents = Pick<TopologyEvents, (typeof MONGO_CLIENT_EVENTS)[number]> & {
  305. // In previous versions the open event emitted a topology, in an effort to no longer
  306. // expose internals but continue to expose this useful event API, it now emits a mongoClient
  307. open(mongoClient: MongoClient): void;
  308. };
  309. /** @internal */
  310. const kOptions = Symbol('options');
  311. /**
  312. * The **MongoClient** class is a class that allows for making Connections to MongoDB.
  313. * @public
  314. *
  315. * @remarks
  316. * The programmatically provided options take precedence over the URI options.
  317. *
  318. * @example
  319. * ```ts
  320. * import { MongoClient } from 'mongodb';
  321. *
  322. * // Enable command monitoring for debugging
  323. * const client = new MongoClient('mongodb://localhost:27017', { monitorCommands: true });
  324. *
  325. * client.on('commandStarted', started => console.log(started));
  326. * client.db().collection('pets');
  327. * await client.insertOne({ name: 'spot', kind: 'dog' });
  328. * ```
  329. */
  330. export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
  331. /** @internal */
  332. s: MongoClientPrivate;
  333. /** @internal */
  334. topology?: Topology;
  335. /** @internal */
  336. override readonly mongoLogger: MongoLogger;
  337. /** @internal */
  338. private connectionLock?: Promise<this>;
  339. /**
  340. * The consolidate, parsed, transformed and merged options.
  341. * @internal
  342. */
  343. [kOptions]: MongoOptions;
  344. constructor(url: string, options?: MongoClientOptions) {
  345. super();
  346. this[kOptions] = parseOptions(url, this, options);
  347. this.mongoLogger = new MongoLogger(this[kOptions].mongoLoggerOptions);
  348. // eslint-disable-next-line @typescript-eslint/no-this-alias
  349. const client = this;
  350. // The internal state
  351. this.s = {
  352. url,
  353. bsonOptions: resolveBSONOptions(this[kOptions]),
  354. namespace: ns('admin'),
  355. hasBeenClosed: false,
  356. sessionPool: new ServerSessionPool(this),
  357. activeSessions: new Set(),
  358. get options() {
  359. return client[kOptions];
  360. },
  361. get readConcern() {
  362. return client[kOptions].readConcern;
  363. },
  364. get writeConcern() {
  365. return client[kOptions].writeConcern;
  366. },
  367. get readPreference() {
  368. return client[kOptions].readPreference;
  369. },
  370. get isMongoClient(): true {
  371. return true;
  372. }
  373. };
  374. }
  375. /** @see MongoOptions */
  376. get options(): Readonly<MongoOptions> {
  377. return Object.freeze({ ...this[kOptions] });
  378. }
  379. get serverApi(): Readonly<ServerApi | undefined> {
  380. return this[kOptions].serverApi && Object.freeze({ ...this[kOptions].serverApi });
  381. }
  382. /**
  383. * Intended for APM use only
  384. * @internal
  385. */
  386. get monitorCommands(): boolean {
  387. return this[kOptions].monitorCommands;
  388. }
  389. set monitorCommands(value: boolean) {
  390. this[kOptions].monitorCommands = value;
  391. }
  392. /**
  393. * @deprecated This method will be removed in the next major version.
  394. */
  395. get autoEncrypter(): AutoEncrypter | undefined {
  396. return this[kOptions].autoEncrypter;
  397. }
  398. get readConcern(): ReadConcern | undefined {
  399. return this.s.readConcern;
  400. }
  401. get writeConcern(): WriteConcern | undefined {
  402. return this.s.writeConcern;
  403. }
  404. get readPreference(): ReadPreference {
  405. return this.s.readPreference;
  406. }
  407. get bsonOptions(): BSONSerializeOptions {
  408. return this.s.bsonOptions;
  409. }
  410. /**
  411. * Connect to MongoDB using a url
  412. *
  413. * @see docs.mongodb.org/manual/reference/connection-string/
  414. */
  415. async connect(): Promise<this> {
  416. if (this.connectionLock) {
  417. return this.connectionLock;
  418. }
  419. try {
  420. this.connectionLock = this._connect();
  421. await this.connectionLock;
  422. } finally {
  423. // release
  424. this.connectionLock = undefined;
  425. }
  426. return this;
  427. }
  428. /**
  429. * Create a topology to open the connection, must be locked to avoid topology leaks in concurrency scenario.
  430. * Locking is enforced by the connect method.
  431. *
  432. * @internal
  433. */
  434. private async _connect(): Promise<this> {
  435. if (this.topology && this.topology.isConnected()) {
  436. return this;
  437. }
  438. const options = this[kOptions];
  439. if (typeof options.srvHost === 'string') {
  440. const hosts = await resolveSRVRecord(options);
  441. for (const [index, host] of hosts.entries()) {
  442. options.hosts[index] = host;
  443. }
  444. }
  445. // It is important to perform validation of hosts AFTER SRV resolution, to check the real hostname,
  446. // but BEFORE we even attempt connecting with a potentially not allowed hostname
  447. if (options.credentials?.mechanism === AuthMechanism.MONGODB_OIDC) {
  448. const allowedHosts =
  449. options.credentials?.mechanismProperties?.ALLOWED_HOSTS || DEFAULT_ALLOWED_HOSTS;
  450. const isServiceAuth = !!options.credentials?.mechanismProperties?.PROVIDER_NAME;
  451. if (!isServiceAuth) {
  452. for (const host of options.hosts) {
  453. if (!hostMatchesWildcards(host.toHostPort().host, allowedHosts)) {
  454. throw new MongoInvalidArgumentError(
  455. `Host '${host}' is not valid for OIDC authentication with ALLOWED_HOSTS of '${allowedHosts.join(
  456. ','
  457. )}'`
  458. );
  459. }
  460. }
  461. }
  462. }
  463. this.topology = new Topology(this, options.hosts, options);
  464. // Events can be emitted before initialization is complete so we have to
  465. // save the reference to the topology on the client ASAP if the event handlers need to access it
  466. this.topology.once(Topology.OPEN, () => this.emit('open', this));
  467. for (const event of MONGO_CLIENT_EVENTS) {
  468. this.topology.on(event, (...args: any[]) => this.emit(event, ...(args as any)));
  469. }
  470. const topologyConnect = async () => {
  471. try {
  472. await promisify(callback => this.topology?.connect(options, callback))();
  473. } catch (error) {
  474. this.topology?.close({ force: true });
  475. throw error;
  476. }
  477. };
  478. if (this.autoEncrypter) {
  479. const initAutoEncrypter = promisify(callback => this.autoEncrypter?.init(callback));
  480. await initAutoEncrypter();
  481. await topologyConnect();
  482. await options.encrypter.connectInternalClient();
  483. } else {
  484. await topologyConnect();
  485. }
  486. return this;
  487. }
  488. /**
  489. * Close the client and its underlying connections
  490. *
  491. * @param force - Force close, emitting no events
  492. */
  493. async close(force = false): Promise<void> {
  494. // There's no way to set hasBeenClosed back to false
  495. Object.defineProperty(this.s, 'hasBeenClosed', {
  496. value: true,
  497. enumerable: true,
  498. configurable: false,
  499. writable: false
  500. });
  501. const activeSessionEnds = Array.from(this.s.activeSessions, session => session.endSession());
  502. this.s.activeSessions.clear();
  503. await Promise.all(activeSessionEnds);
  504. if (this.topology == null) {
  505. return;
  506. }
  507. // If we would attempt to select a server and get nothing back we short circuit
  508. // to avoid the server selection timeout.
  509. const selector = readPreferenceServerSelector(ReadPreference.primaryPreferred);
  510. const topologyDescription = this.topology.description;
  511. const serverDescriptions = Array.from(topologyDescription.servers.values());
  512. const servers = selector(topologyDescription, serverDescriptions);
  513. if (servers.length !== 0) {
  514. const endSessions = Array.from(this.s.sessionPool.sessions, ({ id }) => id);
  515. if (endSessions.length !== 0) {
  516. await this.db('admin')
  517. .command(
  518. { endSessions },
  519. { readPreference: ReadPreference.primaryPreferred, noResponse: true }
  520. )
  521. .catch(() => null); // outcome does not matter
  522. }
  523. }
  524. // clear out references to old topology
  525. const topology = this.topology;
  526. this.topology = undefined;
  527. await new Promise<void>((resolve, reject) => {
  528. topology.close({ force }, error => {
  529. if (error) return reject(error);
  530. const { encrypter } = this[kOptions];
  531. if (encrypter) {
  532. return encrypter.close(this, force, error => {
  533. if (error) return reject(error);
  534. resolve();
  535. });
  536. }
  537. resolve();
  538. });
  539. });
  540. }
  541. /**
  542. * Create a new Db instance sharing the current socket connections.
  543. *
  544. * @param dbName - The name of the database we want to use. If not provided, use database name from connection string.
  545. * @param options - Optional settings for Db construction
  546. */
  547. db(dbName?: string, options?: DbOptions): Db {
  548. options = options ?? {};
  549. // Default to db from connection string if not provided
  550. if (!dbName) {
  551. dbName = this.options.dbName;
  552. }
  553. // Copy the options and add out internal override of the not shared flag
  554. const finalOptions = Object.assign({}, this[kOptions], options);
  555. // Return the db object
  556. const db = new Db(this, dbName, finalOptions);
  557. // Return the database
  558. return db;
  559. }
  560. /**
  561. * Connect to MongoDB using a url
  562. *
  563. * @remarks
  564. * The programmatically provided options take precedence over the URI options.
  565. *
  566. * @see https://www.mongodb.com/docs/manual/reference/connection-string/
  567. */
  568. static async connect(url: string, options?: MongoClientOptions): Promise<MongoClient> {
  569. const client = new this(url, options);
  570. return client.connect();
  571. }
  572. /** Starts a new session on the server */
  573. startSession(options?: ClientSessionOptions): ClientSession {
  574. const session = new ClientSession(
  575. this,
  576. this.s.sessionPool,
  577. { explicit: true, ...options },
  578. this[kOptions]
  579. );
  580. this.s.activeSessions.add(session);
  581. session.once('ended', () => {
  582. this.s.activeSessions.delete(session);
  583. });
  584. return session;
  585. }
  586. /**
  587. * Runs a given operation with an implicitly created session. The lifetime of the session
  588. * will be handled without the need for user interaction.
  589. *
  590. * NOTE: presently the operation MUST return a Promise (either explicit or implicitly as an async function)
  591. *
  592. * @param options - Optional settings for the command
  593. * @param callback - An callback to execute with an implicitly created session
  594. */
  595. async withSession(callback: WithSessionCallback): Promise<void>;
  596. async withSession(options: ClientSessionOptions, callback: WithSessionCallback): Promise<void>;
  597. async withSession(
  598. optionsOrOperation: ClientSessionOptions | WithSessionCallback,
  599. callback?: WithSessionCallback
  600. ): Promise<void> {
  601. const options = {
  602. // Always define an owner
  603. owner: Symbol(),
  604. // If it's an object inherit the options
  605. ...(typeof optionsOrOperation === 'object' ? optionsOrOperation : {})
  606. };
  607. const withSessionCallback =
  608. typeof optionsOrOperation === 'function' ? optionsOrOperation : callback;
  609. if (withSessionCallback == null) {
  610. throw new MongoInvalidArgumentError('Missing required callback parameter');
  611. }
  612. const session = this.startSession(options);
  613. try {
  614. await withSessionCallback(session);
  615. } finally {
  616. try {
  617. await session.endSession();
  618. } catch {
  619. // We are not concerned with errors from endSession()
  620. }
  621. }
  622. }
  623. /**
  624. * Create a new Change Stream, watching for new changes (insertions, updates,
  625. * replacements, deletions, and invalidations) in this cluster. Will ignore all
  626. * changes to system collections, as well as the local, admin, and config databases.
  627. *
  628. * @remarks
  629. * watch() accepts two generic arguments for distinct use cases:
  630. * - The first is to provide the schema that may be defined for all the data within the current cluster
  631. * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument
  632. *
  633. * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
  634. * @param options - Optional settings for the command
  635. * @typeParam TSchema - Type of the data being detected by the change stream
  636. * @typeParam TChange - Type of the whole change stream document emitted
  637. */
  638. watch<
  639. TSchema extends Document = Document,
  640. TChange extends Document = ChangeStreamDocument<TSchema>
  641. >(pipeline: Document[] = [], options: ChangeStreamOptions = {}): ChangeStream<TSchema, TChange> {
  642. // Allow optionally not specifying a pipeline
  643. if (!Array.isArray(pipeline)) {
  644. options = pipeline;
  645. pipeline = [];
  646. }
  647. return new ChangeStream<TSchema, TChange>(this, pipeline, resolveOptions(this, options));
  648. }
  649. }
  650. /**
  651. * Parsed Mongo Client Options.
  652. *
  653. * User supplied options are documented by `MongoClientOptions`.
  654. *
  655. * **NOTE:** The client's options parsing is subject to change to support new features.
  656. * This type is provided to aid with inspection of options after parsing, it should not be relied upon programmatically.
  657. *
  658. * Options are sourced from:
  659. * - connection string
  660. * - options object passed to the MongoClient constructor
  661. * - file system (ex. tls settings)
  662. * - environment variables
  663. * - DNS SRV records and TXT records
  664. *
  665. * Not all options may be present after client construction as some are obtained from asynchronous operations.
  666. *
  667. * @public
  668. */
  669. export interface MongoOptions
  670. extends Required<
  671. Pick<
  672. MongoClientOptions,
  673. | 'autoEncryption'
  674. | 'connectTimeoutMS'
  675. | 'directConnection'
  676. | 'driverInfo'
  677. | 'forceServerObjectId'
  678. | 'minHeartbeatFrequencyMS'
  679. | 'heartbeatFrequencyMS'
  680. | 'keepAlive'
  681. | 'keepAliveInitialDelay'
  682. | 'localThresholdMS'
  683. | 'maxConnecting'
  684. | 'maxIdleTimeMS'
  685. | 'maxPoolSize'
  686. | 'minPoolSize'
  687. | 'monitorCommands'
  688. | 'noDelay'
  689. | 'pkFactory'
  690. | 'raw'
  691. | 'replicaSet'
  692. | 'retryReads'
  693. | 'retryWrites'
  694. | 'serverSelectionTimeoutMS'
  695. | 'socketTimeoutMS'
  696. | 'srvMaxHosts'
  697. | 'srvServiceName'
  698. | 'tlsAllowInvalidCertificates'
  699. | 'tlsAllowInvalidHostnames'
  700. | 'tlsInsecure'
  701. | 'waitQueueTimeoutMS'
  702. | 'zlibCompressionLevel'
  703. >
  704. >,
  705. SupportedNodeConnectionOptions {
  706. appName?: string;
  707. hosts: HostAddress[];
  708. srvHost?: string;
  709. credentials?: MongoCredentials;
  710. readPreference: ReadPreference;
  711. readConcern: ReadConcern;
  712. loadBalanced: boolean;
  713. serverApi: ServerApi;
  714. compressors: CompressorName[];
  715. writeConcern: WriteConcern;
  716. dbName: string;
  717. metadata: ClientMetadata;
  718. /**
  719. * @deprecated This option will be removed in the next major version.
  720. */
  721. autoEncrypter?: AutoEncrypter;
  722. proxyHost?: string;
  723. proxyPort?: number;
  724. proxyUsername?: string;
  725. proxyPassword?: string;
  726. /** @internal */
  727. connectionType?: typeof Connection;
  728. /** @internal */
  729. encrypter: Encrypter;
  730. /** @internal */
  731. userSpecifiedAuthSource: boolean;
  732. /** @internal */
  733. userSpecifiedReplicaSet: boolean;
  734. /**
  735. * # NOTE ABOUT TLS Options
  736. *
  737. * If `tls` is provided as an option, it is equivalent to setting the `ssl` option.
  738. *
  739. * NodeJS native TLS options are passed through to the socket and retain their original types.
  740. *
  741. * ### Additional options:
  742. *
  743. * | nodejs native option | driver spec compliant option name | legacy option name | driver option type |
  744. * |:----------------------|:----------------------------------------------|:-------------------|:-------------------|
  745. * | `ca` | `tlsCAFile` | `sslCA` | `string` |
  746. * | `crl` | `tlsCRLFile` (next major version) | `sslCRL` | `string` |
  747. * | `cert` | `tlsCertificateFile`, `tlsCertificateKeyFile` | `sslCert` | `string` |
  748. * | `key` | `tlsCertificateKeyFile` | `sslKey` | `string` |
  749. * | `passphrase` | `tlsCertificateKeyFilePassword` | `sslPass` | `string` |
  750. * | `rejectUnauthorized` | `tlsAllowInvalidCertificates` | `sslValidate` | `boolean` |
  751. * | `checkServerIdentity` | `tlsAllowInvalidHostnames` | N/A | `boolean` |
  752. * | see note below | `tlsInsecure` | N/A | `boolean` |
  753. *
  754. * If `tlsInsecure` is set to `true`, then it will set the node native options `checkServerIdentity`
  755. * to a no-op and `rejectUnauthorized` to `false`.
  756. *
  757. * If `tlsInsecure` is set to `false`, then it will set the node native options `checkServerIdentity`
  758. * to a no-op and `rejectUnauthorized` to the inverse value of `tlsAllowInvalidCertificates`. If
  759. * `tlsAllowInvalidCertificates` is not set, then `rejectUnauthorized` will be set to `true`.
  760. */
  761. tls: boolean;
  762. /** @internal */
  763. [featureFlag: symbol]: any;
  764. /** @internal */
  765. mongoLoggerOptions: MongoLoggerOptions;
  766. }