Skip to content

Commit ced7d52

Browse files
committed
PYTHON-2205 Don't add stale connections to the pool
1 parent 350ada1 commit ced7d52

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

pymongo/pool.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1205,22 +1205,27 @@ def return_socket(self, sock_info, publish_checkin=True):
12051205
else:
12061206
if self.closed:
12071207
sock_info.close_socket(ConnectionClosedReason.POOL_CLOSED)
1208-
elif sock_info.generation != self.generation:
1209-
sock_info.close_socket(ConnectionClosedReason.STALE)
12101208
elif not sock_info.closed:
1211-
sock_info.update_last_checkin_time()
1212-
sock_info.update_is_writable(self.is_writable)
12131209
with self.lock:
1214-
self.sockets.appendleft(sock_info)
1210+
# Hold the lock to ensure this section does not race with
1211+
# Pool.reset().
1212+
if sock_info.generation != self.generation:
1213+
sock_info.close_socket(ConnectionClosedReason.STALE)
1214+
else:
1215+
sock_info.update_last_checkin_time()
1216+
sock_info.update_is_writable(self.is_writable)
1217+
self.sockets.appendleft(sock_info)
12151218

12161219
self._socket_semaphore.release()
12171220
with self.lock:
12181221
self.active_sockets -= 1
12191222

12201223
def _perished(self, sock_info):
1221-
"""This side-effecty function checks if this socket has been idle for
1224+
"""Return True and close the connection if it is "perished".
1225+
1226+
This side-effecty function checks if this socket has been idle for
12221227
for longer than the max idle time, or if the socket has been closed by
1223-
some external network error.
1228+
some external network error, or if the socket's generation is outdated.
12241229
12251230
Checking sockets lets us avoid seeing *some*
12261231
:class:`~pymongo.errors.AutoReconnect` exceptions on server
@@ -1243,6 +1248,10 @@ def _perished(self, sock_info):
12431248
sock_info.close_socket(ConnectionClosedReason.ERROR)
12441249
return True
12451250

1251+
if sock_info.generation != self.generation:
1252+
sock_info.close_socket(ConnectionClosedReason.STALE)
1253+
return True
1254+
12461255
return False
12471256

12481257
def _raise_wait_queue_timeout(self):

0 commit comments

Comments
 (0)