What context type should be used when closing a cursor? I’ve seen examples where the context used for finding the documents is also used for closing the cursor, e.g.:
But what would happen, if the cursor expires/times out shortly before or during closing? Would the cursor still be closed and the associated resources freed? I also found this comment inside the driver code:
func (c *Cursor) All(ctx context.Context, results interface{}) error {
...
// Defer a call to Close to try to clean up the cursor server-side when all
// documents have not been exhausted. Use context.Background() to ensure Close
// completes even if the context passed to All has errored.
defer c.Close(context.Background())
...
}
So, why would the API even require a context to be passed in? Any help or hints are highly appreciated.
Hey @Todor_Dimitrov, thanks for the question! It’s usually best to use context.Background() when closing a cursor, similar to what Cursor.All does. For example:
defer cursor.Close(context.Background())
There is a small risk that the Close call could block for a long time (e.g. if there is a network interruption), so we let users specify a context if they need to mitigate that risk. However, if the Close call doesn’t complete, the server-side cursor resources may not get cleaned up until they time out (30 minutes by default), so there’s a tradeoff. Client-side resources are always cleaned up when calling Close, even if the context is expired.
Note that if the cursor has been exhausted (i.e. all results were read) then Close doesn’t need to send any server commands, so the context is not used.
Thank you for pointing out that some documentation examples use the same context for iterating the cursor and for calling Close. I’ve created GODRIVER-3304 to always use context.Background() when closing cursors in example code.