@@ -87,6 +87,7 @@ def initialize(view, result, server, options = {})
8787 @connection_global_id = result . connection_global_id
8888 @context = @options [ :context ] &.with ( connection_global_id : connection_global_id_for_context ) || fresh_context
8989 @explicitly_closed = false
90+ @get_more_network_error = false
9091 @lock = Mutex . new
9192 if server . load_balancer?
9293 # We need the connection in the cursor only in load balanced topology;
@@ -297,19 +298,21 @@ def close(opts = {})
297298 ctx = context ? context . refresh ( timeout_ms : opts [ :timeout_ms ] ) : fresh_context ( opts )
298299
299300 unregister
300- read_with_one_retry do
301- spec = {
302- coll_name : collection_name ,
303- db_name : database . name ,
304- cursor_ids : [ id ] ,
305- }
306- op = Operation ::KillCursors . new ( spec )
307- execute_operation ( op , context : ctx )
301+ unless @get_more_network_error
302+ read_with_one_retry do
303+ spec = {
304+ coll_name : collection_name ,
305+ db_name : database . name ,
306+ cursor_ids : [ id ] ,
307+ }
308+ op = Operation ::KillCursors . new ( spec )
309+ execute_operation ( op , context : ctx )
310+ end
308311 end
309312
310313 nil
311- rescue Error ::OperationFailure ::Family , Error ::SocketError , Error ::SocketTimeoutError , Error ::ServerNotUsable
312- # Errors are swallowed since there is noting can be done by handling them.
314+ rescue Error ::OperationFailure ::Family , Error ::SocketError , Error ::SocketTimeoutError , Error ::ServerNotUsable , Error :: ConnectionPerished
315+ # Errors are swallowed since there is nothing can be done by handling them.
313316 ensure
314317 end_session
315318 @cursor_id = 0
@@ -379,6 +382,9 @@ def get_more
379382 with_overload_retry ( context : possibly_refreshed_context ) do
380383 process ( execute_operation ( get_more_operation ) )
381384 end
385+ rescue Error ::SocketError , Error ::SocketTimeoutError
386+ @get_more_network_error = true
387+ raise
382388 rescue Error ::OperationFailure => e
383389 # When overload retries are exhausted on getMore, close the cursor
384390 # so that killCursors is sent to the server.
@@ -579,7 +585,12 @@ def check_in_connection
579585 return if @connection . nil?
580586 return unless @connection . server . load_balancer?
581587
582- @connection . connection_pool . check_in ( @connection )
588+ @connection . unpin
589+ # Do not check in if the connection is still pinned by something
590+ # else (e.g. a transaction).
591+ unless @connection . pinned?
592+ @connection . connection_pool . check_in ( @connection )
593+ end
583594 @connection = nil
584595 end
585596 end
0 commit comments