Skip to content

Commit bac1552

Browse files
authored
DOCSP-49971: csot cc (#526)
1 parent 940d4e1 commit bac1552

File tree

3 files changed

+294
-81
lines changed

3 files changed

+294
-81
lines changed
Lines changed: 232 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,237 @@
1+
.. _golang-timeout-setting:
2+
.. _golang-csot:
13

24
===========================
35
Limit Server Execution Time
46
===========================
57

6-
.. TODO
8+
.. contents:: On this page
9+
:local:
10+
:backlinks: none
11+
:depth: 2
12+
:class: singlecol
13+
14+
.. facet::
15+
:name: genre
16+
:values: reference
17+
18+
.. meta::
19+
:keywords: error, blocking, thread, task, code example
20+
21+
Overview
22+
--------
23+
24+
In this guide, you can learn about the single timeout setting in the
25+
{+driver-short+}, also known as the **client-side operation timeout (CSOT)**.
26+
27+
When you use the {+driver-short+} to perform a server operation, you can also
28+
limit the amount of time in which the server can finish the operation.
29+
The timeout applies to all steps needed to complete the operation,
30+
including server selection, connection checkout, and server-side
31+
execution. When the timeout expires, the {+driver-short+} raises a
32+
timeout exception.
33+
34+
.. note:: Experimental Feature
35+
36+
The CSOT feature is experimental and might change in future driver
37+
releases.
38+
39+
timeoutMS Option
40+
----------------
41+
42+
To specify a timeout when connecting to a MongoDB deployment, set the
43+
``timeoutMS`` connection option to the timeout length in milliseconds. You can
44+
set the ``timeoutMS`` option in the following ways:
45+
46+
- Calling the ``SetTimeout()`` method when
47+
specifying options for your ``Client`` instance
48+
- Setting the ``timeoutMS`` parameter in your connection string
49+
50+
The following code examples set a client-level timeout of ``200`` milliseconds.
51+
Select the :guilabel:`Client` or :guilabel:`Connection
52+
String` tab to see the corresponding code.
53+
54+
.. tabs::
55+
56+
.. tab:: MongoClientSettings
57+
:tabid: mongoclientsettings
58+
59+
.. literalinclude:: /includes/connect/csot.go
60+
:language: go
61+
:start-after: start-client-opts
62+
:end-before: end-client-opts
63+
:dedent:
64+
65+
.. tab:: Connection String
66+
:tabid: connection-string
67+
68+
.. code-block:: go
69+
:copyable: true
70+
71+
uri := "<connection string>/?timeoutMS=200"
72+
client, err := mongo.Connect(options.Client().ApplyURI(uri))
73+
74+
.. note:: Retries Under Timeout Specification
75+
76+
If you set a timeout on your ``Client`` or in an operation-level
77+
Context and the server returns a retryable error, the driver retries the
78+
operation as many times as possible before the timeout expires.
79+
80+
Once the timeout expires, the driver returns a timeout error.
81+
See the Server manual for more information about :ref:`retryable
82+
reads <retryable-reads>` and :manual:`retryable writes
83+
</core/retryable-writes/>`.
84+
85+
Accepted Timeout Values
86+
~~~~~~~~~~~~~~~~~~~~~~~
87+
88+
The following table describes the timeout behavior corresponding to the
89+
accepted values for ``timeoutMS``:
90+
91+
.. list-table::
92+
:header-rows: 1
93+
:widths: 25 75
94+
95+
* - Value
96+
- Behavior
97+
98+
* - Positive integer
99+
- Sets the timeout to use for operation completion.
100+
101+
* - ``0``
102+
- Specifies that operations never time out.
103+
104+
* - ``null`` or unset
105+
- | Defers the timeout behavior to the following settings:
106+
107+
- :manual:`waitQueueTimeoutMS </reference/connection-string-options/#mongodb-urioption-urioption.waitQueueTimeoutMS>`
108+
- :manual:`socketTimeoutMS </reference/connection-string-options/#mongodb-urioption-urioption.socketTimeoutMS>`
109+
- :manual:`wTimeoutMS </reference/connection-string-options/#mongodb-urioption-urioption.wtimeoutMS>`
110+
- :manual:`maxTimeMS </reference/method/cursor.maxTimeMS/>`
111+
112+
| These settings are deprecated and are ignored if you set ``timeoutMS``.
113+
114+
If you specify the ``timeoutMS`` option, the driver automatically applies the
115+
specified timeout to each server operation.
116+
117+
Timeout Inheritance
118+
~~~~~~~~~~~~~~~~~~~
119+
120+
By default, all operations in your application inherit the
121+
``Timeout`` option from ``Client`` if you do not set a different timeout
122+
on specific operations in the operation's Context.
123+
124+
If you set a timeout on a Context passed into an operation, the driver uses
125+
that value for the operation. If you do not specify a Context timeout,
126+
the operation Context derives the timeout from the ``Client`` instance.
127+
128+
The following table describes how the timeout value is inherited at each level:
129+
130+
.. list-table::
131+
:header-rows: 1
132+
:widths: 30 70
133+
134+
* - Level
135+
- Inheritance Description
136+
137+
* - Operation
138+
- Takes the highest precedence and overrides the timeout
139+
options that you set at any other level.
140+
141+
* - Transaction
142+
- Takes precedence over the timeout value that you set at the
143+
client level.
144+
145+
* - Client
146+
- Applies to all databases, collections, sessions, transactions, and
147+
operations within that client that do not otherwise specify a
148+
Context timeout.
149+
150+
For more information on overrides and specific options, see the following
151+
:ref:`golang-csot-overrides` section.
152+
153+
.. _golang-csot-overrides:
154+
155+
Overrides
156+
---------
157+
158+
The {+driver-short+} supports various levels of configuration to control the
159+
behavior and performance of database operations.
160+
161+
You can specify a ``timeoutMS`` option at a more specific level to override the
162+
client-level configuration. The table in the preceding section describes
163+
the levels at which you can specify a timeout setting. This allows you
164+
to customize timeouts based on the needs of individual operations.
165+
166+
The following example shows how to set an operation-level timeout in a
167+
Context, which takes priority over the client-level timeout:
168+
169+
.. literalinclude:: /includes/connect/csot.go
170+
:language: go
171+
:start-after: start-override
172+
:end-before: end-override
173+
:dedent:
174+
:emphasize-lines: 9, 12
175+
176+
.. _go-csot-transaction:
177+
178+
Transactions
179+
~~~~~~~~~~~~
180+
181+
When you perform a transaction by using the `WithTransaction()
182+
<{+api+}/mongo#Session.WithTransaction>`__ method, you can apply a
183+
timeout to the transaction operations by setting a timeout within the
184+
Context.
185+
186+
The following code demonstrates how to set a Context timeout when
187+
calling the ``WithTransaction()`` method to perform a transaction:
188+
189+
.. literalinclude:: /includes/connect/csot.go
190+
:language: go
191+
:start-after: start-txn-context
192+
:end-before: end-txn-context
193+
:dedent:
194+
:emphasize-lines: 1, 4
195+
196+
If you do not specify a Context timeout, the driver inherits the timeout
197+
value set on the parent ``Client``.
198+
199+
You can also pass Context timeouts to the following session
200+
methods:
201+
202+
- ``AbortTransaction()``
203+
- ``CommitTransaction()``
204+
- ``EndSession()``
205+
206+
To learn more about transactions, see the :ref:`golang-transactions`
207+
guide.
208+
209+
.. _go-csot-cursor:
210+
211+
Cursors
212+
-------
213+
214+
Cursors offer configurable timeout settings when using the CSOT feature. You can
215+
adjust cursor timeouts by passing Contexts that have timeout
216+
specifications to `Cursor <{+api+}/mongo#Cursor>`__ methods.
217+
218+
For operations that create cursors, the timeout setting can either limit
219+
the lifetime of the cursor or be applied separately to the original
220+
operation and all subsequent calls.
221+
222+
For example, if you pass a Context timeout to the ``Cursor.Next()``
223+
method, the timeout applies to each action to fetch a result document.
224+
If you pass a Context timeout to the ``Cursor.All()`` method, the
225+
timeout applies to the entire lifetime of the cursor.
226+
227+
To learn more about cursors, see the :ref:`golang-cursor` guide.
228+
229+
API Documentation
230+
-----------------
231+
232+
To learn more about using timeouts with the {+driver-short+}, see the following
233+
API documentation:
234+
235+
- `ClientOptions <{+api+}/mongo/options#ClientOptions>`__
236+
- `SetTimeout() <{+api+}/mongo/options#ClientOptions.SetTimeout>`__
237+
- `Context.WithTimeout() <https://pkg.go.dev/context#WithTimeout>`__

source/connect/specify-connection-options.txt

Lines changed: 3 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,9 @@ default value, and a description of the option.
5656
- ``null``
5757
- Specifies the number of milliseconds that a single operation run on the
5858
``Client`` can take before returning a timeout error. Operations honor
59-
this setting only if there is no deadline on the operation Context.
59+
this setting only if there is no deadline on the operation
60+
Context. To learn more about this option, see the :ref:`CSOT
61+
<golang-csot>` guide.
6062

6163
* - **connectTimeoutMS**
6264
- integer
@@ -127,82 +129,3 @@ default value, and a description of the option.
127129
For a full list of connection options, see the `ClientOptions API
128130
documentation
129131
<{+api+}/mongo/options#ClientOptions>`__.
130-
131-
.. _golang-timeout-setting:
132-
133-
Single Timeout Setting
134-
----------------------
135-
136-
You can set a single ``Timeout`` option on your ``Client`` instance to
137-
specify the maximum amount of time that a single operation can take to
138-
execute.
139-
140-
Set a client-level timeout by calling the ``SetTimeout()`` method when
141-
specifying options for your ``Client`` instance or by specifying the
142-
``timeoutMS`` option in your connection URI. By default, all
143-
``Database``, ``Collection``, ``Session``, ``ChangeStream``, and
144-
``Bucket`` instances elsewhere in your application inherit the
145-
``Timeout`` option from ``Client`` if you do not set a different timeout
146-
on specific operations in the operation's Context.
147-
148-
If you set a timeout on a Context passed into an operation, the driver uses
149-
that value for the operation. If you do not specify a Context timeout,
150-
the operation Context derives the timeout from the ``Client`` instance.
151-
152-
.. note:: Retries under Timeout Specification
153-
154-
If you set a timeout on your ``Client`` or in an operation-level
155-
Context and the server returns a retryable error, the driver retries the
156-
operation as many times as possible before the timeout expires.
157-
158-
Once the timeout expires, the driver returns a timeout error.
159-
See the Server manual for more information about :ref:`retryable
160-
reads <retryable-reads>` and :manual:`retryable writes
161-
</core/retryable-writes/>`.
162-
163-
Timeout Examples
164-
~~~~~~~~~~~~~~~~
165-
166-
This section provides examples that demonstrate different ways to set a
167-
timeout in your application.
168-
169-
Client Option
170-
^^^^^^^^^^^^^
171-
172-
The following code shows how to set the ``Timeout`` option on a ``Client``
173-
by using the ``SetTimeout()`` method:
174-
175-
.. code-block:: go
176-
177-
opts := options.Client().SetTimeout(5 * time.Second)
178-
client, err := mongo.Connect(opts)
179-
180-
Connection String Option
181-
^^^^^^^^^^^^^^^^^^^^^^^^
182-
183-
The following example shows how to set a single timeout by using the
184-
``timeoutMS`` URI option. Then, the code executes an insert operation
185-
that inherits the timeout:
186-
187-
.. code-block:: go
188-
:emphasize-lines: 1, 5
189-
190-
uri := "mongodb://user:[email protected]:27017/?timeoutMS=5000"
191-
client, err := mongo.Connect(options.Client().ApplyURI(uri))
192-
193-
...
194-
coll.InsertOne(context.Background(), doc)
195-
196-
Operation Timeout
197-
^^^^^^^^^^^^^^^^^
198-
199-
The following example shows how to set an operation-level timeout in a
200-
Context, which takes priority over a client-level timeout you might have
201-
set:
202-
203-
.. code-block:: go
204-
205-
ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
206-
defer cancel()
207-
208-
res, err := coll.InsertOne(ctx, bson.D{{"x", 2}})

source/includes/connect/csot.go

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"log"
6+
"time"
7+
8+
"go.mongodb.org/mongo-driver/v2/bson"
9+
"go.mongodb.org/mongo-driver/v2/mongo"
10+
"go.mongodb.org/mongo-driver/v2/mongo/options"
11+
)
12+
13+
func main() {
14+
15+
// start-client-opts
16+
opts := options.Client().SetTimeout(200 * time.Millisecond)
17+
client, err := mongo.Connect(opts)
18+
// end-client-opts
19+
20+
if err != nil {
21+
log.Fatal(err)
22+
}
23+
24+
// start-override
25+
opts = options.Client().SetTimeout(200 * time.Millisecond)
26+
client, err = mongo.Connect(opts)
27+
if err != nil {
28+
log.Fatal(err)
29+
}
30+
31+
coll := client.Database("db").Collection("people")
32+
33+
ctx, cancel := context.WithTimeout(context.TODO(), 300*time.Millisecond)
34+
defer cancel()
35+
36+
_, err = coll.InsertOne(ctx, bson.D{{"name", "Agnes Georgiou"}})
37+
// end-override
38+
39+
session, err := client.StartSession()
40+
if err != nil {
41+
log.Fatal(err)
42+
}
43+
defer session.EndSession(context.TODO())
44+
45+
// start-txn-context
46+
txnContext, cancel := context.WithTimeout(context.TODO(), 300*time.Millisecond)
47+
defer cancel()
48+
49+
result, err := session.WithTransaction(txnContext, func(ctx context.Context) (string, error) {
50+
// Perform transaction operations
51+
})
52+
// end-txn-context
53+
54+
defer func() {
55+
if err = client.Disconnect(context.TODO()); err != nil {
56+
log.Fatal(err)
57+
}
58+
}()
59+
}

0 commit comments

Comments
 (0)