
    FCfD                       d Z ddlmZ ddlZddlZddlZddlmZmZm	Z	m
Z
mZ ddlmZmZ ddlmZ ddlmZmZmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddl m!Z! ddl"m#Z# erddlm$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z* ddZ+ G d d      Z, G d de,      Z- G d de,      Z. G d de,      Z/ e0       Z1d dZ2d!dZ3d"dZ4d"dZ5 ejl                  e5       y)#z9Class to monitor a MongoDB server on a background thread.    )annotationsN)TYPE_CHECKINGAnyMappingOptionalcast)commonperiodic_executor)MovingMinimum)NetworkTimeoutNotPrimaryErrorOperationFailure_OperationCancelled)Hello)_create_lock)_shutdown_executors)_is_faas)MovingAverage)ServerDescription)_SrvResolver)
ConnectionPool_CancellationContext)TopologySettings)Topologyc                .    d| _         d| _        d| _        y)z'PYTHON-2433 Clear error traceback info.N)__traceback____context__	__cause__errors    O/var/www/highfloat_scraper/venv/lib/python3.12/site-packages/pymongo/monitor.py	_sanitizer#   )   s    EEEO    c                  >    e Zd ZddZd	dZd	dZd	dZd
ddZd	dZy)MonitorBasec                    dfd}t        j                  ||||      }|| _        ddfd}t        j                  | |j
                        t        j                  ||      | _        t        |        y)zBase class to do periodic work on a background thread.

        The background thread is signaled to stop when the Topology or
        this instance is freed.
        c                 :            } | y| j                          y)NFT)_run)monitorself_refs    r"   targetz$MonitorBase.__init__.<locals>.target:   s    jGLLNr$   )intervalmin_intervalr,   nameNc                :            }|r|j                          y y Ngc_safe_close)dummyr*   r+   s     r"   _on_topology_gcz-MonitorBase.__init__.<locals>._on_topology_gcG   s      jG%%' r$   )returnboolr1   )r4   zOptional[Topology]r6   None)	r
   PeriodicExecutor	_executorweakrefrefcloseproxy	_topology	_register)	selftopologyr/   r-   r.   r,   executorr5   r+   s	           @r"   __init__zMonitorBase.__init__1   s`    	 %55Ld
 "	( ;;tX^^4 xA$r$   c                8    | j                   j                          y)z[Start monitoring, or restart after a fork.

        Multiple calls have no effect.
        N)r:   openrA   s    r"   rF   zMonitorBase.openS   s    
 	r$   c                8    | j                   j                          y)zGC safe close.N)r:   r=   rG   s    r"   r3   zMonitorBase.gc_safe_closeZ   s    r$   c                $    | j                          y)zWClose and stop monitoring.

        open() restarts the monitor after closing.
        Nr2   rG   s    r"   r=   zMonitorBase.close^   s    
 	r$   Nc                :    | j                   j                  |       y)zWait for the monitor to stop.N)r:   join)rA   timeouts     r"   rK   zMonitorBase.joine   s    G$r$   c                8    | j                   j                          y)z)If the monitor is sleeping, wake it soon.N)r:   wakerG   s    r"   request_checkzMonitorBase.request_checki   s    r$   )rB   r   r/   strr-   intr.   floatr6   r8   r1   )rL   zOptional[int]r6   r8   )	__name__
__module____qualname__rD   rF   r3   r=   rK   rO    r$   r"   r&   r&   0   s!     D%r$   r&   c                  x     e Zd Z	 	 	 	 	 	 	 	 d f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dd
Z xZS )Monitorc                   t         |   |d|j                  t        j                         || _        || _        || _        | j                  j                  j                  | _
        | j                  duxr | j                  j                  | _        d| _        t        |||j                  |j                               | _        |j$                  dk(  rd| _        y|j$                  dk(  rd| _        yt)                | _        y)a   Class to monitor a MongoDB server on a background thread.

        Pass an initial ServerDescription, a Topology, a Pool, and
        TopologySettings.

        The Topology is weakly referenced. The Pool must be exclusive to this
        Monitor.
        pymongo_server_monitor_threadNstreamTpollF)superrD   heartbeat_frequencyr	   MIN_HEARTBEAT_INTERVAL_server_description_pool	_settings_pool_options_event_listeners
_listenersenabled_for_server_heartbeat_publish_cancel_context_RttMonitor_create_pool_for_monitoraddress_rtt_monitorserver_monitoring_mode_streamr   )rA   server_descriptionrB   pooltopology_settings	__class__s        r"   rD   zMonitor.__init__o   s     	+11))		
 $6 
*..66GGt3d8d8d?C'--.@.H.HI

 33x?DL55? DL'z>DLr$   c                B    | j                   }|r|j                          yy)zCancel any concurrent hello check.

        Note: this is called from a weakref.proxy callback and MUST NOT take
        any locks.
        N)ri   cancel)rA   contexts     r"   cancel_checkzMonitor.cancel_check   s#     && NN	 r$   c                    | j                   j                          | j                  j                  r| j                   j	                          yy)z1Start an _RttMonitor that periodically runs ping.N)rm   rF   r:   _stoppedr=   rG   s    r"   _start_rtt_monitorzMonitor._start_rtt_monitor   s:    
 	 >>""##% #r$   c                    | j                   j                          | j                  j                          | j	                          y r1   )r:   r=   rm   r3   rw   rG   s    r"   r3   zMonitor.gc_safe_close   s0    '')r$   c                x    | j                          | j                  j                          | j                          y r1   )r3   rm   r=   _reset_connectionrG   s    r"   r=   zMonitor.close   s.    ! 	 r$   c                8    | j                   j                          y r1   )rb   resetrG   s    r"   r}   zMonitor._reset_connection   s    

r$   c                ^   	 | j                   }	 | j                         | _         | j                  j                  | j                   | j                   j                  t        | j                   j                  t                     | j                  rV| j                   j                  r@| j                   j                  r*| j!                          | j                  j                          | j                   j                  r(|j                  r| j                  j                          y y y # t        $ ra}t        |       t	        | j                   j
                  |      | _         |j                  r| j                  j                          Y d }~y d }~ww xY w# t"        $ r | j%                          Y y w xY w)Nr    )
reset_poolinterrupt_connections)ra   _check_serverr   r#   r   rl   is_server_type_knownr:   
skip_sleepr?   	on_changer!   
isinstancer   ro   topology_versionrz   ReferenceErrorr=   )rA   prev_sdexcs      r"   r)   zMonitor._run   sS   $	..G+/+=+=+?( NN$$((3399&01I1I1O1OQ_&` %  ||((==,,=='')))+''--'2N2N))+ 3O-7 ' 
#+<,,44C,( // NN--/
<  	JJL	s;   F D# C<F #	F,AFF FF F,+F,c                4   t        j                         }	 	 | j                         S # t        t        f$ rW}t        t        t        t        f   |j                        }| j                  j                  |j                  d              d}~ww xY w# t        $ r  t        $ r}t        |       | j                   }|j"                  }t        j                         |z
  }| j$                  r]t'        | j(                  xr |j*                  xr |j,                        }| j.                  J | j.                  j1                  ||||       | j3                          t5        |t6              r | j8                  j;                          t=        ||      cY d}~S d}~ww xY w)z^Call hello or read the next streaming response.

        Returns a ServerDescription.
        z$clusterTimeNr    )time	monotonic_check_oncer   r   r   r   rP   r   detailsr?   receive_cluster_timegetr   	Exceptionr#   ra   rl   rh   r7   ro   r   r   rf   publish_server_heartbeat_failedr}   r   r   rm   r   r   )	rA   startr   r   r!   sdrl   durationawaiteds	            r"   r   zMonitor._check_server   sL   
  	;''))$o6 wsCx0#++>33GKK4OP	
  	 	;e))BjjG~~'%/H}}t||_0G0G_BL_L_`222??SXZab""$%!45##%$WE::	;s4   ' BABBB F"C*FFFc                   | j                   j                  }| j                  r| j                  J | j                   }t	        | j
                  j                  xr( | j                  xr |j                  xr |j                        }| j                  j                  ||       | j                  r&| j                  j                  r| j                          | j
                  j                         5 }|j                  | _        | j!                  |      \  }}|j"                  s| j$                  j'                  |       | j$                  j)                         \  }}t+        ||||      }| j                  r6| j                  J | j                  j-                  ||||j"                         |cddd       S # 1 sw Y   yxY w)zfA single attempt to call hello.

        Returns a ServerDescription, or raises an exception.
        N)min_round_trip_time)ra   rl   rh   rf   r7   rb   connsro   r   r    publish_server_heartbeat_startedri   	cancelledr}   checkoutcancel_context_check_with_socket	awaitablerm   
add_sampler   r   "publish_server_heartbeat_succeeded)	rA   rl   r   r   connresponseround_trip_timeavg_rttmin_rtts	            r"   r   zMonitor._check_once  s   
 **22==??...))B 

   (LL(++( ''	G OO<<WgND$8$8$B$B""$ZZ  " 	d#'#6#6D (,(?(?(E%Ho%%!!,,_=#00446GW"7HgSZ[B}}222BB_h8J8J 	 	 	s   .B<F44F=c                   | j                   j                         }t        j                         }|j                  rt        |j                         d      }n}| j                  r^|j                  rR| j                  j                  r<|j                  || j                  j                  | j                  j                        }n|j                  |dd      }|t        j                         |z
  fS )zcReturn (Hello, round_trip_time).

        Can raise ConnectionFailure or OperationFailure.
        T)r   N)r?   max_cluster_timer   r   more_to_comer   _next_replyro   performed_handshakera   r   _hellorc   r_   )rA   r   cluster_timer   r   s        r"   r   zMonitor._check_with_socket'  s    
 ~~668 T--/4@HLLT55$:R:R:c:c {{((9922H {{<t<H)E111r$   )rp   r   rB   r   rq   r   rr   r   rS   )r6   r   )r   r   r6   ztuple[Hello, float])rT   rU   rV   rD   rw   rz   r3   r=   r}   r)   r   r   r   __classcell__rs   s   @r"   rY   rY   n   s_    %*-%* %* 	%*
 ,%*N&
!%N;@"H2r$   rY   c                  0     e Zd Zd fdZddZddZ xZS )
SrvMonitorc                R   t         |   |dt        j                  |j                         || _        | j
                  j                  | _        t        | j
                  j                  t              sJ | j
                  j                  | _        t        j                         | _        y)zClass to poll SRV records on a background thread.

        Pass a Topology and a TopologySettings.

        The Topology is weakly referenced.
        pymongo_srv_polling_threadN)r^   rD   r	   MIN_SRV_RESCAN_INTERVALr_   rc   _seeds	_seedlistr   fqdnrP   _fqdnr   r   _startup_time)rA   rB   rr   rs   s      r"   rD   zSrvMonitor.__init__A  s~     	(**11		
 +..$..--s333..--
!^^-r$   c                (   t        j                         | j                  t        j                  z   k  ry | j                         }|r.|| _        	 | j                  j                  | j                         y y # t        $ r | j                          Y y w xY wr1   )r   r   r   r	   r   _get_seedlistr   r?   on_srv_updater   r=   )rA   seedlists     r"   r)   zSrvMonitor._runT  sw    >>d0063Q3QQQ%%'%DN,,T^^<  " 

s   %A5 5BBc                   	 t        | j                  | j                  j                  j                  | j                  j
                        }|j                         \  }}t        |      dk(  rt        	 | j                  j                  t        |t        j                               |S # t        $ r | j                          Y yw xY w)zXPoll SRV records for a seedlist.

        Returns a list of ServerDescriptions.
        r   N)r   r   rc   pool_optionsconnect_timeoutsrv_service_nameget_hosts_and_min_ttllenr   r:   update_intervalmaxr	   r   rO   )rA   resolverr   ttls       r"   r   zSrvMonitor._get_seedlista  s    
	#

++;;//H
 %::<MHc8}! " NN**3sF4R4R+STO  	
  	s   A0B( (CC)rB   r   rr   r   rS   )r6   zOptional[list[tuple[str, Any]]])rT   rU   rV   rD   r)   r   r   r   s   @r"   r   r   @  s    .&r$   r   c                  P     e Zd Zd fdZd	dZd
dZddZd	dZd	dZddZ	 xZ
S )rj   c                    t         |   |d|j                  t        j                         || _        t               | _        t               | _	        t               | _        y)z\Maintain round trip times for a server.

        The Topology is weakly referenced.
        pymongo_server_rtt_threadN)r^   rD   r_   r	   r`   rb   r   _moving_averager   _moving_minr   _lock)rA   rB   rr   rq   rs   s       r"   rD   z_RttMonitor.__init__}  sP    
 	'11))		
 
,(?!^
r$   c                X    | j                          | j                  j                          y r1   )r3   rb   r   rG   s    r"   r=   z_RttMonitor.close  s      	

r$   c                    | j                   5  | j                  j                  |       | j                  j                  |       ddd       y# 1 sw Y   yxY w)zAdd a RTT sample.N)r   r   r   r   )rA   samples     r"   r   z_RttMonitor.add_sample  sF    ZZ 	0  ++F3''/	0 	0 	0s   7AAc                    | j                   5  | j                  j                         | j                  j                         fcddd       S # 1 sw Y   yxY w)zBGet the calculated average, or None if no samples yet and the min.N)r   r   r   r   rG   s    r"   r   z_RttMonitor.get  sH    ZZ 	F''++-t/?/?/C/C/EE	F 	F 	Fs   4AAc                    | j                   5  | j                  j                          | j                  j                          ddd       y# 1 sw Y   yxY w)zReset the average RTT.N)r   r   r   r   rG   s    r"   r   z_RttMonitor.reset  sB    ZZ 	%  &&(""$	% 	% 	%s   5AAc                    	 | j                         }| j                  |       y # t        $ r | j                          Y y t        $ r | j
                  j                          Y y w xY wr1   )_pingr   r   r=   r   rb   r   )rA   rtts     r"   r)   z_RttMonitor._run  sP    
	 **,COOC  	JJL 	JJ	s   !$ A$"A$#A$c                   | j                   j                         5 }| j                  j                  rt	        d      t        j                         }|j                          t        j                         |z
  cddd       S # 1 sw Y   yxY w)z)Run a "hello" command and return the RTT.z_RttMonitor closedN)rb   r   r:   ry   r   r   r   hello)rA   r   r   s      r"   r   z_RttMonitor._ping  sf    ZZ  " 	,d~~&& 455NN$EJJL>>#e+	, 	, 	,s   ABB
)rB   r   rr   r   rq   r   rS   )r   rR   r6   r8   )r6   ztuple[Optional[float], float])r6   rR   )rT   rU   rV   rD   r=   r   r   r   r)   r   r   r   s   @r"   rj   rj   |  s'    $"0F
%,r$   rj   c                b    t        j                  | t              }t        j	                  |       y r1   )r;   r<   _unregister	_MONITORSadd)r*   r<   s     r"   r@   r@     s    
++g{
+CMM#r$   c                .    t         j                  |        y r1   )r   remove)monitor_refs    r"   r   r     s    [!r$   c                 v    t         y t        t               } | D ]  } |       }|s|j                           d }y r1   )r   listr3   )monitorsr<   r*   s      r"   _shutdown_monitorsr     sD     IH  $%!!#$
 Gr$   c                 B    t         } | r |         t        } | r |         y y r1   )r   r   )shutdowns    r"   _shutdown_resourcesr     s!    !H
"H
 r$   )r!   r   r6   r8   )r*   r&   r6   r8   )r   z"weakref.ReferenceType[MonitorBase]r6   r8   rS   )7__doc__
__future__r   atexitr   r;   typingr   r   r   r   r   pymongor	   r
   pymongo._csotr   pymongo.errorsr   r   r   r   pymongo.hellor   pymongo.lockr   pymongo.periodic_executorr   pymongo.poolr   pymongo.read_preferencesr   pymongo.server_descriptionr   pymongo.srv_resolverr   r   r   r   pymongo.settingsr   pymongo.topologyr   r#   r&   rY   r   rj   setr   r@   r   r   r   registerrW   r$   r"   <module>r      s    @ "    > > - ' a a  % 9 ! 2 8 -CC1); ;|O2k O2d9 9x=,+ =,F E	
"  # $r$   