o
    C©Ìh$±  ã                   @  s  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ZQeReeSƒjTƒZUd1dd„ZVG dd„ dƒZWG dd „ d ƒZXd2d$d%„ZYd3d)d*„ZZ	d4d5d/d0„Z[dS )6z<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Ú_AddressTÚ	queue_refú"weakref.ReferenceType[queue.Queue]ÚreturnÚboolc                 C  sF   | ƒ }|sdS 	 z|  ¡ }W n tjy   Y dS w |\}}||Ž  q)NFT)Ú
get_nowaitÚqueueÚEmpty)r6   ÚqÚeventÚfnÚargs© rA   úk/var/www/html/Moveonwheels/move_on_wheels/venv/lib/python3.10/site-packages/pymongo/synchronous/topology.pyÚprocess_events_queueW   s   úùrC   c                   @  sü  e Zd ZdZd�dd„ZdŽdd	„Zd�dd„Z			d�d‘dd„Zd’dd„Z				d“d”d"d#„Z					d“d”d$d%„Z
		d•d–d'd(„Z	)	)d—d˜d/d0„Z	)	)d—d˜d1d2„Zd™d5d6„Zd™d7d8„Zdšd:d;„Zd›d<d=„Zdœd>d?„Zd�dAdB„ZdždCdD„ZdždEdF„ZdŸdHdI„Zd dLdM„Zd dNdO„Zd¡d¢dSdT„Zd£dUdV„ZdŽdWdX„ZdŽdYdZ„Zed¤d\d]„ƒZd¥d_d`„Zd¦dcdd„Z d§dfdg„Z!d¨didj„Z"dŽdkdl„Z#d©dodp„Z$dªdqdr„Z%dªdsdt„Z&dŽdudv„Z'dŽdwdx„Z(d«dzd{„Z)d«d|d}„Z*d¬d~d„Z+dŽd€d�„Z,d­d‚dƒ„Z-d®d…d†„Z.d¯d‰dŠ„Z/d°d‹dŒ„Z0dS )±ÚTopologyz*Monitor a topology of one or more servers.Útopology_settingsr3   c                   s˜  |j | _ |jj| _| jd uo| jj| _| jd uo| jj| _d | _d | _	| js)| jr0t
jdd�| _t tj¡r?tttj| j d� | jrU| jd usIJ ‚| j | jj| j ff¡ || _t| ¡ | ¡ |jd d |ƒ}|| _ttji d d d | jƒ}| jr�| jd us~J ‚| j | jj|| j| j ff¡ t tj¡r£tttj| j t|ƒt| jƒd� |j D ].}| jr¿| jd us²J ‚| j | jj!|| j ff¡ t tj¡rÔtttj"| j |d |d d� q¦t#| $¡ ƒ| _%d| _&d| _'t(ƒ | _)t*| j)t+rï| jj,nd ƒ| _-i | _.d | _/d | _0t1ƒ | _2| j�s| j�r1| jd u�sJ ‚d‡ fdd„}t3j4t5j6t5j7|dd�}t8 9| j|j:¡‰ || _	| ;¡  d | _<| jj=d u�rG| jj>�sGt?| | jƒ| _<g | _@d S )Néd   )Úmaxsize©ÚmessageÚ
topologyId©rI   rJ   ÚpreviousDescriptionÚnewDescriptionr   é   )rI   rJ   Ú
serverHostÚ
serverPortFr8   r9   c                     s   t ˆ ƒS ©N)rC   rA   ©ÚweakrA   rB   Útarget¿   s   z!Topology.__init__.<locals>.targetÚpymongo_events_thread)ÚintervalÚmin_intervalrT   Úname)r8   r9   )AÚ_topology_idÚ_pool_optionsÚ_event_listenersÚ
_listenersÚenabled_for_serverÚ_publish_serverÚenabled_for_topologyÚ_publish_tpÚ_eventsÚ_Topology__events_executorr;   ÚQueuer   ÚisEnabledForÚloggingÚDEBUGr   r   ÚSTART_TOPOLOGYÚputÚpublish_topology_openedÚ	_settingsr/   Úget_topology_typeÚget_server_descriptionsÚreplica_set_nameÚ_descriptionr.   ÚUnknownÚ$publish_topology_description_changedÚTOPOLOGY_CHANGEÚreprÚ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)ÚselfrE   Útopology_descriptionÚ
initial_tdÚseedrT   ÚexecutorrA   rR   rB   Ú__init__k   sª   
ýú	ÿþÿû
û€	ÿü

zTopology.__init__r8   ÚNonec                 C  sÞ   t  ¡ }| jdu r|| _nH|| jkrU|| _tjdd… dkr$dtfi}nddi}tj	di |¤Ž | j� | j	 
¡ D ]}| ¡  q:| j ¡  W d  ƒ n1 sPw   Y  | j� |  ¡  W d  ƒ dS 1 shw   Y  dS )	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é   ú³MongoClient 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)r›   )ÚosÚgetpidr€   ÚsysÚversion_infoÚ_pymongo_dirÚwarningsÚwarnr{   r   Úvaluesrˆ   r‚   ÚresetÚ_ensure_opened)rŽ   ÚpidÚkwargsÚserverrA   rA   rB   r‰   ×   s*   

ÿü
ú
"ÿzTopology.openÚfloatc                 C  s   t  ¡ }|d u r| jjS |S rQ   )r
   Ú	remainingrj   Úserver_selection_timeout)rŽ   ÚtimeoutrA   rA   rB   Úget_server_selection_timeoutþ   s   z%Topology.get_server_selection_timeoutNÚselectorú Callable[[Selection], Selection]Ú	operationÚstrr«   úOptional[float]ÚaddressúOptional[_Address]Úoperation_idúOptional[int]úlist[Server]c                   sv   |du r	ˆ   ¡ }n|}tsˆ jrˆ  ¡  ˆ j� ˆ  |||||¡}‡ fdd„|D ƒW  d  ƒ S 1 s4w   Y  dS )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.
        Nc                   s   g | ]}t tˆ  |j¡ƒ‘qS rA   )r	   r,   Úget_server_by_addressr³   ©Ú.0Úsd©rŽ   rA   rB   Ú
<listcomp>*  s    ÿz+Topology.select_servers.<locals>.<listcomp>)r­   r|   r�   Úcleanup_monitorsr{   Ú_select_servers_loop)rŽ   r®   r°   r«   r³   rµ   Úserver_timeoutrw   rA   r¼   rB   Úselect_servers  s   


ÿ
ÿ$ûzTopology.select_serversr¬   úlist[ServerDescription]c           
      C  sP  t  ¡ }|| }d}t tj¡r tttj|||| j	| j	j
jd� | jj||| jjd�}	|	s¡|dks5||kr_t tj¡rOtttj|||| j	| j	j
j|  |¡d� t|  |¡› d|› d| j	›�ƒ‚|s|tttj|||| j	| j	j
jtd|t  ¡   ƒd	� d
}|  ¡  |  ¡  t| jtjƒ | j ¡  t  ¡ }| jj||| jjd�}	|	r-| j ¡  |	S )z7select_servers() guts. Hold the lock when calling this.F)rI   r®   r°   ÚoperationIdÚtopologyDescriptionÚclientId)Úcustom_selectorr   )rI   r®   r°   rÃ   rÄ   rÅ   Úfailurez, Timeout: zs, Topology Description: iè  )rI   r®   r°   rÃ   rÄ   rÅ   ÚremainingTimeMST)ÚtimeÚ	monotonicr   rd   re   rf   r   r   ÚSTARTEDÚdescriptionÚ_topology_settingsrY   rn   Úapply_selectorrj   Ú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_waitingrw   rA   rA   rB   r¿   .  sn   	ù

ÿø
ÿø


ÿ×
-zTopology._select_servers_loopÚdeprioritized_serversúOptional[list[Server]]r,   c           
      C  sX   |   |||||¡}t||ƒ}t|ƒdkr|d S t |d¡\}}	|jj|	jjkr*|S |	S )NrN   r   r•   )rÁ   Ú_filter_serversÚlenÚrandomÚsampleÚpoolÚoperation_count)
rŽ   r®   r°   r«   r³   rÙ   rµ   ÚserversÚserver1Úserver2rA   rA   rB   Ú_select_serverz  s   	
ÿ
zTopology._select_serverc                 C  sp   | j ||||||d�}t ¡ rt |jj¡ t tj	¡r6t
ttj|||| j| jjj|jjd |jjd d�	 |S )zALike select_servers, but choose a random server if several match.©rµ   r   rN   )rI   r®   r°   rÃ   rÄ   rÅ   rO   rP   )rä   r
   Úget_timeoutÚset_rttrÌ   Úmin_round_trip_timer   rd   re   rf   r   r   Ú	SUCCEEDEDrÍ   rY   r³   )rŽ   r®   r°   r«   r³   rÙ   rµ   r¨   rA   rA   rB   Úselect_server�  s.   
ú

÷zTopology.select_serverr5   c                 C  s   | j t||||d�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µ   rA   rA   rB   Úselect_server_by_address±  s   ûz!Topology.select_server_by_addressFÚserver_descriptionr!   Ú
reset_poolr9   Úinterrupt_connectionsc           	      C  s\  | j }|j|j }t||ƒrdS t| j |ƒ}|js"|jr0|jtj	kr0| j
 |j¡}|r0|j ¡  ||k}| jrP|sP| jdus@J ‚| j | jj|||j| jff¡ || _ |  ¡  | jrr|sr| jduscJ ‚| j | jj|| j | jff¡ t tj¡rŠ|sŠtttj| jt|ƒt| j ƒd� | jr§|jtj kr§| j jt!vr§| j "¡  t#s§| j$ %| j¡ | j& '¡  dS )ziProcess a new ServerDescription on an opened topology.

        Hold the lock when calling this.
        NrK   )(rn   Ú_server_descriptionsr³   Ú_is_stale_server_descriptionr1   Úis_readableÚis_server_type_knownÚtopology_typer.   ÚSingler   Úgetrß   Úreadyr^   ra   rh   r\   Ú"publish_server_description_changedrY   Ú_update_serversr`   rp   r   rd   re   rf   r   r   rq   rr   rŠ   ro   r-   rˆ   r|   r�   Úappendr~   Ú
notify_all)	rŽ   rì   rí   rî   Útd_oldÚsd_oldÚnew_tdr¨   Úsuppress_eventrA   rA   rB   Ú_process_changeÒ  sX   

ÿ

þÿ
þÿû
zTopology._process_changec                 C  sx   | j � | jr| j |j¡r|  |||¡ W d  ƒ n1 sw   Y  |r8| j |j¡}|r:|jj	|d� dS dS dS )z>Process a new ServerDescription after an hello call completes.N)rî   )
r{   ry   rn   Ú
has_serverr³   rÿ   r   rõ   rß   r¤   )rŽ   rì   rí   rî   r¨   rA   rA   rB   Ú	on_change  s   	€öýzTopology.on_changeÚseedlistúlist[tuple[str, Any]]c                 C  s�   | j }|jtvr
dS t| j |ƒ| _ |  ¡  | jr.| jdusJ ‚| j | jj	|| j | j
ff¡ t tj¡rFtttj| j
t|ƒt| j ƒd� dS dS )z_Process a new seedlist on an opened topology.
        Hold the lock when calling this.
        NrK   )rn   ró   r-   r0   rø   r`   ra   rh   r\   rp   rY   r   rd   re   rf   r   r   rq   rr   )rŽ   r  rû   rA   rA   rB   Ú_process_srv_update0  s*   
þÿ
ûÿzTopology._process_srv_updatec                 C  sL   | j � | jr|  |¡ W d  ƒ dS W d  ƒ dS 1 sw   Y  dS )z?Process a new list of nodes obtained from scanning SRV records.N)r{   ry   r  )rŽ   r  rA   rA   rB   Úon_srv_updateL  s   þ"ÿzTopology.on_srv_updateúOptional[Server]c                 C  ó   | 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³   rA   rA   rB   r¸   S  s   zTopology.get_server_by_addressc                 C  s
   || j v S rQ   )r   r  rA   rA   rB   r   ]  s   
zTopology.has_serverc                 C  s`   | j �# | jj}|tjkr	 W d  ƒ dS t|  ¡ ƒd jW  d  ƒ S 1 s)w   Y  dS )z!Return primary's address or None.Nr   )r{   rn   ró   r.   ÚReplicaSetWithPrimaryr&   Ú_new_selectionr³   )rŽ   ró   rA   rA   rB   Úget_primary`  s   
ý$ûzTopology.get_primaryúset[_Address]c                 C  sp   | j �+ | jj}|tjtjfvrtƒ W  d  ƒ S dd„ t||  ¡ ƒƒD ƒW  d  ƒ S 1 s1w   Y  dS )z+Return set of replica set member addresses.Nc                 S  s   h | ]}|j ’qS rA   )r³   r¹   rA   rA   rB   Ú	<setcomp>u  s    z4Topology._get_replica_set_members.<locals>.<setcomp>)	r{   rn   ró   r.   r	  ÚReplicaSetNoPrimaryÚsetÚiterr
  )rŽ   r®   ró   rA   rA   rB   Ú_get_replica_set_membersj  s   þú$øz!Topology._get_replica_set_membersc                 C  ó
   |   t¡S )z"Return set of secondary addresses.)r  r%   r¼   rA   rA   rB   Úget_secondariesw  ó   
zTopology.get_secondariesc                 C  r  )z Return set of arbiter addresses.)r  r$   r¼   rA   rA   rB   Úget_arbiters{  r  zTopology.get_arbitersúOptional[ClusterTime]c                 C  ó   | j S )z1Return a document, the highest seen $clusterTime.©r�   r¼   rA   rA   rB   Úmax_cluster_time  ó   zTopology.max_cluster_timeÚcluster_timeúOptional[Mapping[str, Any]]c                 C  s.   |r| j r|d | j d kr|| _ d S d S d S )NÚclusterTimer  ©rŽ   r  rA   rA   rB   Ú_receive_cluster_time_no_lockƒ  s   ÿ
úz&Topology._receive_cluster_time_no_lockc                 C  s6   | j � |  |¡ W d   ƒ d S 1 sw   Y  d S rQ   )r{   r  r  rA   rA   rB   Úreceive_cluster_time’  s   "ÿzTopology.receive_cluster_timeé   Ú	wait_timerÓ   c                 C  s@   | j � |  ¡  t| j|ƒ W d  ƒ dS 1 sw   Y  dS )z=Wake all monitors, wait for at least one to check its server.N)r{   rÔ   r   r~   )rŽ   r"  rA   rA   rB   Úrequest_check_all–  s   "þzTopology.request_check_allc                 C  s   | 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.
        )rn   ró   r.   rô   Úknown_serversÚreadable_serversr¼   rA   rA   rB   Údata_bearing_serversœ  s   zTopology.data_bearing_serversc                 C  s¶   g }| j �  |  ¡ D ]}| j|j }| ||jj ¡ f¡ q
W d   ƒ n1 s(w   Y  |D ])\}}z|j |¡ W q/ t	yX } zt
|d|dd ƒ}|  |jj|¡ ‚ d }~ww d S )Nr   F)r{   r&  r   r³   rù   rß   ÚgenÚget_overallÚremove_stale_socketsr   Ú_ErrorContextÚhandle_errorrÌ   )rŽ   rá   r»   r¨   Ú
generationÚexcÚctxrA   rA   rB   Úupdate_pool¥  s"   þþ€ýýzTopology.update_poolc                 C  s¦  | j �T | j}| j ¡ D ]}| ¡  ts| j |j¡ q| j 	¡ | _| j 
¡  ¡ D ]\}}|| jv r8|| j| _q)| jrJ| j ¡  tsJ| j | j¡ d| _d| _W d  ƒ n1 sZw   Y  | jr—| jdusiJ ‚ttji | jj| jj| jj| jjƒ| _| j | jj|| j| jff¡ | j | jj| jff¡ t t j!¡r¶t"tt#j$| jt%|ƒt%| jƒd� t"tt#j&| jd� | j's¼| jrÑ| j( ¡  | j( )d¡ t*t+ ,| j¡ƒ dS dS )z¤Clear pools and terminate monitors. Topology does not reopen on
        demand. Any further operations will raise
        :exc:`~.errors.InvalidOperation`.
        FTNrK   rH   rN   )-r{   rn   r   r£   rˆ   r|   r�   rù   Ú_monitorr¤   rw   ÚitemsrÌ   rŠ   ry   rz   r`   ra   r/   r.   ro   rm   Úmax_set_versionÚmax_election_idrÍ   rh   r\   rp   rY   Úpublish_topology_closedr   rd   re   rf   r   r   rq   rr   ÚSTOP_TOPOLOGYr^   rb   ÚjoinrC   r†   r‡   )rŽ   Úold_tdr¨   r³   r»   rA   rA   rB   rˆ   ¶  sl   €
€
ìúýþÿ
û
ÿ
üzTopology.closer/   c                 C  r  rQ   )rn   r¼   rA   rA   rB   rÌ   ù  r  zTopology.descriptionúlist[_ServerSession]c                 C  s
   | j  ¡ S )z"Pop all session ids from the pool.)r‚   Úpop_allr¼   rA   rA   rB   Úpop_all_sessionsý  r  zTopology.pop_all_sessionsÚsession_timeout_minutesr'   c                 C  r  )z>Start or resume a server session, or raise ConfigurationError.)r‚   Úget_server_session)rŽ   r;  rA   rA   rB   r<    s   zTopology.get_server_sessionÚserver_sessionc                 C  s   | j  |¡ d S rQ   )r‚   Úreturn_server_session)rŽ   r=  rA   rA   rB   r>    s   zTopology.return_server_sessionr"   c                 C  s   t  | j¡S )zmA Selection object, initially including all known servers.

        Hold the lock when calling this.
        )r"   Úfrom_topology_descriptionrn   r¼   rA   rA   rB   r
    s   zTopology._new_selectionc              	   C  sœ   | j rtdƒ‚| js@d| _|  ¡  | js| jr| j ¡  | jr*| j	j
tv r*| j ¡  | jjr@|  t| jd td| jddœƒƒ¡ | j ¡ D ]}| ¡  qEdS )z[Start monitors, or restart after a fork.

        Hold the lock when calling this.
        z"Cannot use MongoClient after closeTr   rN   é   )ÚokÚ	serviceIdÚmaxWireVersionN)rz   r   ry   rø   r`   r^   rb   r‰   rŠ   rÌ   ró   r-   rj   rŒ   rÿ   r!   rx   r   rY   r   r£   ©rŽ   r¨   rA   rA   rB   r¥     s&   

þÿ
ÿzTopology._ensure_openedÚerr_ctxr*  c                 C  sp   | j  |¡}|d u rdS |j |j|j¡rdS |jj}|j}d }|r3t	|dƒr3t
|jtƒr3|j d¡}t||ƒS )NTÚdetailsÚtopologyVersion)r   rõ   Ú_poolÚstale_generationÚsock_generationÚ
service_idrÌ   Útopology_versionÚerrorÚhasattrÚ
isinstancerF  ÚdictÚ _is_stale_error_topology_version)rŽ   r³   rE  r¨   Úcur_tvrM  Úerror_tvrA   rA   rB   Ú_is_stale_error0  s   
zTopology._is_stale_errorc           	      C  sp  |   ||¡rd S | j| }|j}|j}| jjr|s|jsd S t|tƒr(|jr(d S t|t	ƒr/d S t|t
tfƒr‘t|dƒr?|j}nt|t
ƒrFdnd }|j d|¡}|tjv rx|tjv }| jjsf|  t||d�¡ |sm|jdkrr| |¡ | ¡  d S |js�| jjsˆ|  t||d�¡ | |¡ d S d S t|tƒr¶t|tƒr�d S | jjsª|  t||d�¡ | |¡ |j ¡  d S d S )NÚcodei{'  ©rM  é   )rT  r   rM  rK  rj   rŒ   Úcompleted_handshakerO  r   r   r   r   rN  rU  rF  rõ   r   Ú_NOT_PRIMARY_CODESÚ_SHUTDOWN_CODESrÿ   r!   Úmax_wire_versionr¤   Úrequest_checkr   r   r0  Úcancel_check)	rŽ   r³   rE  r¨   rM  rK  Úerr_codeÚdefaultÚis_shutting_downrA   rA   rB   Ú_handle_errorD  sH   


	


û


ôzTopology._handle_errorc                 C  s8   | j � |  ||¡ W d  ƒ dS 1 sw   Y  dS )z®Handle 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{   ra  )rŽ   r³   rE  rA   rA   rB   r+  ˆ  s   "ÿzTopology.handle_errorc                 C  s   | j  ¡ D ]}| ¡  qdS )z3Wake all monitors. Hold the lock when calling this.N)r   r£   r\  rD  rA   rA   rB   rÔ   ‘  s   
ÿzTopology._request_check_allc              	   C  s  | j  ¡  ¡ D ]\\}}|| jvrG| jj|| |  |¡| jd�}d}| jr.| jdur.t	 
| j¡}t||  |¡|| j| j|d�}|| j|< | ¡  q| j| jj}|| j| _||jkrc| j| j |j¡ qt| j ¡ ƒD ]\}}| j  |¡sˆ| ¡  ts‚| j |j¡ | j |¡ qkdS )zrSync our Servers from TopologyDescription.server_descriptions.

        Hold the lock while calling this.
        )rì   Útopologyrß   rE   N)rì   rß   ÚmonitorÚtopology_idÚ	listenersÚevents)rn   rw   r1  r   rj   Úmonitor_classÚ_create_pool_for_monitorr^   ra   r†   r‡   r,   Ú_create_pool_for_serverrY   r\   r‰   rÌ   Úis_writablerß   Úupdate_is_writablerv   r   rˆ   r|   r�   rù   r0  Úpop)rŽ   r³   r»   rc  rS   r¨   Úwas_writablerA   rA   rB   rø   –  sD   
üú
	

€€ûzTopology._update_serversr+   c                 C  s   | j j|| j j| jd�S )N)Ú	client_id)rj   Ú
pool_classÚpool_optionsrY   r  rA   rA   rB   ri  Â  s   ÿz Topology._create_pool_for_serverc                 C  sH   | j j}t|j|j|j|j|j|j|jd|j	d�	}| j j
||d| jd�S )NF)	Úconnect_timeoutÚsocket_timeoutÚssl_contextÚtls_allow_invalid_hostnamesÚevent_listenersÚappnameÚdriverÚpause_enabledÚ
server_apiT)Úis_sdamrn  )rj   rp  r    rq  Ú_ssl_contextrt  r[   rv  rw  ry  ro  rY   )rŽ   r³   ÚoptionsÚmonitor_pool_optionsrA   rA   rB   rh  Ç  s   ÷
ÿz!Topology._create_pool_for_monitorc                   s  | j jtjtjfv }|rd}n| j jtjkrd}nd}| j jr4|tu r+|r'dS d| S d|› d|› d�S t| j  	¡ ƒ}t| j  	¡  
¡ ƒ}|sT|rPd	 || jj¡S d
| S |d j‰ t‡ fdd„|dd… D ƒƒ}|r„ˆ du rrd| S |r€t|ƒ | j¡s€d| S tˆ ƒS d d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  s   � | ]}|j ˆ kV  qd S rQ   rV  ©rº   r¨   rV  rA   rB   Ú	<genexpr>  s   € z*Topology._error_message.<locals>.<genexpr>rN   NzNo %s found yetz\Could not reach any servers in %s. Replica set is configured with internal hostnames or IPs?ú,c                 s  s    � | ]}|j rt|j ƒV  qd S rQ   )rM  r±   r€  rA   rA   rB   r�    s   € )rn   ró   r.   r	  r  ÚShardedr$  r&   rv   rw   r£   Úformatrj   rm   rM  Úallr  Úintersectionrx   r±   r6  )rŽ   r®   Úis_replica_setÚserver_pluralÚ	addressesrá   ÚsamerA   rV  rB   rÑ   Ý  sH   þþ
ÿÿzTopology._error_messagec                 C  sV   g }z| j r| | j  ¡ ¡ | j sW n	 ty   Y nw tjdd„ |D ƒddiŽ d S )Nc                 S  s   g | ]}|  ¡ ‘qS rA   )r6  )rº   ÚtrA   rA   rB   r½     s    z-Topology.cleanup_monitors.<locals>.<listcomp>Úreturn_exceptionsT)r�   rù   rl  Ú
IndexErrorÚasyncioÚgather)rŽ   ÚtasksrA   rA   rB   r¾     s   ÿ€ÿzTopology.cleanup_monitorsc                 C  s*   d}| j sd}d| jj› d|› | j›d�S )NÚ zCLOSED ú<ú ú>)ry   Ú	__class__Ú__name__rn   )rŽ   ÚmsgrA   rA   rB   Ú__repr__   s   zTopology.__repr__ú>tuple[tuple[_Address, ...], Optional[str], Optional[str], str]c                 C  s"   | j }tt|jƒƒ|j|j|jfS )z?The properties to use for MongoClient/Topology equality checks.)rj   ÚtupleÚsortedrs   rm   r‹   Úsrv_service_name)rŽ   ÚtsrA   rA   rB   Úeq_props&  s   zTopology.eq_propsÚotherÚobjectc                 C  s    t || jƒr|  ¡ | ¡ kS tS rQ   )rO  r•  rž  ÚNotImplemented)rŽ   rŸ  rA   rA   rB   Ú__eq__+  s   zTopology.__eq__c                 C  s   t |  ¡ ƒS rQ   )Úhashrž  r¼   rA   rA   rB   Ú__hash__0  s   zTopology.__hash__)rE   r3   )r8   r”   )r8   r©   )NNN)r®   r¯   r°   r±   r«   r²   r³   r´   rµ   r¶   r8   r·   )r®   r¯   r¬   r©   r°   r±   rµ   r¶   r³   r´   r8   rÂ   )NNNN)r®   r¯   r°   r±   r«   r²   r³   r´   rÙ   rÚ   rµ   r¶   r8   r,   )NN)
r³   r5   r°   r±   r«   r¶   rµ   r¶   r8   r,   )FF)rì   r!   rí   r9   rî   r9   r8   r”   )r  r  r8   r”   )r³   r5   r8   r  )r³   r5   r8   r9   )r8   r´   )r®   r¯   r8   r  )r8   r  )r8   r  )r  r  r8   r”   )r!  )r"  rÓ   r8   r”   )r8   rÂ   )r8   r/   )r8   r8  )r;  r¶   r8   r'   )r=  r'   r8   r”   )r8   r"   )r³   r5   rE  r*  r8   r9   )r³   r5   rE  r*  r8   r”   )r³   r5   r8   r+   )r®   r¯   r8   r±   )r8   r±   )r8   r™  )rŸ  r   r8   r9   )r8   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¥   rT  ra  r+  rÔ   rø   ri  rh  rÑ   r¾   r˜  rž  r¢  r¤  rA   rA   rA   rB   rD   h   s€    

l
'ú
)Pùù&û$üHü














	
C





!

D
	

,


:
	

rD   c                   @  s   e Zd ZdZddd„ZdS )r*  z.An error with context for SDAM error handling.rM  ÚBaseExceptionr[  rÓ   rJ  rX  r9   rK  úOptional[ObjectId]c                 C  s"   || _ || _|| _|| _|| _d S rQ   )rM  r[  rJ  rX  rK  )rŽ   rM  r[  rJ  rX  rK  rA   rA   rB   r“   7  s
   
z_ErrorContext.__init__N)
rM  r©  r[  rÓ   rJ  rÓ   rX  r9   rK  rª  )r–  r¥  r¦  r§  r“   rA   rA   rA   rB   r*  4  s    r*  Ú
current_tvr  rS  c                 C  s8   | du s|du r
dS | d |d krdS | d |d kS )z9Return True if the error's topologyVersion is <= current.NFÚ	processIdÚcounterrA   )r«  rS  rA   rA   rB   rQ  F  s
   rQ  Ú
current_sdr!   Únew_sdc                 C  sF   | j |j }}|du s|du rdS |d |d krdS |d |d kS )z4Return True if the new topologyVersion is < current.NFr¬  r­  )rL  )r®  r¯  r«  Únew_tvrA   rA   rB   rð   Q  s   rð   Ú
candidatesr·   rÙ   rÚ   c                   s"   ˆ s| S ‡ fdd„| D ƒ}|p| S )zBFilter out deprioritized servers from a list of server candidates.c                   s   g | ]}|ˆ vr|‘qS rA   rA   r€  ©rÙ   rA   rB   r½   b  s    z#_filter_servers.<locals>.<listcomp>rA   )r±  rÙ   ÚfilteredrA   r²  rB   rÛ   [  s   rÛ   )r6   r7   r8   r9   )r«  r  rS  r  r8   r9   )r®  r!   r¯  r!   r8   r9   rQ   )r±  r·   rÙ   rÚ   r8   r·   )\r§  Ú
__future__r   rŽ  re   rœ   r;   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.   r/   r0   r1   Úbsonr2   Úpymongo.synchronous.settingsr3   Úpymongo.typingsr4   r5   r|   r±   Ú__file__Úparentr    rC   rD   r*  rQ  rð   rÛ   rA   rA   rA   rB   Ú<module>   s\    ,
       S

ÿ