
    nhL                       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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 ddlmZ dd	lmZ dd
l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% e	rddl&m'Z'm(Z(m)Z) ddl*m+Z+ ddl,m-Z- dZ.d"dZ/d#dZ0 G d d      Z1 G d de1      Z2 G d de1      Z3 G d de1      Z4 e5       Z6d$dZ7d%dZ8d&d Z9d&d!Z:e.r ejv                  e:       yy)'z9Class to monitor a MongoDB server on a background thread.    )annotationsN)TYPE_CHECKINGAnyOptional)commonperiodic_executor)MovingMinimum)NetworkTimeout_OperationCancelled)Hello)_create_lock)_SDAM_LOGGER
_debug_log_SDAMStatusMessage)_shutdown_executors)_is_faas)MovingAverage)ServerDescription)_SrvResolver)
ConnectionPool_CancellationContext)TopologySettings)TopologyTc                .    d| _         d| _        d| _        y)z'PYTHON-2433 Clear error traceback info.N)__traceback____context__	__cause__errors    /var/www/html/SchoolMeal/SchoolMeal/pds_admin_SchoolMeal/Backend/venv/lib/python3.12/site-packages/pymongo/synchronous/monitor.py	_sanitizer"   2   s    EEEO    c                D    t        dt        j                         | z
        S )zReturn the duration since the given start time.

    Accounts for buggy platforms where time.monotonic() is not monotonic.
    See PYTHON-4600.
    g        )maxtime	monotonic)starts    r!   _monotonic_durationr)   9   s     sDNN$u,--r#   c                  <    e Zd ZddZd	dZd	dZd	dZ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>.targetL   s    jGLLNr#   )intervalmin_intervalr1   nameNc                :            }|r|j                          y y Ngc_safe_close)dummyr/   r0   s     r!   _on_topology_gcz-MonitorBase.__init__.<locals>._on_topology_gcY   s      jG%%' r#   )returnboolr6   )r9   zOptional[Topology]r;   None)	r   PeriodicExecutor	_executorweakrefrefcloseproxy	_topology	_register)	selftopologyr4   r2   r3   r1   executorr:   r0   s	           @r!   __init__zMonitorBase.__init__C   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rF   s    r!   rK   zMonitorBase.opene   s    
 	r#   c                8    | j                   j                          y)zGC safe close.N)r?   rB   rL   s    r!   r8   zMonitorBase.gc_safe_closel   s    r#   c                $    | j                          y)zWClose and stop monitoring.

        open() restarts the monitor after closing.
        Nr7   rL   s    r!   rB   zMonitorBase.closep   s    
 	r#   c                8    | j                   j                          y)zWait for the monitor to stop.N)r?   joinrL   s    r!   rP   zMonitorBase.joinw       r#   c                8    | j                   j                          y)z)If the monitor is sleeping, wake it soon.N)r?   wakerL   s    r!   request_checkzMonitorBase.request_check{   rQ   r#   N)rG   r   r4   strr2   intr3   floatr;   r=   )	__name__
__module____qualname__rI   rK   r8   rB   rP   rT    r#   r!   r+   r+   B   s!     Dr#   r+   c                       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ddZ xZS )Monitorc                   t         |   |d|j                  t        j                         || _        || _        || _        | j                  j                  j                  | _
        | j                  duxr | j                  j                  | _        d| _        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)superrI   heartbeat_frequencyr   MIN_HEARTBEAT_INTERVAL_server_description_pool	_settings_pool_options_event_listeners
_listenersenabled_for_server_heartbeat_publish_cancel_context_conn_id_RttMonitor_create_pool_for_monitoraddress_rtt_monitorserver_monitoring_mode_streamr   )rF   server_descriptionrG   pooltopology_settings	__class__s        r!   rI   zMonitor.__init__   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)rn   cancel)rF   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)rs   rK   r?   _stoppedrB   rL   s    r!   _start_rtt_monitorzMonitor._start_rtt_monitor   s:    
 	 >>""##% #r#   c                    | j                   j                          | j                  j                          | j	                          y r6   )r?   rB   rs   r8   r}   rL   s    r!   r8   zMonitor.gc_safe_close   s0    '')r#   c                    t        j                  | j                  j                         | j                  j                         d       y )NT)return_exceptions)asynciogatherr?   rP   rs   rL   s    r!   rP   zMonitor.join   s/    t~~**,d.?.?.D.D.FZ^_r#   c                x    | j                          | j                  j                          | j                          y r6   )r8   rs   rB   _reset_connectionrL   s    r!   rB   zMonitor.close   s.    ! 	 r#   c                8    | j                   j                          y r6   )rg   resetrL   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                          | j                  j                  r| j                  j                          y y # t        $ r}t        |       t	        | j                   j
                  |      | _         |j                  r| j                  j                          Y d }~| j                  j                  r| j                  j                          y y d }~ww xY w# t(        $ r | j                          Y w xY w# | j                  j                  r| j                  j                          w w xY w)Nr   )
reset_poolinterrupt_connections)rf   _check_serverr   r"   r   rr   is_server_type_knownr?   
skip_sleepr   rs   rB   rD   	on_changer    
isinstancer
   ru   topology_versionr   ReferenceError)rF   prev_sdexcs      r!   r.   zMonitor._run   s   '	*..G+/+=+=+?( NN$$((3399&01I1I1O1OQ_&` %  ||((==,,=='')))+''--'2N2N))+
 ~~&&!!'') 'E ' 
#+<,,44C,( // NN--/0 ~~&&!!'') 'E
<  	JJL	 ~~&&!!'') 'sM   G0 E C<G0 	G-AG(2G0 (G--G0 0H	H HH 3Ic                8   d| _         t        j                         }	 | j                         S # t        $ r  t
        $ rY}t        |       | j                  }|j                  }t        |      }t        | j                  xr |j                  xr |j                        }| j                  r,| j                  J | j                  j!                  ||||       t#        j$                  t&        j(                        rMt+        t"        t,        j.                  | j0                  j2                  |d   |d   ||dz  || j                   	       | j5                          t7        |t8              r | j:                  j=                          t?        ||      cY d}~S d}~ww xY w)z^Call hello or read the next streaming response.

        Returns a ServerDescription.
        Nr        )message
topologyId
serverHost
serverPortawaited
durationMSfailuredriverConnectionIdr   ) ro   r&   r'   _check_oncer   	Exceptionr"   rf   rr   r)   r<   ru   r   r   rm   rk   publish_server_heartbeat_failedr   isEnabledForloggingDEBUGr   r   HEARTBEAT_FAILrD   _topology_idr   r   r   rs   r   r   )rF   r(   r    sdrr   durationr   s          r!   r   zMonitor._check_server   sQ   
  	;##%% 	 	;e))BjjG*51H4<<[B,C,C[H[H[\G}}222??SXZab((7 .==#~~::&qz&qz#'$!'+}}
 ""$%!45##%$WE::5	;s   - F EFFFc                   | j                   j                  }| j                   }t        | j                  j                  xr( | j
                  xr |j                  xr |j                        }| j                  r*| j                  J | j                  j                  ||       | j                  r&| j                  j                  r| j                          | j                  j                         5 }t        j                   t"        j$                        rSt'        t        t(        j*                  | j,                  j.                  |j0                  |j2                  |d   |d   |       |j4                  | _        |j0                  | _        | j9                  |      \  }}|j:                  s| j<                  j?                  |       | j<                  jA                         \  }}tC        ||||      }| j                  r6| j                  J | j                  jE                  ||||j:                         t        j                   t"        j$                        rbt'        t        t(        jF                  | j,                  j.                  |j0                  |j2                  |d   |d   ||dz  |jH                  
       |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.
        Nr   r   )r   r   r   serverConnectionIdr   r   r   )min_round_trip_timer   )	r   r   r   r   r   r   r   r   reply)%rf   rr   r<   rg   connsru   r   r   rm   rk    publish_server_heartbeat_startedrn   	cancelledr   checkoutr   r   r   r   r   r   HEARTBEAT_STARTrD   r   idserver_connection_idcancel_contextro   _check_with_socket	awaitablers   
add_samplegetr   "publish_server_heartbeat_succeededHEARTBEAT_SUCCESSdocument)	rF   rr   r   r   connresponseround_trip_timeavg_rttmin_rtts	            r!   r   zMonitor._check_once#  s?   
 **22%% JJaa"2I2IabNaNa
 ==??...OO<<WgND$8$8$B$B""$ZZ  " (	d((7 .>>#~~::'+ww'+'@'@&qz&qz#	 $(#6#6D  GGDM(,(?(?(E%Ho%%!!,,_=#00446GW"7HgSZ[B}}222BB_h8J8J ((7 .@@#~~::'+ww'+'@'@&qz&qz#.5"++ Q(	 (	 (	s   .GK  K	c                   t        j                         }|j                  rt        |j	                         d      }n{| j
                  r]|j                  rQ| j                  j                  r;|j                  | j                  j                  | j                  j                        }n|j                  dd      }t        |      }||fS )zcReturn (Hello, round_trip_time).

        Can raise ConnectionFailure or OperationFailure.
        T)r   N)r&   r'   more_to_comer   _next_replyru   performed_handshakerf   r   _hellorh   rd   r)   )rF   r   r(   r   r   s        r!   r   zMonitor._check_with_socket`  s    
  T--/4@HLLT55$:R:R:c:c {{((9922H {{4.H&u-!!r#   )rv   r   rG   r   rw   r   rx   r   rX   )r;   r   )r   r   r;   ztuple[Hello, float])rY   rZ   r[   rI   r}   r   r8   rP   rB   r   r.   r   r   r   __classcell__ry   s   @r!   r^   r^      se    &*-&* &* 	&*
 ,&*P&
`!(*T%;N;z"r#   r^   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)rc   rI   r   MIN_SRV_RESCAN_INTERVALrd   rh   _seeds	_seedlistr   fqdnrU   _fqdnr&   r'   _startup_time)rF   rG   rx   ry   s      r!   rI   zSrvMonitor.__init__y  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r6   )r&   r'   r   r   r   _get_seedlistr   rD   on_srv_updater   rB   )rF   seedlists     r!   r.   zSrvMonitor._run  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   rh   pool_optionsconnect_timeoutsrv_service_nameget_hosts_and_min_ttllenr   r?   update_intervalr%   r   r   rT   )rF   resolverr   ttls       r!   r   zSrvMonitor._get_seedlist  s    
	#

++;;//H
 %::<MHc8}! " NN**3sF4R4R+STO  	
  	s   A0B( (CC)rG   r   rx   r   rX   )r;   zOptional[list[tuple[str, Any]]])rY   rZ   r[   rI   r.   r   r   r   s   @r!   r   r   x  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 )rp   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)rc   rI   rd   r   re   rg   r   _moving_averager	   _moving_minr   _lock)rF   rG   rx   rw   ry   s       r!   rI   z_RttMonitor.__init__  sP    
 	'11))		
 
,(?!^
r#   c                X    | j                          | j                  j                          y r6   )r8   rg   r   rL   s    r!   rB   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   )rF   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   rL   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   rL   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r6   )_pingr   r   rB   r   rg   r   )rF   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        |      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)	rg   r   r?   r   r   r&   r'   hellor)   )rF   r   r(   s      r!   r   z_RttMonitor._ping  s_    ZZ  " 	.d~~&& 455NN$EJJL&u-	. 	. 	.s   AA55A>)rG   r   rx   r   rw   r   rX   )r   rW   r;   r=   )r;   ztuple[Optional[float], float])r;   rW   )rY   rZ   r[   rI   rB   r   r   r   r.   r   r   r   s   @r!   rp   rp     s'    $"0F
%.r#   rp   c                b    t        j                  | t              }t        j	                  |       y r6   )r@   rA   _unregister	_MONITORSadd)r/   rA   s     r!   rE   rE     s    
++g{
+CMM#r#   c                .    t         j                  |        y r6   )r   remove)monitor_refs    r!   r   r     s    [!r#   c                 v    t         y t        t               } | D ]  } |       }|s|j                           d }y r6   )r   listr8   )monitorsrA   r/   s      r!   _shutdown_monitorsr     sD     IH  $%!!#$
 Gr#   c                 B    t         } | r |         t        } | r |         y y r6   )r   r   )shutdowns    r!   _shutdown_resourcesr     s!    !H
"H
 r#   )r    r   r;   r=   )r(   rW   r;   rW   )r/   r+   r;   r=   )r   z"weakref.ReferenceType[MonitorBase]r;   r=   rX   )<__doc__
__future__r   r   atexitr   r&   r@   typingr   r   r   pymongor   r   pymongo._csotr	   pymongo.errorsr
   r   pymongo.hellor   pymongo.lockr   pymongo.loggerr   r   r   pymongo.periodic_executorr   pymongo.pool_optionsr   pymongo.read_preferencesr   pymongo.server_descriptionr    pymongo.synchronous.srv_resolverr   pymongo.synchronous.poolr   r   r   pymongo.synchronous.settingsr   pymongo.synchronous.topologyr   _IS_SYNCr"   r)   r+   r^   r   rp   setr   rE   r   r   r   registerr\   r#   r!   <module>r     s    @ "      / / - ' >  % G G 9 ) 2 8 9 
 >5.; ;|u"k u"p9 9x=.+ =.F E	
"  FOO'( r#   