|
| 1 | +.. _golang-context: |
| 2 | + |
| 3 | +=============== |
| 4 | +Context Package |
| 5 | +=============== |
| 6 | + |
| 7 | +.. facet:: |
| 8 | + :name: genre |
| 9 | + :values: reference |
| 10 | + |
| 11 | +.. meta:: |
| 12 | + :keywords: code example, unblock |
| 13 | + :description: Learn how to use the context package in Go to manage timeouts and cancellations for blocking method calls in the MongoDB Go driver. |
| 14 | + |
| 15 | +.. contents:: On this page |
| 16 | + :local: |
| 17 | + :backlinks: none |
| 18 | + :depth: 2 |
| 19 | + :class: singlecol |
| 20 | + |
| 21 | +Overview |
| 22 | +-------- |
| 23 | + |
| 24 | +The {+driver-short+} uses the `context package |
| 25 | +<https://pkg.go.dev/context>`__ from the Go standard library to allow |
| 26 | +applications to signal timeouts and cancellations for any **blocking method** |
| 27 | +call. A blocking method relies on an external event, such as a network |
| 28 | +input or output, to proceed with its task. |
| 29 | + |
| 30 | +An example of a blocking method is the ``InsertOne()`` |
| 31 | +method. If you want to perform an insert operation on a ``Collection`` |
| 32 | +within 10 seconds, you can use a Context with a timeout. If the |
| 33 | +operation doesn't complete within the timeout, the method returns |
| 34 | +an error. |
| 35 | + |
| 36 | +.. code-block:: go |
| 37 | + |
| 38 | + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 39 | + defer cancel() |
| 40 | + |
| 41 | + client.Database("db").Collection("items").InsertOne(ctx, bson.D{{"x",1}}) |
| 42 | + |
| 43 | +If the Context passed into an operation does not have a deadline, you |
| 44 | +can set a ``Timeout`` option on your ``Client`` and the operation |
| 45 | +derives the timeout specification from this setting. To learn more |
| 46 | +about using the single timeout setting, see the |
| 47 | +:ref:`golang-timeout-setting` in the Connection Options guide. |
| 48 | + |
| 49 | +Expiration |
| 50 | +---------- |
| 51 | + |
| 52 | +The driver considers a Context expired when an operation exceeds its |
| 53 | +timeout or is canceled. The driver checks the Context expiration with |
| 54 | +the ``Done()`` method. |
| 55 | + |
| 56 | +The following sections describe when and how the driver checks for |
| 57 | +expiration. |
| 58 | + |
| 59 | +Server Selection |
| 60 | +~~~~~~~~~~~~~~~~ |
| 61 | + |
| 62 | +The driver might block a method call if it can't select a server for |
| 63 | +an operation. |
| 64 | + |
| 65 | +In this scenario, the driver loops until it finds a server to use for the |
| 66 | +operation. After each iteration, the driver returns a server selection |
| 67 | +timeout error if the Context expired or the selection process took |
| 68 | +longer than the ``serverSelectionTimeoutMS`` setting. |
| 69 | + |
| 70 | +To learn more about how the driver selects a server, see the |
| 71 | +:ref:`Read Concern <golang-readconcern>` section in the Configure |
| 72 | +CRUD Operations guide. |
| 73 | + |
| 74 | +Connection Checkout |
| 75 | +~~~~~~~~~~~~~~~~~~~ |
| 76 | + |
| 77 | +The driver might block a method call if there are no available |
| 78 | +connections to check out. |
| 79 | + |
| 80 | +After selecting a server, the driver tries to check out a connection |
| 81 | +from the server's connection pool. If the Context expires while checking |
| 82 | +out a connection, the method returns a timeout error. |
| 83 | + |
| 84 | +Connection Establishment |
| 85 | +~~~~~~~~~~~~~~~~~~~~~~~~ |
| 86 | + |
| 87 | +The driver might block a method call if it must create a new |
| 88 | +connection. |
| 89 | + |
| 90 | +When the driver creates a new connection to perform an operation, the |
| 91 | +Context sets a timeout for the establishment process. The driver sets the |
| 92 | +timeout to either the Context expiration or connection timeout, whichever is |
| 93 | +shorter. |
| 94 | + |
| 95 | +The following example sets the connection timeout to *1* second and the |
| 96 | +Context deadline to *2* seconds. Because the connection timeout is |
| 97 | +shorter, the establishment process expires after *1* second. |
| 98 | + |
| 99 | +.. code-block:: go |
| 100 | + :emphasize-lines: 2, 5 |
| 101 | + |
| 102 | + opts := options.Client() |
| 103 | + opts.SetConnectTimeout(1*time.Second) |
| 104 | + client, err := mongo.Connect(opts) |
| 105 | + |
| 106 | + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 107 | + defer cancel() |
| 108 | + client.Database("<db>").Collection("<collection>").InsertOne(ctx, bson.D{{"x",1}}) |
| 109 | + |
| 110 | +Socket Read and Write |
| 111 | +~~~~~~~~~~~~~~~~~~~~~ |
| 112 | + |
| 113 | +When the driver retrieves a connection for an operation, it sets the |
| 114 | +socket's read or write deadline to either the Context deadline or socket |
| 115 | +timeout, whichever is shorter. |
| 116 | + |
| 117 | +If you cancel the Context after the execution of the ``Read()`` or |
| 118 | +``Write()`` method but before its deadline, the behavior of the driver |
| 119 | +differs based on version. |
| 120 | + |
| 121 | +The driver generates a separate goroutine to listen for Context |
| 122 | +cancellation when the ``Read()`` or ``Write()`` method is in progress. |
| 123 | +If the goroutine detects a cancellation, it closes the connection. The |
| 124 | +pending ``Read()`` or ``Write()`` method returns an error which the |
| 125 | +driver overwrites with the ``context.Canceled`` error. |
| 126 | + |
| 127 | +.. important:: |
| 128 | + |
| 129 | + In versions before 1.5.0, the driver doesn't detect the Context |
| 130 | + cancellation and waits for the ``Read()`` or ``Write()`` method to |
| 131 | + return. |
0 commit comments