MCPcopy Index your code
hub / github.com/mongodb/mongo-python-driver / _ServerSessionPool

Class _ServerSessionPool

pymongo/asynchronous/client_session.py:1209–1267  ·  view source on GitHub ↗

Pool of _ServerSession objects. This class is thread-safe.

Source from the content-addressed store, hash-verified

1207
1208
1209class _ServerSessionPool(collections.deque): # type: ignore[type-arg]
1210 """Pool of _ServerSession objects.
1211
1212 This class is thread-safe.
1213 """
1214
1215 def __init__(self, *args: Any, **kwargs: Any):
1216 super().__init__(*args, **kwargs)
1217 self.generation = 0
1218
1219 def reset(self) -> None:
1220 self.generation += 1
1221 self.clear()
1222
1223 def pop_all(self) -> list[_ServerSession]:
1224 ids = []
1225 while True:
1226 try:
1227 ids.append(self.pop().session_id)
1228 except IndexError:
1229 break
1230 return ids
1231
1232 def get_server_session(self, session_timeout_minutes: Optional[int]) -> _ServerSession:
1233 # Although the Driver Sessions Spec says we only clear stale sessions
1234 # in return_server_session, PyMongo can't take a lock when returning
1235 # sessions from a __del__ method (like in AsyncCursor.__die), so it can't
1236 # clear stale sessions there. In case many sessions were returned via
1237 # __del__, check for stale sessions here too.
1238 self._clear_stale(session_timeout_minutes)
1239
1240 # The most recently used sessions are on the left.
1241 while True:
1242 try:
1243 s = self.popleft()
1244 except IndexError:
1245 break
1246 if not s.timed_out(session_timeout_minutes):
1247 return s
1248
1249 return _ServerSession(self.generation)
1250
1251 def return_server_session(self, server_session: _ServerSession) -> None:
1252 # Discard sessions from an old pool to avoid duplicate sessions in the
1253 # child process after a fork.
1254 if server_session.generation == self.generation and not server_session.dirty:
1255 self.appendleft(server_session)
1256
1257 def _clear_stale(self, session_timeout_minutes: Optional[int]) -> None:
1258 # Clear stale sessions. The least recently used are on the right.
1259 while True:
1260 try:
1261 s = self.pop()
1262 except IndexError:
1263 break
1264 if not s.timed_out(session_timeout_minutes):
1265 self.append(s)
1266 # The remaining sessions also haven't timed out.

Callers 1

__init__Method · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected