
    nh                    R   d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlmZ ddlmZmZmZmZmZmZ ddlmZmZmZmZ ddlmZmZmZmZmZm Z m!Z!m"Z"m#Z# ddl$m%Z% dd	l&m'Z'm(Z(m)Z) dd
l*m+Z+m,Z,m-Z-m.Z.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8m9Z9 ddl:m;Z;m<Z< ddl=m>Z>m?Z? ddl@mAZA ddlBmCZC ddlDmEZEmFZFmGZGmHZHmIZI erddlJmKZK ddlLmMZM ddlNmOZOmPZP dZQ eR eeS      j                        ZUddZV G d d      ZW G d d      ZX	 	 	 	 	 	 d dZYd!dZZ	 d"	 	 	 	 	 d#dZ[y)$z<Internal class to monitor a topology of one or more servers.    )annotationsN)Path)TYPE_CHECKINGAnyCallableMappingOptionalcast)_csotcommonhelpers_sharedperiodic_executor)	ConnectionFailureInvalidOperationNetworkTimeoutNotPrimaryErrorOperationFailurePyMongoErrorServerSelectionTimeoutErrorWaitQueueTimeoutError
WriteError)Hello)
_cond_wait_create_condition_create_lock)_SDAM_LOGGER_SERVER_SELECTION_LOGGER
_debug_log_SDAMStatusMessage_ServerSelectionStatusMessage)PoolOptions)ServerDescription)	Selectionany_server_selectorarbiter_server_selectorsecondary_server_selectorwritable_server_selector)_ServerSession_ServerSessionPool)MonitorBase
SrvMonitor)Pool)Server)SRV_POLLING_TOPOLOGIESTOPOLOGY_TYPETopologyDescription)_updated_topology_description_srv_pollingupdated_topology_description)ObjectId)TopologySettings)ClusterTime_AddressTc                     |        }|sy	 	 |j                         }|\  }} ||  # t        j                  $ r Y yw xY w)NFT)
get_nowaitqueueEmpty)	queue_refqeventfnargss        /var/www/html/SchoolMeal/SchoolMeal/pds_admin_SchoolMeal/Backend/venv/lib/python3.12/site-packages/pymongo/synchronous/topology.pyprocess_events_queuerA   W   sV    A
	LLNE HBI  {{ 	
 	s   ( >>c                  :   e Zd ZdZd/dZd0dZd1dZ	 	 	 d2	 	 	 	 	 	 	 	 	 	 	 d3dZ	 	 	 	 	 	 	 	 	 	 	 	 d4dZ	 	 	 	 d5	 	 	 	 	 	 	 	 	 	 	 	 	 d6dZ		 	 	 	 d5	 	 	 	 	 	 	 	 	 	 	 	 	 d6d	Z
	 	 d7	 	 	 	 	 	 	 	 	 d8d
Z	 	 d9	 	 	 	 	 	 	 d:dZ	 	 d9	 	 	 	 	 	 	 d:dZd;dZd;dZd<dZd=dZd>dZd?dZd@dZd@dZdAdZdBdZdBdZdCdDdZdEdZd0dZd0dZedFd       ZdGdZdHdZ dIdZ!dJd Z"d0d!Z#dKd"Z$dLd#Z%dLd$Z&d0d%Z'd0d&Z(dMd'Z)dMd(Z*dNd)Z+d0d*Z,dOd+Z-dPd,Z.dQd-Z/dRd.Z0y)STopologyz*Monitor a topology of one or more servers.c           	     	   |j                   | _         |j                  j                  | _        | j                  d uxr | j                  j                  | _        | j                  d uxr | j                  j                  | _        d | _        d | _	        | j
                  s| j                  rt        j                  d      | _        t        j                  t        j                        r*t!        t        t"        j$                  | j                          | j                  rJ| j                  J | j                  j'                  | j                  j(                  | j                   ff       || _        t-        |j/                         |j1                         |j2                  d d |      }|| _        t-        t6        j8                  i d d d | j*                        }| j                  rV| j                  J | j                  j'                  | j                  j:                  || j4                  | j                   ff       t        j                  t        j                        r6t!        t        t"        j<                  | j                   || j4                         |j>                  D ]  }| j
                  rK| j                  J | j                  j'                  | j                  j@                  || j                   ff       t        j                  t        j                        s~t!        t        t"        jB                  | j                   |d   |d           tE        |jG                               | _$        d| _%        d| _&        tO               | _(        tS        | jP                  tT        r| j*                  jV                  nd       | _,        i | _-        d | _.        d | _/        ta               | _1        | j
                  s| j                  r| j                  J dfd	}te        jf                  th        jj                  th        jl                  |d
      }to        jp                  | j                  |jr                        || _	        |ju                          d | _;        | j*                  jx                  1| j*                  jz                  st}        | | j*                        | _;        g | _?        y )Nd   )maxsizemessage
topologyIdrH   rI   previousDescriptionnewDescriptionr      )rH   rI   
serverHost
serverPortFc                     t               S N)rA   )weaks   r@   targetz!Topology.__init__.<locals>.target   s    +D11    pymongo_events_thread)intervalmin_intervalrS   name)returnbool)@_topology_id_pool_options_event_listeners
_listenersenabled_for_server_publish_serverenabled_for_topology_publish_tp_events_Topology__events_executorr9   Queuer   isEnabledForloggingDEBUGr   r   START_TOPOLOGYputpublish_topology_opened	_settingsr0   get_topology_typeget_server_descriptionsreplica_set_name_descriptionr/   Unknown$publish_topology_description_changedTOPOLOGY_CHANGEseedspublish_server_openedSTART_SERVERlistserver_descriptions_seed_addresses_opened_closedr   _lockr   _IS_SYNCcondition_class
_condition_servers_pid_max_cluster_timer)   _session_poolr   PeriodicExecutorr   EVENTS_QUEUE_FREQUENCYMIN_HEARTBEAT_INTERVALweakrefrefcloseopen_srv_monitorfqdnload_balancedr+   _monitor_tasks)selftopology_settingstopology_description
initial_tdseedrS   executorrR   s          @r@   __init__zTopology.__init__k   s   -::+99JJ#d:at?a?a??$6_4??;_;_ &*4#3#3 ;;s3DL$$W]]3*99,, <<+++LLdooEEHYHYG[\]*2//1557.. 
 1(!!2tT4

 <<+++LLOOHH!2!2D4E4EF $$W]]3*::,,$.#00 &++ 	D##||///  $//"G"G$PTPaPaIb!cd((7 .;;#00#Aw#Aw	  $$8$L$L$NO!^
+JJ(66
 13#'	8</14#3#3<<+++2 )9966#::,	H ;;t||X^^<D%-D"MMO >>*4>>3O3O *4 @D 24rT   c                *   t        j                         }| j                  || _        n|| j                  k7  r|| _        t        j                  dd dk\  r
dt
        fi}nddi}t        j                  	 di | | j                  5  | j                  j                         D ]  }|j                           | j                  j                          ddd       | j                  5  | j                          ddd       y# 1 sw Y   /xY w# 1 sw Y   yxY w)a  Start monitoring, or restart after a fork.

        No effect if called multiple times.

        .. warning:: Topology is shared among multiple threads and is protected
          by mutual exclusion. Using Topology from a process other than the one
          that initialized it will emit a warning and may result in deadlock. To
          prevent this from happening, MongoClient must be created after any
          forking.

        N   )      skip_file_prefixes
stacklevel   )zMongoClient opened before fork. May not be entirely fork-safe, proceed with caution. See PyMongo's documentation for details: https://dochub.mongodb.org/core/pymongo-fork-deadlock)osgetpidr   sysversion_info_pymongo_dirwarningswarnr|   r   valuesr   r   reset_ensure_opened)r   pidkwargsservers       r@   r   zTopology.open   s     iik99DIDIIDI#w..@&*MMH 	  +"mm224 #FLLN# ""((*+ ZZ 	"!	" 	"+ +	" 	"s   A
C=#D	=D	Dc                ^    t        j                         }|| j                  j                  S |S rQ   )r   	remainingrl   server_selection_timeout)r   timeouts     r@   get_server_selection_timeoutz%Topology.get_server_selection_timeout   s(    //#?>>:::rT   Nc           
     V   || j                         }n|}t        s| j                  r| j                          | j                  5  | j                  |||||      }|D cg c]+  }t        t        | j                  |j                              - c}cddd       S c c}w # 1 sw Y   yxY w)a  Return a list of Servers matching selector, or time out.

        :param selector: function that takes a list of Servers and returns
            a subset of them.
        :param operation: The name of the operation that the server is being selected for.
        :param server_selection_timeout: maximum seconds to wait.
            If not provided, the default value common.SERVER_SELECTION_TIMEOUT
            is used.
        :param address: optional server address to select.

        Calls self.open() if needed.

        Raises exc:`ServerSelectionTimeoutError` after
        `server_selection_timeout` if no matching servers are found.
        N)
r   r}   r   cleanup_monitorsr|   _select_servers_loopr
   r-   get_server_by_addressaddress)	r   selector	operationr   r   operation_idserver_timeoutrx   sds	            r@   select_serverszTopology.select_servers  s    . $+!>>@N5N D//!!#ZZ 	"&";";.)\7#
 PcIKVT77

CD	 	
	 	s   B0BBBB(c                V   t        j                         }||z   }d}t        j                  t        j
                        rLt        t        t        j                  |||| j                  | j                  j                  j                         | j                  j                  ||| j                  j                        }	|	s|dk(  s||kD  rt        j                  t        j
                        r\t        t        t        j                   |||| j                  | j                  j                  j                  | j#                  |             t%        | j#                  |       d| d| j                        |spt        t        t        j&                  |||| j                  | j                  j                  j                  t)        d|t        j                         z
  z        	       d
}| j+                          | j-                          t/        | j0                  t2        j4                         | j                  j7                          t        j                         }| j                  j                  ||| j                  j                        }	|	s| j                  j7                          |	S )z7select_servers() guts. Hold the lock when calling this.F)rH   r   r   operationIdtopologyDescriptionclientId)custom_selectorr   )rH   r   r   r   r   r   failurez, Timeout: zs, Topology Description: i  )rH   r   r   r   r   r   remainingTimeMST)time	monotonicr   rf   rg   rh   r   r    STARTEDdescription_topology_settingsr[   rp   apply_selectorrl   server_selectorFAILED_error_messager   WAITINGintr   _request_check_allr   r   r   r   check_compatible)
r   r   r   r   r   r   nowend_timelogged_waitingrx   s
             r@   r   zTopology._select_servers_loop.  s:    nn=#00?(5==!#($($4$4))<<II #//>>gt~~/M/M ? 
 &!|sX~+88G0 = D D!)"+$0,0,<,<!%!1!1!D!D!Q!Q $ 3 3H =	 2**845[	Ibcgcscsbvw  ",9AA%' ,(,(8(8!--@@MM$'4>>;K0K(L$M	 "&!##% t(E(EF..0.."C"&"3"3"B"B'4>>3Q3Q #C #S &Z 	**,""rT   c                    | j                  |||||      }t        ||      }t        |      dk(  r|d   S t        j                  |d      \  }}	|j
                  j                  |	j
                  j                  k  r|S |	S )NrM   r   r   )r   _filter_serverslenrandomsamplepooloperation_count)
r   r   r   r   r   deprioritized_serversr   serversserver1server2s
             r@   _select_serverzTopology._select_serverz  s     %%i!97L
 "'+@Aw<11:!==!4<<''7<<+G+GGNNrT   c                   | j                  ||||||      }t        j                         r)t        j                  |j                  j
                         t        j                  t        j                        r|t        t        t        j                  |||| j                  | j                  j                  j                  |j                  j                  d   |j                  j                  d   	       |S )zALike select_servers, but choose a random server if several match.r   r   rM   )rH   r   r   r   r   r   rN   rO   )r   r   get_timeoutset_rttr   min_round_trip_timer   rf   rg   rh   r   r    	SUCCEEDEDr   r[   r   )r   r   r   r   r   r   r   r   s           r@   select_serverzTopology.select_server  s     $$$!% % 
 MM&,,@@A#00?(5??!#($($4$4))<<II!--55a8!--55a8
 rT   c                6    | j                  t        ||||      S )a=  Return a Server for "address", reconnecting if necessary.

        If the server's type is not known, request an immediate check of all
        servers. Time out after "server_selection_timeout" if the server
        cannot be reached.

        :param address: A (host, port) pair.
        :param operation: The name of the operation that the server is being selected for.
        :param server_selection_timeout: maximum seconds to wait.
            If not provided, the default value
            common.SERVER_SELECTION_TIMEOUT is used.
        :param operation_id: The unique id of the current operation being performed. Defaults to None if not provided.

        Calls self.open() if needed.

        Raises exc:`ServerSelectionTimeoutError` after
        `server_selection_timeout` if no matching servers are found.
        r   )r   r$   )r   r   r   r   r   s        r@   select_server_by_addressz!Topology.select_server_by_address  s+    2 !!$% " 
 	
rT   c                   | j                   }|j                  |j                     }t        ||      ryt	        | j                   |      }|j
                  s)|j                  r^|j                  t        j                  k(  rA| j                  j                  |j                        }|r|j                  j                          ||k(  }| j                  rY|sW| j                  J | j                  j!                  | j"                  j$                  |||j                  | j&                  ff       || _         | j)                          | j*                  rX|sV| j                  J | j                  j!                  | j"                  j,                  || j                   | j&                  ff       t/        j0                  t2        j4                        r8|s6t7        t.        t8        j:                  | j&                  || j                          | j<                  r~|j                  t        j>                  k(  ra| j                   j                  t@        vrE| j<                  jC                          tD        s%| jF                  jI                  | j<                         |rC| j                  j                  |j                        }|r|j                  jK                  |       | jL                  jO                          y)ziProcess a new ServerDescription on an opened topology.

        Hold the lock when calling this.
        NrJ   )interrupt_connections)(rp   _server_descriptionsr   _is_stale_server_descriptionr2   is_readableis_server_type_knowntopology_typer/   Singler   getr   readyr`   rc   rj   r^   "publish_server_description_changedr[   _update_serversrb   rr   r   rf   rg   rh   r   r   rs   r   rq   r.   r   r}   r   appendr   r   
notify_all)	r   server_description
reset_poolr   td_oldsd_oldnew_tdr   suppress_events	            r@   _process_changezTopology._process_change  sW    "",,-?-G-GH'0BC-d.?.?AST))338L8LP]PdPd8d]]&&'9'A'ABF!!##55<<+++LLOOFF/1C1K1KTM^M^_ #N<<+++LLOOHHT..0A0AB $$W]]3N*::,,$*#00   M$9$99!!//7MM##%##**4+<+<= ]]&&'9'A'ABF!!8M!N 	""$rT   c                    | j                   5  | j                  r8| j                  j                  |j                        r| j                  |||       ddd       y# 1 sw Y   yxY w)z>Process a new ServerDescription after an hello call completes.N)r|   rz   rp   
has_serverr   r   )r   r   r   r   s       r@   	on_changezTopology.on_change  s[     ZZ 
	\ || 1 1 < <=O=W=W X$$%7EZ[
	\ 
	\ 
	\s   AAA$c                   | j                   }|j                  t        vryt        | j                   |      | _         | j	                          | j
                  rV| j                  J | j                  j                  | j                  j                  || j                   | j                  ff       t        j                  t        j                        r7t        t        t         j"                  | j                  || j                          yy)z_Process a new seedlist on an opened topology.
        Hold the lock when calling this.
        NrJ   )rp   r   r.   r1   r   rb   rc   rj   r^   rr   r[   r   rf   rg   rh   r   r   rs   )r   seedlistr   s      r@   _process_srv_updatezTopology._process_srv_update1  s     ""'==EdFWFWYab<<+++LLOOHHT..0A0AB $$W]]3*::,,$*#00 4rT   c                    | j                   5  | j                  r| j                  |       ddd       y# 1 sw Y   yxY w)z?Process a new list of nodes obtained from scanning SRV records.N)r|   rz   r   )r   r   s     r@   on_srv_updatezTopology.on_srv_updateM  s5     ZZ 	3||((2	3 	3 	3s   4=c                8    | j                   j                  |      S )aJ  Get a Server or None.

        Returns the current version of the server immediately, even if it's
        Unknown or absent from the topology. Only use this in unittests.
        In driver code, use select_server_by_address, since then you're
        assured a recent view of the server's type and wire protocol version.
        )r   r   r   r   s     r@   r   zTopology.get_server_by_addressT  s     }}  ))rT   c                    || j                   v S rQ   )r   r  s     r@   r   zTopology.has_server^  s    $--''rT   c                    | j                   5  | j                  j                  }|t        j                  k7  r
	 ddd       yt        | j                               d   j                  cddd       S # 1 sw Y   yxY w)z!Return primary's address or None.Nr   )r|   rp   r   r/   ReplicaSetWithPrimaryr'   _new_selectionr   )r   r   s     r@   get_primaryzTopology.get_primarya  sp     ZZ 	N --;;M C CC	N 	N
 ,D,?,?,AB1EMM	N 	N 	Ns   +A0%A00A9c                T   | j                   5  | j                  j                  }|t        j                  t        j
                  fvrt               cddd       S t         || j                                     D ch c]  }|j                   c}cddd       S c c}w # 1 sw Y   yxY w)z+Return set of replica set member addresses.N)
r|   rp   r   r/   r  ReplicaSetNoPrimarysetiterr  r   )r   r   r   r   s       r@   _get_replica_set_membersz!Topology._get_replica_set_membersk  s     ZZ 	P --;;M3311%  u	P 	P *.ht7J7J7L.M)NO2BJJO	P 	P P	P 	Ps$   AB!B:BBBB'c                ,    | j                  t              S )z"Return set of secondary addresses.)r  r&   r   s    r@   get_secondarieszTopology.get_secondariesx  s    ,,-FGGrT   c                ,    | j                  t              S )z Return set of arbiter addresses.)r  r%   r  s    r@   get_arbiterszTopology.get_arbiters|  s    ,,-DEErT   c                    | j                   S )z1Return a document, the highest seen $clusterTime.r   r  s    r@   max_cluster_timezTopology.max_cluster_time  s    %%%rT   c                \    |r*| j                   r|d   | j                   d   kD  r|| _         y y y )NclusterTimer  r   cluster_times     r@   _receive_cluster_time_no_lockz&Topology._receive_cluster_time_no_lock  s=      **.1G1G1VV)5& W	 rT   c                h    | j                   5  | j                  |       d d d        y # 1 sw Y   y xY wrQ   )r|   r  r  s     r@   receive_cluster_timezTopology.receive_cluster_time  s,    ZZ 	=..|<	= 	= 	=s   (1c                    | j                   5  | j                          t        | j                  |       ddd       y# 1 sw Y   yxY w)z=Wake all monitors, wait for at least one to check its server.N)r|   r   r   r   )r   	wait_times     r@   request_check_allzTopology.request_check_all  s8    ZZ 	3##%t	2	3 	3 	3s	   '=Ac                    | j                   j                  t        j                  k(  r| j                   j                  S | j                   j
                  S )z~Return a list of all data-bearing servers.

        This includes any server that might be selected for an operation.
        )rp   r   r/   r   known_serversreadable_serversr  s    r@   data_bearing_serverszTopology.data_bearing_servers  sB    
 **m.B.BB$$222  111rT   c           	        g }| j                   5  | j                         D ]P  }| j                  |j                     }|j	                  ||j
                  j                  j                         f       R 	 d d d        |D ]!  \  }}	 |j
                  j                  |       # y # 1 sw Y   0xY w# t        $ r;}t        |d|dd       }| j                  |j                  j                  |        d }~ww xY w)Nr   F)r|   r$  r   r   r   r   genget_overallremove_stale_socketsr   _ErrorContexthandle_errorr   )r   r   r   r   
generationexcctxs          r@   update_poolzTopology.update_pool  s    ZZ 	H//1 Hrzz2(C(C(EFGH	H #* 	FJ00<		H 	H   #CJtD!!&"4"4"<"<cBs$   A$B#B/#B,/	C386C..C3c                   | j                   5  | j                  }| j                  j                         D ]>  }|j	                          t
        r| j                  j                  |j                         @ | j                  j                         | _        | j                  j                         j                         D ](  \  }}|| j                  v s|| j                  |   _        * | j                  rE| j                  j	                          t
        s%| j                  j                  | j                         d| _        d| _        ddd       | j                   r| j"                  J t%        t&        j(                  i | j                  j*                  | j                  j,                  | j                  j.                  | j                  j0                        | _        | j"                  j3                  | j4                  j6                  | j                  | j8                  ff       | j"                  j3                  | j4                  j:                  | j8                  ff       t=        j>                  t@        jB                        r`tE        t<        tF        jH                  | j8                  | j                         tE        t<        tF        jJ                  | j8                         | jL                  s| j                   r^| jN                  j	                          | jN                  jQ                  d       tS        tU        jV                  | j"                               yy# 1 sw Y   xY w)zClear pools and terminate monitors. Topology does not reopen on
        demand. Any further operations will raise
        :exc:`~.errors.InvalidOperation`.
        FTNrJ   rG   rM   ),r|   rp   r   r   r   r}   r   r   _monitorr   rx   itemsr   r   rz   r{   rb   rc   r0   r/   rq   ro   max_set_versionmax_election_idr   rj   r^   rr   r[   publish_topology_closedr   rf   rg   rh   r   r   rs   STOP_TOPOLOGYr`   rd   joinrA   r   r   )r   old_tdr   r   r   s        r@   r   zTopology.close  s   
 ZZ 	 &&F--..0 @''..v?@ !% 1 1 7 7 9D#00DDFLLN <dmm+9;DMM'*6<
   !!'')''..t/@/@A DLDL)	 . <<+++ 3%%!!22!!11!!11!!44!D LLOOHH))))	 LLdooEEHYHYG[\]$$W]]3*::,,$*#00 &8&F&FSWSdSd 4#3#3""((*""''* T\\!:;	 $4q	  	 s   A MBMA5MM$c                    | j                   S rQ   )rp   r  s    r@   r   zTopology.description  s       rT   c                6    | j                   j                         S )z"Pop all session ids from the pool.)r   pop_allr  s    r@   pop_all_sessionszTopology.pop_all_sessions  s    !!))++rT   c                8    | j                   j                  |      S )z>Start or resume a server session, or raise ConfigurationError.)r   get_server_session)r   session_timeout_minutess     r@   r=  zTopology.get_server_session  s    !!445LMMrT   c                :    | j                   j                  |       y rQ   )r   return_server_session)r   server_sessions     r@   r@  zTopology.return_server_session  s    00@rT   c                @    t        j                  | j                        S )zmA Selection object, initially including all known servers.

        Hold the lock when calling this.
        )r#   from_topology_descriptionrp   r  s    r@   r  zTopology._new_selection	  s    
 2243D3DEErT   c                h   | j                   rt        d      | j                  sd| _        | j                          | j                  s| j
                  r| j                  j                          | j                  r6| j                  j                  t        v r| j                  j                          | j                  j                  r?| j                  t        | j                   d   t#        d| j$                  dd                   | j&                  j)                         D ]  }|j                           y)z[Start monitors, or restart after a fork.

        Hold the lock when calling this.
        z"Cannot use MongoClient after closeTr   rM      )ok	serviceIdmaxWireVersionN)r{   r   rz   r   rb   r`   rd   r   r   r   r   r.   rl   r   r   r"   ry   r   r[   r   r   r   r   s     r@   r   zTopology._ensure_opened  s    
 <<"#GHH||DL  " 4#7#7&&++-   d&6&6&D&DH^&^!!&&(~~++$$%,,Q/QT5F5FZ\]^ mm**, 	FKKM	rT   c                   | j                   j                  |      }|y|j                  j                  |j                  |j
                        ry|j                  j                  }|j                  }d }|rAt        |d      r5t        |j                  t              r|j                  j                  d      }t        ||      S )NTdetailstopologyVersion)r   r   _poolstale_generationsock_generation
service_idr   topology_versionerrorhasattr
isinstancerK  dict _is_stale_error_topology_version)r   r   err_ctxr   cur_tvrR  error_tvs          r@   _is_stale_errorzTopology._is_stale_error1  s    ""7+><<(()@)@'BTBTU ##44WUI.%--. ==,,->?/AArT   c                   | j                  ||      ry | j                  |   }|j                  }|j                  }| j                  j
                  r|s|j                  sy t        |t              r|j                  ry t        |t              ry t        |t        t        f      r#t        |d      r|j                  }n0t        |t              rdnd }|j                  j                  d|      }|t         j"                  v rw|t         j$                  v }| j                  j
                  s| j'                  t)        ||             |s|j*                  dk  r|j-                  |       |j/                          y |j                  sD| j                  j
                  s| j'                  t)        ||             |j-                  |       y y t        |t0              rot        |t2              ry | j                  j
                  s| j'                  t)        ||             |j-                  |       |j4                  j7                          y y )Ncodei{'  rR     )rZ  r   rR  rP  rl   r   completed_handshakerT  r   r   r   r   rS  r\  rK  r   r   _NOT_PRIMARY_CODES_SHUTDOWN_CODESr   r"   max_wire_versionr   request_checkr   r   r0  cancel_check)	r   r   rW  r   rR  rP  err_codedefaultis_shutting_downs	            r@   _handle_errorzTopology._handle_errorE  s   1w'''
 >>''
7C^C^e^,1L1L
 z*1ABC uf% :: $.e_#E%4 ==,,VW=><<<#+~/M/M#M ~~33(():7%)PQ#(@(@A(ELL,$$&00~~33(():7%)PQZ( 1 01%!67 >>//$$%6we%LMLL$ OO((* 2rT   c                j    | j                   5  | j                  ||       ddd       y# 1 sw Y   yxY w)zHandle an application error.

        May reset the server to Unknown, clear the pool, and request an
        immediate check depending on the error and the context.
        N)r|   rh  )r   r   rW  s      r@   r*  zTopology.handle_error  s0     ZZ 	1w0	1 	1 	1s   )2c                b    | j                   j                         D ]  }|j                           y)z3Wake all monitors. Hold the lock when calling this.N)r   r   rc  rI  s     r@   r   zTopology._request_check_all  s*    mm**, 	#F  "	#rT   c           	     <   | j                   j                         j                         D ]S  \  }}|| j                  vr| j                  j                  || | j                  |      | j                        }d}| j                  r+| j                  t        j                  | j                        }t        || j                  |      || j                  | j                  |      }|| j                  |<   |j                          | j                  |   j                   j"                  }|| j                  |   _        ||j"                  k7  s"| j                  |   j$                  j'                  |j"                         V t)        | j                  j                               D ]w  \  }}| j                   j+                  |      r"|j-                          t.        s%| j0                  j3                  |j4                         | j                  j7                  |       y y)zrSync our Servers from TopologyDescription.server_descriptions.

        Hold the lock while calling this.
        )r   topologyr   r   N)r   r   monitortopology_id	listenersevents)rp   rx   r1  r   rl   monitor_class_create_pool_for_monitorr`   rc   r   r   r-   _create_pool_for_serverr[   r^   r   r   is_writabler   update_is_writablerw   r   r   r}   r   r   r0  pop)r   r   r   rm  rR   r   was_writables          r@   r   zTopology._update_servers  s   
  ,,@@BHHJ 	SKGRdmm+..66')!66w?&*nn	 7  ''DLL,D";;t||4D')55g># $ 1 1"oo *0g&  $}}W5AAMM57g&22>>1MM'*//BB2>>R=	S@  $DMM$7$7$9: 	+OGV$$//8''..v?!!'*	+rT   c                z    | j                   j                  || j                   j                  | j                        S )N)	client_id)rl   
pool_classpool_optionsr[   r  s     r@   rs  z Topology._create_pool_for_server  s5    ~~((T^^00D<M<M ) 
 	
rT   c                H   | j                   j                  }t        |j                  |j                  |j                  |j
                  |j                  |j                  |j                  d|j                  	      }| j                   j                  ||d| j                        S )NF)	connect_timeoutsocket_timeoutssl_contexttls_allow_invalid_hostnamesevent_listenersappnamedriverpause_enabled
server_api)	handshakery  )rl   r{  r!   r}  _ssl_contextr  r]   r  r  r  rz  r[   )r   r   optionsmonitor_pool_optionss       r@   rr  z!Topology._create_pool_for_monitor  s    ..--
  +#33"22,,(/(K(K#44OO>>))
 
 ~~(()UdFWFW ) 
 	
rT   c                0   | j                   j                  t        j                  t        j                  fv }|rd}n,| j                   j                  t        j
                  k(  rd}nd}| j                   j                  r|t        u r|ryd|z  S d| d| dS t        | j                   j                               }t        | j                   j                         j                               }|s-|r&d	j                  || j                  j                        S d
|z  S |d   j                  t        fd|dd D              }|r=d|z  S |r)t!        |      j#                  | j$                        sd|z  S t'              S dj)                  d |D              S )zeFormat an error message if server selection fails.

        Hold the lock when calling this.
        zreplica set membersmongosesr   zNo primary available for writeszNo %s available for writeszNo z match selector ""z)No {} available for replica set name "{}"zNo %s availabler   c              3  <   K   | ]  }|j                   k(    y wrQ   r]  ).0r   rR  s     r@   	<genexpr>z*Topology._error_message.<locals>.<genexpr>  s     Gv||u,Gs   rM   NzNo %s found yetz\Could not reach any servers in %s. Replica set is configured with internal hostnames or IPs?,c              3  `   K   | ]&  }|j                   st        |j                          ( y wrQ   )rR  str)r  r   s     r@   r  z*Topology._error_message.<locals>.<genexpr>  s     Xf6<<FLL 1Xs   ..)rp   r   r/   r  r  Shardedr"  r'   rw   rx   r   formatrl   ro   rR  allr  intersectionry   r  r6  )r   r   is_replica_setserver_plural	addressesr   samerR  s          @r@   r   zTopology._error_message  s   
 **88//--=
 

 1M,,0E0EE&M%M**33!<7-GG]O+<XJaHHT..BBDEI4,,@@BIIKLG!FMM%77 
 -}<< AJ$$EG712;GGD=,}<<!#i.*E*EdFZFZ*[FHQR
 5z!xxXXXXrT   c                   g }	 | j                   r6|j                  | j                   j                                | j                   r6t	        j
                  |D cg c]  }|j                          c}ddi y # t        $ r Y =w xY wc c}w )Nreturn_exceptionsT)r   r   rv  
IndexErrorasynciogatherr6  )r   tasksts      r@   r   zTopology.cleanup_monitors  su    	%%T004467 %% 	51a1JTJ  		1s   AA8 B8	BBc                t    d}| j                   sd}d| j                  j                   d| | j                  dS )N zCLOSED < >)rz   	__class____name__rp   )r   msgs     r@   __repr__zTopology.__repr__!  s>    ||C4>>**+1SE$2C2C1FaHHrT   c                    | j                   }t        t        |j                              |j                  |j
                  |j                  fS )z?The properties to use for MongoClient/Topology equality checks.)rl   tuplesortedrt   ro   r   srv_service_name)r   tss     r@   eq_propszTopology.eq_props'  s8    ^^fRXX&')<)<bggrGZGZ[[rT   c                |    t        || j                        r!| j                         |j                         k(  S t        S rQ   )rT  r  r  NotImplemented)r   others     r@   __eq__zTopology.__eq__,  s.    eT^^,==?enn&666rT   c                4    t        | j                               S rQ   )hashr  r  s    r@   __hash__zTopology.__hash__1  s    DMMO$$rT   )r   r4   )rY   None)rY   float)NNN)r    Callable[[Selection], Selection]r   r  r   Optional[float]r   Optional[_Address]r   Optional[int]rY   list[Server])r   r  r   r  r   r  r   r  r   r  rY   list[ServerDescription])NNNN)r   r  r   r  r   r  r   r  r   Optional[list[Server]]r   r  rY   r-   )NN)
r   r6   r   r  r   r  r   r  rY   r-   )FF)r   r"   r   rZ   r   rZ   rY   r  )r   zlist[tuple[str, Any]]rY   r  )r   r6   rY   zOptional[Server])r   r6   rY   rZ   )rY   r  )r   r  rY   set[_Address])rY   r  )rY   zOptional[ClusterTime])r  Optional[Mapping[str, Any]]rY   r  )   )r  r   rY   r  )rY   r  )rY   r0   )rY   zlist[_ServerSession])r>  r  rY   r(   )rA  r(   rY   r  )rY   r#   )r   r6   rW  r)  rY   rZ   )r   r6   rW  r)  rY   r  )r   r6   rY   r,   )r   r  rY   r  )rY   r  )rY   z>tuple[tuple[_Address, ...], Optional[str], Optional[str], str])r  objectrY   rZ   )rY   r   )1r  
__module____qualname____doc__r   r   r   r   r   r   r   r   r   r   r   r  r   r   r	  r  r  r  r  r  r  r   r$  r.  r   propertyr   r;  r=  r@  r  r   rZ  rh  r*  r   r   rs  rr  r   r   r  r  r  r   rT   r@   rC   rC   h   s   4j4X%"N 59&*&*'2' ' #2	'
 $' $' 
'RJ#2J# J# 	J#
 $J# $J# 
!J#` 59&*8<&*2  #2	
 $  6 $ 
2 59&*8<&* 2    #2	 
 $   6  $  
 L 37&*

 
 #0	

 $
 

H !&+	I%-I% I%  $	I%
 
I%\ !&+	\-\ \  $	\
 
\(83*(NPHF&6=32"A<F ! !,NAFBB(B+H1#
*+X


,8YtKI\

%rT   rC   c                  ,    e Zd ZdZ	 	 	 	 	 	 	 	 	 	 ddZy)r)  z.An error with context for SDAM error handling.c                J    || _         || _        || _        || _        || _        y rQ   )rR  rb  rO  r_  rP  )r   rR  rb  rO  r_  rP  s         r@   r   z_ErrorContext.__init__8  s*     
 0.#6 $rT   N)
rR  BaseExceptionrb  r   rO  r   r_  rZ   rP  zOptional[ObjectId])r  r  r  r  r   r  rT   r@   r)  r)  5  s:    8%% % 	%
 "% '%rT   r)  c                :    | |y| d   |d   k7  ry| d   |d   k\  S )z9Return True if the error's topologyVersion is <= current.F	processIdcounterr  )
current_tvrY  s     r@   rV  rV  G  s<     X-+(;"77i HY$777rT   c                j    | j                   |j                   }}||y|d   |d   k7  ry|d   |d   kD  S )z4Return True if the new topologyVersion is < current.Fr  r  )rQ  )
current_sdnew_sdr  new_tvs       r@   r   r   R  sN    #44f6M6MJV^+&"55i 6)#444rT   c                H    |s| S | D cg c]	  }||vs| }}|xs | S c c}w )zBFilter out deprioritized servers from a list of server candidates.r  )
candidatesr   r   filtereds       r@   r   r   \  s;     !%/W66AV3VWHW !z! Xs   	)r;   z"weakref.ReferenceType[queue.Queue]rY   rZ   )r  r  rY  r  rY   rZ   )r  r"   r  r"   rY   rZ   rQ   )r  r  r   r  rY   r  )\r  
__future__r   r  rg   r   r9   r   r   r   r   r   pathlibr   typingr   r   r   r   r	   r
   pymongor   r   r   r   pymongo.errorsr   r   r   r   r   r   r   r   r   pymongo.hellor   pymongo.lockr   r   r   pymongo.loggerr   r   r   r   r    pymongo.pool_optionsr!   pymongo.server_descriptionr"   pymongo.server_selectorsr#   r$   r%   r&   r'   "pymongo.synchronous.client_sessionr(   r)   pymongo.synchronous.monitorr*   r+   pymongo.synchronous.poolr,   pymongo.synchronous.serverr-   pymongo.topology_descriptionr.   r/   r0   r1   r2   bsonr3   pymongo.synchronous.settingsr4   pymongo.typingsr5   r6   r}   r  __file__parentr   rA   rC   r)  rV  r   r   r  rT   r@   <module>r     s   C "   	   
     H H D D
 
 
   
  - 8  R ? ) -  =54>(()"J% J%Z% %$8+87R8	85 OS
"
"5K
"
"rT   