Skip to content

Commit 01e45f5

Browse files
nbbeekendariakpbaileympearson
authored
docs(NODE-6935): clarify the steps and responsibilities of MongoClient close (#4532)
Co-authored-by: Daria Pardue <[email protected]> Co-authored-by: Bailey Pearson <[email protected]>
1 parent 6a35701 commit 01e45f5

File tree

1 file changed

+60
-17
lines changed

1 file changed

+60
-17
lines changed

src/mongo_client.ts

+60-17
Original file line numberDiff line numberDiff line change
@@ -347,22 +347,35 @@ export type MongoClientEvents = Pick<TopologyEvents, (typeof MONGO_CLIENT_EVENTS
347347
};
348348

349349
/**
350-
* The **MongoClient** class is a class that allows for making Connections to MongoDB.
351350
* @public
352351
*
352+
* The **MongoClient** class is a class that allows for making Connections to MongoDB.
353+
*
354+
* **NOTE:** The programmatically provided options take precedence over the URI options.
355+
*
353356
* @remarks
354-
* The programmatically provided options take precedence over the URI options.
357+
*
358+
* A MongoClient is the entry point to connecting to a MongoDB server.
359+
*
360+
* It handles a multitude of features on your application's behalf:
361+
* - **Server Host Connection Configuration**: A MongoClient is responsible for reading TLS cert, ca, and crl files if provided.
362+
* - **SRV Record Polling**: A "`mongodb+srv`" style connection string is used to have the MongoClient resolve DNS SRV records of all server hostnames which the driver periodically monitors for changes and adjusts its current view of hosts correspondingly.
363+
* - **Server Monitoring**: The MongoClient automatically keeps monitoring the health of server nodes in your cluster to reach out to the correct and lowest latency one available.
364+
* - **Connection Pooling**: To avoid paying the cost of rebuilding a connection to the server on every operation the MongoClient keeps idle connections preserved for reuse.
365+
* - **Session Pooling**: The MongoClient creates logical sessions that enable retryable writes, causal consistency, and transactions. It handles pooling these sessions for reuse in subsequent operations.
366+
* - **Cursor Operations**: A MongoClient's cursors use the health monitoring system to send the request for more documents to the same server the query began on.
367+
* - **Mongocryptd process**: When using auto encryption, a MongoClient will launch a `mongocryptd` instance for handling encryption if the mongocrypt shared library isn't in use.
368+
*
369+
* There are many more features of a MongoClient that are not listed above.
370+
*
371+
* In order to enable these features, a number of asynchronous Node.js resources are established by the driver: Timers, FS Requests, Sockets, etc.
372+
* For details on cleanup, please refer to the MongoClient `close()` documentation.
355373
*
356374
* @example
357375
* ```ts
358376
* import { MongoClient } from 'mongodb';
359-
*
360377
* // Enable command monitoring for debugging
361-
* const client = new MongoClient('mongodb://localhost:27017', { monitorCommands: true });
362-
*
363-
* client.on('commandStarted', started => console.log(started));
364-
* client.db().collection('pets');
365-
* await client.insertOne({ name: 'spot', kind: 'dog' });
378+
* const client = new MongoClient('mongodb://localhost:27017?appName=mflix', { monitorCommands: true });
366379
* ```
367380
*/
368381
export class MongoClient extends TypedEventEmitter<MongoClientEvents> implements AsyncDisposable {
@@ -641,17 +654,47 @@ export class MongoClient extends TypedEventEmitter<MongoClientEvents> implements
641654
}
642655

643656
/**
644-
* Cleans up client-side resources used by the MongoClient.
657+
* Cleans up resources managed by the MongoClient.
658+
*
659+
* The close method clears and closes all resources whose lifetimes are managed by the MongoClient.
660+
* Please refer to the `MongoClient` class documentation for a high level overview of the client's key features and responsibilities.
661+
*
662+
* **However,** the close method does not handle the cleanup of resources explicitly created by the user.
663+
* Any user-created driver resource with its own `close()` method should be explicitly closed by the user before calling MongoClient.close().
664+
* This method is written as a "best effort" attempt to leave behind the least amount of resources server-side when possible.
665+
*
666+
* The following list defines ideal preconditions and consequent pitfalls if they are not met.
667+
* The MongoClient, ClientSession, Cursors and ChangeStreams all support [explicit resource management](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html).
668+
* By using explicit resource management to manage the lifetime of driver resources instead of manually managing their lifetimes, the pitfalls outlined below can be avoided.
669+
*
670+
* The close method performs the following in the order listed:
671+
* - Client-side:
672+
* - **Close in-use connections**: Any connections that are currently waiting on a response from the server will be closed.
673+
* This is performed _first_ to avoid reaching the next step (server-side clean up) and having no available connections to check out.
674+
* - _Ideal_: All operations have been awaited or cancelled, and the outcomes, regardless of success or failure, have been processed before closing the client servicing the operation.
675+
* - _Pitfall_: When `client.close()` is called and all connections are in use, after closing them, the client must create new connections for cleanup operations, which comes at the cost of new TLS/TCP handshakes and authentication steps.
676+
* - Server-side:
677+
* - **Close active cursors**: All cursors that haven't been completed will have a `killCursor` operation sent to the server they were initialized on, freeing the server-side resource.
678+
* - _Ideal_: Cursors are explicitly closed or completed before `client.close()` is called.
679+
* - _Pitfall_: `killCursors` may have to build a new connection if the in-use closure ended all pooled connections.
680+
* - **End active sessions**: In-use sessions created with `client.startSession()` or `client.withSession()` or implicitly by the driver will have their `.endSession()` method called.
681+
* Contrary to the name of the method, `endSession()` returns the session to the client's pool of sessions rather than end them on the server.
682+
* - _Ideal_: Transaction outcomes are awaited and their corresponding explicit sessions are ended before `client.close()` is called.
683+
* - _Pitfall_: **This step aborts in-progress transactions**. It is advisable to observe the outcome of a transaction before closing your client.
684+
* - **End all pooled sessions**: The `endSessions` command with all session IDs the client has pooled is sent to the server to inform the cluster it can clean them up.
685+
* - _Ideal_: No user intervention is expected.
686+
* - _Pitfall_: None.
687+
*
688+
* The remaining shutdown is of the MongoClient resources that are intended to be entirely internal but is documented here as their existence relates to the JS event loop.
645689
*
646-
* This includes:
690+
* - Client-side (again):
691+
* - **Stop all server monitoring**: Connections kept live for detecting cluster changes and roundtrip time measurements are shutdown.
692+
* - **Close all pooled connections**: Each server node in the cluster has a corresponding connection pool and all connections in the pool are closed. Any operations waiting to check out a connection will have an error thrown instead of a connection returned.
693+
* - **Clear out server selection queue**: Any operations that are in the process of waiting for a server to be selected will have an error thrown instead of a server returned.
694+
* - **Close encryption-related resources**: An internal MongoClient created for communicating with `mongocryptd` or other encryption purposes is closed. (Using this same method of course!)
647695
*
648-
* - Closes in-use connections.
649-
* - Closes all active cursors.
650-
* - Ends all in-use sessions with {@link ClientSession#endSession|ClientSession.endSession()}.
651-
* - aborts in progress transactions if is one related to the session.
652-
* - Ends all unused sessions server-side.
653-
* - Closes all remaining idle connections.
654-
* - Cleans up any resources being used for auto encryption if auto encryption is enabled.
696+
* After the close method completes there should be no MongoClient related resources [ref-ed in Node.js' event loop](https://docs.libuv.org/en/v1.x/handle.html#reference-counting).
697+
* This should allow Node.js to exit gracefully if MongoClient resources were the only active handles in the event loop.
655698
*
656699
* @param _force - currently an unused flag that has no effect. Defaults to `false`.
657700
*/

0 commit comments

Comments
 (0)