Skip to content

Commit a2ff558

Browse files
authoredJan 15, 2025
DOCSP-44666 Add CSOT (#951)
1 parent 83d5fb1 commit a2ff558

File tree

5 files changed

+301
-0
lines changed

5 files changed

+301
-0
lines changed
 

‎.github/workflows/vale-tdbx.yml

+3
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ jobs:
1111
steps:
1212
- name: checkout
1313
uses: actions/checkout@master
14+
15+
- name: Install docutils
16+
run: sudo apt-get install -y docutils
1417

1518
- name: Install docutils
1619
run: sudo apt-get install -y docutils
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { MongoClient } from "mongodb";
2+
3+
// start-operation
4+
const uri = "<connection string uri>";
5+
const client = new MongoClient(uri, {
6+
timeoutMS: 10000
7+
});
8+
9+
async function run() {
10+
try {
11+
const db = client.db("test-db");
12+
const coll = db.collection("test-collection");
13+
14+
const result = await coll.insertOne({ name: "Yngwie" });
15+
console.log("Insert result:", result);
16+
} finally {
17+
await client.close();
18+
}
19+
}
20+
21+
run().catch(console.dir);
22+
// end-operation
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { MongoClient } from "mongodb";
2+
3+
//start-csot
4+
// Creates a new MongoClient with a client-level timeoutMS configuration
5+
const uri = "<connection string uri>";
6+
const client = new MongoClient(uri, {
7+
// Client-level timeout: 15 seconds
8+
timeoutMS: 15000
9+
});
10+
11+
async function run() {
12+
try {
13+
const db = client.db("test-db");
14+
const coll = db.collection("test-collection");
15+
16+
// Performs a query operation with an operation-level timeoutMS configuration
17+
const docs = await coll.find({},
18+
// Operation-level timeout: 10 seconds
19+
{ timeoutMS: 10000 })
20+
.toArray();
21+
22+
console.log(docs);
23+
} finally {
24+
await client.close();
25+
}
26+
}
27+
28+
run().catch(console.dir);
29+
//end-csot

‎source/fundamentals/connection.txt

+2
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Connection
2121
Network Compression </fundamentals/connection/network-compression>
2222
TLS </fundamentals/connection/tls>
2323
SOCKS5 Proxy Support </fundamentals/connection/socks>
24+
Limit Server Execution Time </fundamentals/connection/csot>
2425
Connect with AWS Lambda <https://www.mongodb.com/docs/atlas/manage-connections-aws-lambda/>
2526

2627
.. contents:: On this page
@@ -41,6 +42,7 @@ learn:
4142
- :ref:`How to Enable Network Compression <node-network-compression>`
4243
- :ref:`How to Enable TLS on a Connection <node-connect-tls>`
4344
- :ref:`How to Enable SOCKS5 Proxy Support <node-connect-socks>`
45+
- :ref:`How to Limit Server Execution Time <node-csot>`
4446
- :atlas:`How to Connect to MongoDB Atlas from AWS Lambda </manage-connections-aws-lambda/>`
4547

4648
Compatibility
+245
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,245 @@
1+
.. _node-csot:
2+
3+
Limit Server Execution Time
4+
===========================
5+
6+
.. contents:: On this page
7+
:local:
8+
:backlinks: none
9+
:depth: 2
10+
:class: singlecol
11+
12+
.. facet::
13+
:name: genre
14+
:values: reference
15+
16+
.. meta::
17+
:keywords: error, blocking, thread, task
18+
19+
Overview
20+
--------
21+
22+
When you use the {+driver-short+} to perform a server operation, you can also
23+
limit the duration allowed for the server to finish the operation. To do so,
24+
specify a **client-side operation timeout (CSOT)**. The timeout applies to all
25+
steps needed to complete the operation, including server selection, connection
26+
checkout, and server-side execution. When the timeout expires, the
27+
{+driver-short+} raises a timeout exception.
28+
29+
.. note:: Experimental Feature
30+
31+
The CSOT feature is experimental and might change in future driver releases.
32+
33+
timeoutMS Option
34+
----------------
35+
36+
To specify a timeout when connecting to a MongoDB deployment, set the
37+
``timeoutMS`` connection option to the timeout length in milliseconds. You can
38+
do this in two ways: by passing an argument to the ``MongoClient`` constructor
39+
or through a parameter in your connection string.
40+
41+
The following code examples use the ``timeoutMS`` option to specify a timeout of
42+
30 seconds:
43+
44+
.. tabs::
45+
46+
.. tab:: MongoClient
47+
:tabid: mongoclient
48+
49+
.. code-block:: javascript
50+
:emphasize-lines: 2
51+
52+
const uri = "mongodb://<hostname:<port>";
53+
const client = new MongoClient(uri, { timeoutMS: 30000 });
54+
55+
.. tab:: Connection String
56+
:tabid: connection-string
57+
58+
.. code-block:: javascript
59+
:emphasize-lines: 1
60+
61+
const uri = "mongodb://<hostname:<port>?timeoutMS=30000";
62+
const client = new MongoClient(uri);
63+
64+
.. note::
65+
66+
The ``timeoutMS`` connection option takes precedence over the
67+
following options:
68+
69+
- ``socketTimeoutMS``
70+
- ``waitQueueTimeoutMS``
71+
- ``wTimeoutMS``
72+
- ``maxTimeMS``
73+
- ``maxCommitTimeMS``
74+
75+
When the CSOT feature is no longer experimental, the preceding options will
76+
be deprecated.
77+
78+
If you specify the ``timeoutMS`` option, the driver automatically applies the
79+
specified timeout per each server operation. The following code example specifies
80+
a timeout of 10 seconds at the client level, and then calls the ``insertOne()``
81+
method:
82+
83+
.. literalinclude:: /code-snippets/connection/csot-operation.js
84+
:language: javascript
85+
:start-after: start-operation
86+
:end-before: end-operation
87+
88+
Timeout Inheritance
89+
~~~~~~~~~~~~~~~~~~~
90+
91+
When you specify a ``timeoutMS`` option, the driver applies the timeout
92+
according to the same inheritance behaviors as the other {+driver-short+} options.
93+
The following table describes how the timeout value is inherited at each level:
94+
95+
.. list-table::
96+
:header-rows: 1
97+
:widths: 30 70
98+
99+
* - Level
100+
- Inheritance Description
101+
102+
* - Operation
103+
- Takes the highest precedence and will override ``timeoutMS``
104+
options set at any other level.
105+
106+
* - Transaction
107+
- Takes precedence over ``timeoutMS`` set at the session,
108+
collection, database, or client level.
109+
110+
* - Session
111+
- Applies to all transactions and operations within
112+
that session, unless the option is overridden by options set at those levels.
113+
114+
* - Database
115+
- Applies to all sessions and operations within that
116+
database, unless the option is overridden by options set at those levels.
117+
118+
* - Collection
119+
- Applies to all sessions and operations on that
120+
collection, unless the option is overridden by options set at those levels.
121+
122+
* - Client
123+
- Applies to all databases, collections, sessions, transactions, and
124+
operations within that client that do not otherwise specify
125+
``timeoutMS``.
126+
127+
For more information on overrides and specific options, see the :ref:`Overrides
128+
<node-csot-overrides>` section.
129+
130+
.. _node-csot-overrides:
131+
132+
Overrides
133+
---------
134+
135+
The {+driver-short+} supports various levels of configuration to control the
136+
behavior and performance of database operations.
137+
138+
You can specify a ``timeoutMS`` option at the operation level to override the
139+
client-level configuration for a specific operation. This allows you to
140+
customize timeouts based on the needs of individual queries.
141+
142+
The following example demonstrates how an operation-level ``timeoutMS``
143+
configuration can override a client-level ``timeoutMS`` configuration:
144+
145+
.. literalinclude:: /code-snippets/connection/csot.js
146+
:language: javascript
147+
:start-after: start-csot
148+
:end-before: end-csot
149+
150+
Transactions
151+
~~~~~~~~~~~~
152+
153+
When you create a new ``ClientSession`` instance to implement a transaction, use
154+
the ``defaultTimeoutMS`` option. You can set ``defaultTimeoutMS`` to specify the
155+
``timeoutMS`` values to use for:
156+
157+
- `commitTransaction()
158+
<{+api+}/classes/ClientSession.html#commitTransaction>`__
159+
- `abortTransaction()
160+
<{+api+}/classes/ClientSession.html#abortTransaction>`__
161+
- `withTransaction() <{+api+}/classes/ClientSession.html#withTransaction>`__
162+
- `endSession()
163+
<{+api+}/classes/ClientSession.html#endSession>`__
164+
165+
If you do not specify ``defaultTimeoutMS``, the driver uses the ``timeoutMS``
166+
value set on the parent ``MongoClient``.
167+
168+
You cannot override ``defaultTimeoutMS`` by setting the ``timeoutMS`` option on an
169+
operation in a transaction session provided by the ``withTransaction()`` callback.
170+
Doing so throws an error.
171+
172+
Client Encryption
173+
~~~~~~~~~~~~~~~~~
174+
175+
When you use Client-Side Field Level Encryption (CSFLE), the driver uses the
176+
``timeoutMS`` option to limit the time allowed for encryption and decryption
177+
operations.
178+
179+
If you specify the ``timeoutMS`` option when you construct a
180+
``ClientEncryption`` instance, it controls the lifetime of all operations
181+
performed on that instance. If you do not provide ``timeoutMS``, the instance
182+
inherits the ``timeoutMS`` setting from the ``MongoClient`` used in the
183+
``ClientEncryption`` constructor.
184+
185+
If you set ``timeoutMS`` on both the client and directly in
186+
``ClientEncryption``, the value provided to ``ClientEncryption`` takes
187+
precedence.
188+
189+
Cursors
190+
-------
191+
192+
Cursors offer configurable timeout settings when using the CSOT feature. You can
193+
adjust cursor handling by configuring either the cursor lifetime or cursor
194+
iteration mode if needed. To configure the mode, set the ``timeoutMode`` option
195+
to ``cursorLifetime``, which is the default, or ``iteration``.
196+
197+
Cursor Lifetime Mode
198+
~~~~~~~~~~~~~~~~~~~~
199+
200+
The cursor lifetime mode uses ``timeoutMS`` to limit the entire lifetime of a
201+
cursor. In this mode, the initialization of the cursor and all subsequent calls
202+
to the cursor methods must complete within the limit specified by the
203+
``timeoutMS`` option. All documents must be returned within this limit.
204+
Otherwise, the cursor's lifetime expires and a timeout error occurs.
205+
206+
When you close a cursor by calling the ``toArray()`` or ``close()`` method, the
207+
timeout resets for the ``killCursors`` command to ensure server-side resources are
208+
cleaned up.
209+
210+
The following example shows how to set the ``timeoutMS`` option to ensure that
211+
the cursor is initialized and all documents are retrieved within 10 seconds:
212+
213+
.. code-block:: javascript
214+
215+
const docs = await collection.find({}, {timeoutMS: 10000}).toArray();
216+
217+
Cursor Iteration Mode
218+
~~~~~~~~~~~~~~~~~~~~~
219+
220+
The cursor iteration mode uses the ``timeoutMS`` option to limit each call to
221+
the ``next()``, ``hasNext()``, or ``tryNext()`` method. The timeout refreshes
222+
after each call completes. This is the default mode for all tailable cursors,
223+
such as the tailable cursors returned by the ``find()`` method on capped
224+
collections or change streams.
225+
226+
The following code example iterates over documents in the ``mflix`` collection
227+
using a cursor with the ``timeoutMode`` set to ``iteration``, and then fetches
228+
and logs the ``imdb_url`` for each movie document:
229+
230+
.. code-block:: javascript
231+
232+
for await (const movie of mflix.find({}, { timeoutMode: 'iteration' })) {
233+
const imdbResponse = await fetch(movie.imdb_url);
234+
console.log(await imdbResponse.text());
235+
}
236+
237+
API Documentation
238+
-----------------
239+
240+
To learn more about using timeouts with the {+driver-short+}, see the following
241+
API documentation:
242+
243+
- `MongoClient <{+api+}/classes/MongoClient.html>`__
244+
- `timeoutMS <{+api+}/classes/MongoClient.html#timeoutMS>`__
245+
- `ClientSession <{+api+}/classes/ClientSession.html>`__

0 commit comments

Comments
 (0)
Please sign in to comment.