@@ -861,10 +861,11 @@ def __init__(
861861 srv_max_hosts = srv_max_hosts ,
862862 server_monitoring_mode = options .server_monitoring_mode ,
863863 )
864- self ._topology = Topology (self ._topology_settings )
865864
866865 self ._opened = False
867866 self ._closed = False
867+ if not is_srv :
868+ self ._init_background (first = True )
868869
869870 self ._resolve_srv_info .update (
870871 {
@@ -977,19 +978,13 @@ def _resolve_srv(self) -> None:
977978 srv_max_hosts = srv_max_hosts ,
978979 server_monitoring_mode = self ._options .server_monitoring_mode ,
979980 )
980- self ._topology = Topology (self ._topology_settings )
981981
982982 if self ._options .auto_encryption_opts :
983983 from pymongo .asynchronous .encryption import _Encrypter
984984
985985 self ._encrypter = _Encrypter (self , self ._options .auto_encryption_opts )
986986 self ._timeout = self ._options .timeout
987987
988- if _HAS_REGISTER_AT_FORK :
989- # Add this client to the list of weakly referenced items.
990- # This will be used later if we fork.
991- AsyncMongoClient ._clients [self ._topology ._topology_id ] = self
992-
993988 def _normalize_and_validate_options (
994989 self , opts : common ._CaseInsensitiveDictionary , seeds : set [tuple [str , int | None ]]
995990 ) -> common ._CaseInsensitiveDictionary :
@@ -1019,7 +1014,12 @@ async def aconnect(self) -> None:
10191014 """Explicitly connect to MongoDB asynchronously instead of on the first operation."""
10201015 await self ._get_topology ()
10211016
1022- def _init_background (self , old_pid : Optional [int ] = None ) -> None :
1017+ def _init_background (self , old_pid : Optional [int ] = None , first = False ) -> None :
1018+ self ._topology = Topology (self ._topology_settings )
1019+ if first and _HAS_REGISTER_AT_FORK :
1020+ # Add this client to the list of weakly referenced items.
1021+ # This will be used later if we fork.
1022+ AsyncMongoClient ._clients [self ._topology ._topology_id ] = self
10231023 # Seed the topology with the old one's pid so we can detect clients
10241024 # that are opened before a fork and used after.
10251025 self ._topology ._pid = old_pid
@@ -1679,7 +1679,7 @@ async def close(self) -> None:
16791679 .. versionchanged:: 3.6
16801680 End all server sessions created by this client.
16811681 """
1682- if self . _opened :
1682+ if hasattr ( self , "_topology" ) :
16831683 session_ids = self ._topology .pop_all_sessions ()
16841684 if session_ids :
16851685 await self ._end_sessions (session_ids )
@@ -1712,7 +1712,7 @@ async def _get_topology(self) -> Topology:
17121712 if not self ._opened :
17131713 if self ._resolve_srv_info ["is_srv" ]:
17141714 self ._resolve_srv ()
1715- self ._init_background ()
1715+ self ._init_background (first = True )
17161716 await self ._topology .open ()
17171717 async with self ._lock :
17181718 self ._kill_cursors_executor .open ()
0 commit comments