
    Ii+                      S SK Jr  S SKrS SKrS SKrS SKrS SKrS SKrS SKrS SK	r	S SK
r
S SKrS SKrS SKrS SKJrJrJrJrJrJrJrJrJr  S SKJr  S SKJrJr  S SKJrJrJ r J!r!J"r"  S SK#J$r$J%r%J&r&J'r'J(r(J)r)J*r*J+r+J,r,J-r-J.r.J/r/  S SK0J1r1J2r2  S S	K3J4r4J5r5  S S
K6J7r7J8r8J9r9J:r:  S SK;J<r<J=r=  S SK>J?r?  S SK@JArA  S SKBJCrC  S SKDJErE  S SKFJGrG  S SKHJIrI  S SKJJKrKJLrL  S SKMJNrN  S SKOJPrP  S SKQJRrRJSrS  \(       aT  S SKJTrT  S SKUJVrV  S SKWJXrXJYrYJZrZ  S SK[J\r\J]r]  S SK^J_r_  S SK`Jara  S SKBJbrb  S SKcJdrd  S SKMJere  S SKfJgrgJhrh  S S KiJjrjJkrkJlrl  S S!KmJnrn   S S"KoJprpJqrqJrrrJoro  SES# jrsS%ruS&rvS'rwS(rx\
R                  S):X  aG   S SKzr{S* r| \{R                  " \{R                  S+5       r\|" \S,S-5      r\|" \S.S/5      rSSS5        S0 rO
SFS1 jrSGS2 jr  SH         SIS3 jjrSJS4 jrSKS5 jrSLS6 jr " S7 S85      r " S9 S:5      rSMS; jrSNS< jr " S= S>\-5      r " S? S@5      r " SA SB5      r " SC SD5      rg! \t a    SES$ jrs Nf = f! \t a    S SK{r{ Nf = f! , (       d  f       N= f! \ a    S-rS/r Nf = f)O    )annotationsN)	TYPE_CHECKINGAny	GeneratorMappingMutableMappingNoReturnOptionalSequenceUnion)DEFAULT_CODEC_OPTIONS)_csothelpers_shared)MAX_BSON_SIZEMAX_MESSAGE_SIZEMAX_WIRE_VERSIONMAX_WRITE_BATCH_SIZEORDERED_TYPES)AutoReconnectConfigurationErrorConnectionFailureDocumentTooLargeExecutionTimeoutInvalidOperationNetworkTimeoutNotPrimaryErrorOperationFailurePyMongoErrorWaitQueueTimeoutError_CertificateError)HelloHelloCompat)_create_lock_Lock)_CONNECTION_LOGGER_ConnectionStatusMessage
_debug_log _verbose_connection_error_reason)ConnectionCheckOutFailedReasonConnectionClosedReason)sendall)PoolOptions)ReadPreference)_add_to_command)SERVER_TYPE)SocketChecker)HAS_SNISSLError)_validate_session_write_concern)_handle_reauth)commandreceive_message)CodecOptions)ObjectId)SnappyContextZlibContextZstdContext)_OpMsg_OpReply)_sslConn)ReadConcern)_ServerMode)_AuthContext)ClientSession)MongoClient_MongoClientErrorHandler)ClusterTime_Address_CollationIn)WriteConcern)F_GETFDF_SETFD
FD_CLOEXECfcntlc                T    [        U [        5      n[        U [        U[        -  5        g)z8Set the close-on-exec flag on the given file descriptor.N)rL   rI   rJ   rK   )fdflagss     >/venv/lib/python3.13/site-packages/pymongo/synchronous/pool.py_set_non_inheritable_non_atomicrQ   l   s    b'"b'5:-.    c                    g)z6Dummy function for platforms that don't provide fcntl.N )rN   s    rP   rQ   rQ   u   s    rR   Tx   
   	   win32c                z     [         R                  " X5      u  p4[        U5      $ ! [        [        4 a    Us $ f = fN)winregQueryValueExintOSError
ValueError)keynamedefaultvalue_s        rP   _queryre      s>    	**35HEu:$ 	 N	s   "% ::z2SYSTEM\CurrentControlSet\Services\Tcpip\ParametersKeepAliveTimei m KeepAliveInterval  c                    [        [        [        S-  5      n[        [        [        S-  5      nU[        :  d
  U[        :  a#  U R                  [        R                  SX45        g g )Nrh      )min_WINDOWS_TCP_IDLE_MS_MAX_TCP_KEEPIDLE_WINDOWS_TCP_INTERVAL_MS_MAX_TCP_KEEPINTVLioctlsocketSIO_KEEPALIVE_VALS)sockidle_msinterval_mss      rP   _set_keepalive_timesrv      sX    *,=,DE24F4MN))[;S-SJJv001g2KL .TrR   c                    [        [        U5      (       aX  [        [        U5      n U R                  [        R                  U5      nXB:  a!  U R                  [        R                  X25        g g g ! [         a     g f = frZ   )hasattrrq   getattr
getsockoptIPPROTO_TCP
setsockoptr^   )rs   
tcp_option	max_valuesockoptrb   s        rP   _set_tcp_optionr      sp    6:&&fj1G //&*<*<gF&OOF$6$6K ' '  s   AA/ /
A<;A<c                j    [        U S[        5        [        U S[        5        [        U S[        5        g )NTCP_KEEPIDLETCP_KEEPINTVLTCP_KEEPCNT)r   rm   ro   _MAX_TCP_KEEPCNT)rs   s    rP   rv   rv      s)    n.?@o/ABm-=>rR   c                :   U u  pEUb  SXEU4-  nOU SU 3nU(       a  X&-   nSU;  a  U[        U5      -  n[        U[        R                  5      (       a  [	        U5      Ue[        U[
        5      (       a  S[        U5      ;   a  [	        U5      Ue[        U5      Ue)z9Convert a socket.error to ConnectionFailure and raise it.z	%s:%d: %s: zconfigured timeouts	timed out)format_timeout_details
isinstancerq   timeoutr   r2   strr   )addresserror
msg_prefixtimeout_detailshostportmsgs          rP   _raise_connection_failurer      s     JDT//b C'%o66%((S!u,	E8	$	$E
)B
 S!u,C e+rR   c                f    U(       a  U[         R                  " 5       -
  OS nU R                  U5      $ rZ   )time	monotonicwait)	conditiondeadliner   s      rP   
_cond_waitr      s&    -5h))4G>>'""rR   c                    0 n[         R                  " 5       nU R                  nU R                  nU(       a  US-  US'   U(       a  U(       d  US-  US'   U(       a  US-  US'   U$ )Nrh   	timeoutMSsocketTimeoutMSconnectTimeoutMS)r   get_timeoutsocket_timeoutconnect_timeout)optionsdetailsr   r   r   s        rP   _get_timeout_detailsr      si    G!G++N--O&~g%3d%:!"&5&<"#NrR   c                r    SnU (       a-  US-  nS H  nX ;   d  M
  USU SX    S3-  nM     US S nUS-  nU$ )	N z (configured timeouts:)r   r   r    r   zms,)rT   )r   resultr   s      rP   r   r      s^    F**KG!AgYb)9(:#>> L #MrR   c                  <    \ rS rSrSS jrSS jr\SS j5       rSrg)	_CancellationContext   c                    SU l         g NF
_cancelledselfs    rP   __init___CancellationContext.__init__   s	    rR   c                    SU l         g)zCancel this context.TNr   r   s    rP   cancel_CancellationContext.cancel   s	    rR   c                    U R                   $ )zWas cancel called?r   r   s    rP   	cancelled_CancellationContext.cancelled   s     rR   r   NreturnNoner   bool)	__name__
__module____qualname____firstlineno__r   r   propertyr   __static_attributes__rT   rR   rP   r   r      s        rR   r   c                  *   \ rS rSrSr        S&S jrS'S jr      S(S jrS)S jrS)S jr	S)S jr
S*S	 jrS+S
 jr        S,S jrS*S jr\\R"                  \SSSSSSSSSSSS4                                 S-S jj5       rS.S jrS/S jrS0S jrS1S jr        S2S jrS3S4S jjr      S5S jrS6S jrS)S jrS7S jr        S8S jrS9S jrS)S jr S:S jr!S;S jr"S<S  jr#S=S! jr$S=S" jr%S>S# jr&S?S$ jr'S%r(g)@
Connection   zStore a connection with some metadata.

:param conn: a raw connection object
:param pool: a Pool instance
:param address: the server's (host, port)
:param id: the id of this socket in it's pool
c                   [         R                  " U5      U l        Xl        X0l        X@l        SU l        [        R                  " 5       U l	        SU l
        SU l        [        U l        [        U l        [         U l        [$        U l        SU l        SU l        SU l        SU l        UR0                  R2                  U l        UR6                  U l        UR8                  U l        UR0                  R:                  U l        S U l        [A        5       U l!        S U l"        S U l#        S U l$        URJ                  U l&        U RL                  RO                  5       U l(        SU l)        [U        5       U l+        UR0                  U l        SU l,        S U l-        S U l.        SU l/        SU l0        SU l1        U R0                  Rd                  U l3        SU l4        URj                  U l5        [        R                  " 5       U l6        g )NFg        )7weakrefrefpool_refconnr   idclosedr   r   last_checkin_timeperformed_handshakeis_writabler   max_wire_versionr   max_bson_sizer   max_message_sizer   max_write_batch_sizesupports_sessionshello_ok	is_mongosop_msg_enabledopts_event_listeners	listenersenabled_for_cmapenabled_for_logging_compression_settingscompression_settingscompression_contextr0   socket_checkeroidc_token_gen_idnegotiated_mechsauth_ctxgenpool_genget_overall
generationreadyr   cancel_contextmore_to_come
service_idserver_connection_id
pinned_txnpinned_cursoractiver   last_timeoutconnect_rtt
_client_idcreation_time)r   r   poolr   r   s        rP   r   Connection.__init__	  s     D)	!%!1#( !& 0* 0$8!!&##33 $ 5 5#'#;#; $(II$C$C!Y] -:_045904 --335
4H4JII	"'.237!  " II44//!^^-rR   c                f    XR                   :X  a  gXl         U R                  R                  U5        g)z?Cache last timeout to avoid duplicate calls to conn.settimeout.N)r   r   
settimeout)r   r   s     rP   set_conn_timeoutConnection.set_conn_timeout<  s)    '''#		W%rR   c                   [         R                  " 5       nUc7  U R                  (       d%  U R                  U R                  R
                  5        g [         R                  " 5       nUc  U R                  nX4-
  nUS:  aI  [        U R                  5      n[        U5      nSUS SUS SU 3n[        USSUSS.U R                  5      eUb  [        US-  5      US	'   U R                  U5        U$ )
Nr   z5operation would exceed time limit, remaining timeout:z.5fz <= network round trip time:r   2   okerrmsgcoderh   	maxTimeMS)r   	remainingr   r   r   r   get_rttr   r   r   r   r   r]   )	r   clientcmdr   rttmax_time_msr   	formattedr  s	            rP   apply_timeoutConnection.apply_timeoutC  s     //#?$$%%dii&>&>?mmo;""Cm?2499=O.?ILWUXMYuvyz}u~~  AJ  @K  LF"FB7%%	  ?";#56Cg&rR   c                8    SU l         U R                  (       a   eg NT)r   r   r   s    rP   pin_txnConnection.pin_txnb  s    %%%%%rR   c                8    SU l         U R                  (       a   eg r  )r   r   r   s    rP   
pin_cursorConnection.pin_cursorf  s    !??""?rR   c                    U R                  5       nU(       a  UR                  U 5        g U R                  [        R                  5        g rZ   )r   checkin
close_connr*   STALE)r   r   s     rP   unpinConnection.unpinj  s/    }}LLOO2889rR   c                    U R                   R                  (       d,  U R                  (       d  U R                   R                  (       a  SU l        [
        R                  S0$ [
        R                  SSS0$ )NTrj   helloOk)r   
server_apir   load_balancedr   r"   CMD
LEGACY_CMDr   s    rP   	hello_cmdConnection.hello_cmdq  sO     994==DII4K4K"&DOOQ''**Ay$??rR   c                (    U R                  S S S 5      $ rZ   )_hellor   s    rP   helloConnection.helloz  s    {{4t,,rR   c                   U R                  5       nU R                  (       + nSnU(       ak  SU l        U R                  R                  US'   U R                  (       a  U R                  R
                  US'   U R                  R                  (       a  SUS'   ObUb_  X$S'   Uc   e[        US-  5      US'   SnU R                  R                  (       a(  U R                  U R                  R                  U-   5        U(       d  Ub  XS	'   U R                  R                  nU(       a  UR                  S
:X  a0  UR                  (       a  UR                  S-   UR                  -   US'   SSKJn  UR                   R#                  XpR$                  5      n	U	(       a  U	R'                  5       n
U
b  XS'   OS n	U(       a  [(        R*                  " 5       nU R-                  SUSUS9nU(       a  [(        R*                  " 5       W-
  U l        [1        XS9nUR2                  U l        UR4                  U l        UR6                  U l        UR8                  U l        UR:                  U l        UR<                  S L=(       a    UR>                  U l         UR<                  U l        URB                  U l!        URD                  [F        RH                  [F        RJ                  [F        RL                  [F        RN                  [F        RP                  4;   U l)        URD                  [F        RT                  :H  U l+        URD                  [F        RX                  :H  U l-        U(       a<  U R                  (       a+  U R                  R]                  UR
                  5      nXl/        SU l0        URb                  U l2        U(       a  URf                  U l4        U	(       a,  U	Rk                  U5        U	Rm                  5       (       a  Xl7        U R                  R                  (       aW  URp                  (       d  [s        S5      eURp                  U l8        U Rt                  Rw                  U Rp                  5      U l<        U$ )NFTr  compressionloadBalancedtopologyVersionrh   maxAwaitTimeMSz$clusterTimeDEFAULT.saslSupportedMechsr   authspeculativeAuthenticateadmin)publish_eventsexhaust_allowed)	awaitablez`Driver attempted to initialize in load balancing mode, but the server does not support this mode)=r"  r   r   metadatar   compressorsr  r]   r   r   _credentials	mechanismusernamesourcepymongo.synchronousr1  rA   from_credentialsr   speculate_commandr   r   r5   r   r!   r   r   r   r   r   logical_session_timeout_minutesis_readabler   r   server_typer/   	RSPrimaryRSSecondary	RSArbiterRSOtherRSGhostis_repl
Standaloneis_standaloneMongosr   get_compression_contextr   r   connection_idr   sasl_supported_mechsr   parse_responsespeculate_succeededr   r   r   r   getr   )r   cluster_timetopology_versionheartbeat_frequencyr	  performing_handshaker6  credsr1  r   speculative_authenticatestartdocr&  ctxs                  rP   r%  Connection._hello}  s    nn#'#;#;;	'+D$ II..CM((%)%>%>%J%JM"yy&&&*N#)%5!"&222$'(;d(B$CC !Iyy((%%dii&?&?BU&UV#(@".		&&)+,1LL3,>,O()0((99%NH+3+E+E+G(+75M12HNN$Ell7CylY#~~/%7Dc/ ,, % 6 6"00 % 6 6$)$>$>!11=S%BSBS 	 ?D>c>c,((!!##!!-
 
 #..+2H2HH**k.@.@@D$=$=++CCEDUDUVC'*$"$)$7$7!$)$>$>D!##E*++-- (99""##(A  $..DO"mm//@DOrR   c                    U R                  S 5      nUR                  U l        UR                  5       nUS   n[        R                  " X0R
                  5        U$ Nr   )r6   r   unpack_responser   _check_command_responser   )r   replyunpacked_docsresponse_docs       rP   _next_replyConnection._next_reply  sR    $$T*!..--/$Q'..|=R=RSrR   TNFc                   U R                  X5        [        X5      n[        U[        5      (       d  [	        U5      nUb  UR
                  (       d  U
b  [        S5      eU R                  U5        U(       a  UR                  X-X05        U R                  X+U5        U(       a  U R                  OSn[        U=(       a    UR
                  (       + 5      nU R                  (       a  U R                  U5         [        U UUU R                  UUUUUUU R                   UU R"                  UU	U
U R$                  U R                  UUUUS9$ ! [&        [(        4 a    e [*         a  nU R-                  U5         SnAgSnAff = f)a  Execute a command or raise an error.

:param dbname: name of the database on which to run the command
:param spec: a command document as a dict, SON, or mapping object
:param read_preference: a read preference
:param codec_options: a CodecOptions instance
:param check: raise OperationFailure if there are errors
:param allowable_errors: errors to ignore if `check` is True
:param read_concern: The read concern for this command.
:param write_concern: The write concern for this command.
:param parse_write_concern_error: Whether to parse the
    ``writeConcernError`` field in the command response.
:param collation: The collation for this command.
:param session: optional ClientSession instance.
:param client: optional MongoClient for gossipping $clusterTime.
:param retryable_write: True if this command is a retryable write.
:param publish_events: Should we publish events for this command?
:param user_fields: Response fields that should be decoded
    using the TypeDecoders from codec_options, passed to
    bson._decode_all_selective.
Nz3Collation is unsupported for unacknowledged writes.)parse_write_concern_error	collationcompression_ctx
use_op_msgunacknowledgeduser_fieldsr5  write_concern)validate_sessionr3   r   r   dictacknowledgedr   add_server_api	_apply_tosend_cluster_timer   r   r   _raise_if_not_writabler5   r   r   r   r   r   r   BaseExceptionr   )r   dbnamespecread_preferencecodec_optionscheckallowable_errorsread_concernrl  rf  rg  sessionr  retryable_writer4  rk  r5  r   rj  r   s                       rP   r5   Connection.command  sb   R 	f.1'I $..:D%)C)CyGX$%Z[[D!d_Ktf5&4DNN$	mNM4N4N0NO''7	2 ""*C# $ 8 8..-' /+- 0 !/2 	 	2**511	2s   6AE E; E66E;c                    U R                   b(  X R                   :  a  [        SX R                   4-  5      e [        U R                  U5        g! [         a  nU R                  U5         SnAgSnAff = f)zmSend a raw BSON message or raise ConnectionFailure.

If a network exception is raised, the socket is closed.
NzfBSON document too large (%d bytes) - the connected server supports BSON document sizes up to %d bytes.)r   r   r+   r   rt  r   )r   messagemax_doc_sizer   s       rP   send_messageConnection.send_message8  ss    
 )l=O=O.O"?BNPbPbAcd 
	2DIIw' 	2**511	2s   A 
A3A..A3c                     [        XU R                  5      $ ! [         a  nU R                  U5         SnAgSnAff = f)zjReceive a raw BSON message or raise ConnectionFailure.

If any exception is raised, the socket is closed.
N)r6   r   rt  r   )r   
request_idr   s      rP   r6   Connection.receive_messageH  s;    
	2"4T5J5JKK 	2**511	2s    
=8=c                V    U(       a"  U R                   (       d  [        SSSSS.5      egg)zNRaise NotPrimaryError on unacknowledged write if this socket is not
writable.
znot primaryr   i{'  r  N)r   r   )r   rj  s     rP   rs  !Connection._raise_if_not_writableR  s+     $"2"2!-]\a1bcc #3>rR   c                H    U R                  S5        U R                  X5        g)zSend unack OP_MSG.

Can raise ConnectionFailure or InvalidDocument.

:param msg: bytes, an OP_MSG message.
:param max_doc_size: size in bytes of the largest document in `msg`.
TN)rs  r  )r   r   r  s      rP   unack_writeConnection.unack_writeZ  s      	##D)#,rR   c                    U R                  US5        U R                  U5      nUR                  U5      n[        R                  " XPR
                  5        U$ )zSend "insert" etc. command, returning response as a dict.

Can raise ConnectionFailure or OperationFailure.

:param request_id: an int.
:param msg: bytes, the command message.
r   )r  r6   command_responser   r_  r   )r   r  r   rx  r`  r   s         rP   write_commandConnection.write_commande  sO     	#q!$$Z0''6 	..v7L7LMrR   c           
        U(       a  U R                   (       a  SU l        SU l        U R                  (       Gd9  U R                  R                  nU(       a  SSKJn  UR                  X US9  SU l        [        R                  " 5       U R                  -
  nU R                  (       a@  U R                  c   eU R                  R                  U R                  U R                  U5        U R                   (       az  ["        R$                  " [&        R(                  5      (       aP  [+        ["        U R,                  [.        R0                  U R                  S   U R                  S   U R                  US9  gggg)	zXAuthenticate to the server if needed.

Can raise ConnectionFailure or OperationFailure.
NFr   r0  )reauthenticateTrj   clientIdr  
serverHost
serverPortdriverConnectionId
durationMS)r   r   r   r   r9  r=  r1  authenticater   r   r   r   r   publish_connection_readyr   r   r   r%   isEnabledForloggingDEBUGr'   r   r&   
CONN_READY)r   r  rV  r1  durations        rP   r  Connection.authenticatew  s    '' $DJzzzII**E4!!%n!MDJ~~'$*<*<<H$$~~11177dggxX'',>,K,KGMM,Z,Z&!__4??#||A#||A'+ww' -[' rR   c                H    U(       a  UR                   ULa  [        S5      egg)zsValidate this session before use with client.

Raises error if the client is not the one that created the session.
z9Can only use session with the MongoClient that started itN)_clientr   )r   r  r|  s      rP   rm  Connection.validate_session  s)     f,&'bcc - rR   c                $   U R                   (       a  gU R                  5         U(       a  U R                  (       a@  U R                  c   eU R                  R	                  U R
                  U R                  U5        U R                  (       a  [        R                  " [        R                  5      (       aZ  [        [        U R                  [        R                  U R
                  S   U R
                  S   U R                  [!        U5      US9  gggg)z$Close this connection with a reason.Nr   rj   r  r  r  r  r  reasonr   )r   _close_connr   r   publish_connection_closedr   r   r   r%   r  r  r  r'   r   r&   CONN_CLOSEDr(   )r   r  s     rP   r  Connection.close_conn  s    ;;$$~~11188twwPVW'',>,K,KGMM,Z,Z&!__4@@#||A#||A'+ww;FC 	 -['	 rR   c                    U R                   (       a  gSU l         U R                  R                  5          U R                  R	                  5         g! [
         a     gf = f)zClose this connection.NT)r   r   r   r   close	Exceptionr   s    rP   r  Connection._close_conn  sJ    ;;""$	IIOO 		s   A 
AAc                L    U R                   R                  U R                  5      $ )z?Return True if we know socket has been closed, False otherwise.)r   socket_closedr   r   s    rP   conn_closedConnection.conn_closed  s    ""00;;rR   c                6    U(       a  UR                  X5        gg)zAdd $clusterTime.N)_send_cluster_time)r   r5   r|  r  s       rP   rr  Connection.send_cluster_time  s     %%g7 rR   c                z    U R                   R                  (       a   [        XR                   R                  5        gg)zAdd server_api parameters.N)r   r  r.   )r   r5   s     rP   rp  Connection.add_server_api  s&    99GYY%9%9:  rR   c                8    [         R                  " 5       U l        g rZ   r   r   r   r   s    rP   update_last_checkin_time#Connection.update_last_checkin_time  s    !%!1rR   c                    Xl         g rZ   )r   )r   r   s     rP   update_is_writableConnection.update_is_writable  s    &rR   c                F    [         R                  " 5       U R                  -
  $ )z9Seconds since this socket was last checked into its pool.r  r   s    rP   idle_time_secondsConnection.idle_time_seconds  s    ~~$"8"888rR   c                   U R                   (       a  S nO[        R                  nU R                  U5        [	        U[
        [        [        45      (       a*  [        U R                  5      n[        U R                  XS9  g e )Nr   )r   r*   ERRORr  r   IOErrorr^   r2   r   r   r   r   )r   r   r  r   s       rP   r   $Connection._raise_connection_failure  sZ      ::F+11Fegw9::*4995G%dllESrR   c                4    U R                   UR                   :H  $ rZ   )r   r   others     rP   __eq__Connection.__eq__  s    yyEJJ&&rR   c                    X:X  + $ rZ   rT   r  s     rP   __ne__Connection.__ne__  s      rR   c                ,    [        U R                  5      $ rZ   )hashr   r   s    rP   __hash__Connection.__hash__  s    DIIrR   c                    SR                  [        U R                  5      U R                  =(       a    S=(       d    S[	        U 5      5      $ )NzConnection({}){} at {}z CLOSEDr   )formatreprr   r   r   r   s    rP   __repr__Connection.__repr__  s8    '..OKK%I+tH
 	
rR   )+r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rH  rJ  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   Union[socket.socket, _sslConn]r   Poolr   ztuple[str, int]r   r]   )r   Optional[float]r   r   )r  rC   r	  z"Optional[MutableMapping[str, Any]]r   r  r   )r   dict[str, Any])r   r!   )rR  zOptional[ClusterTime]rS  zOptional[Any]rT  Optional[int]r   zHello[dict[str, Any]])"ru  r   rv  MutableMapping[str, Any]rw  r@   rx  r7   ry  r   rz  z#Optional[Sequence[Union[str, int]]]r{  zOptional[ReadConcern]rl  zOptional[WriteConcern]rf  r   rg  zOptional[_CollationIn]r|  Optional[ClientSession]r  Optional[MongoClient]r}  r   r4  r   rk  zOptional[Mapping[str, Any]]r5  r   r   r  )r  bytesr  r]   r   r   )r  r  r   zUnion[_OpReply, _OpMsg])rj  r   r   r   )r   r  r  r]   r   r   )r  r]   r   r  rx  r7   r   r  )F)r  r   r   r   )r  r  r|  r  r   r   )r  Optional[str]r   r   r   )r5   r  r|  r  r  r  r   r   )r5   r  r   r   )r   r   r   r   )r   float)r   rt  r   r	   )r  r   r   r   r   r]   )r   r   ))r   r   r   r   __doc__r   r   r  r  r  r  r"  r&  r%  rc  r4   r-   PRIMARYr   r5   r  r6   rs  r  r  r  rm  r  r  r  rr  rp  r  r  r  r   r  r  r  r  r   rT   rR   rP   r   r      si   1.21.:>1.IX1.^a1.f&!(J	>&#:@-W+W (W +	W
 
Wr 
 (6'='=&;@D.204*/,0+/(, %#37 %#W2W2 'W2 %	W2
 $W2 W2 >W2 ,W2 .W2 $(W2 *W2 )W2 &W2 W2 W2  1!W2" #W2$ 
%W2 W2r2 2d	-$):F	$ D	d+	d6M	d		d*<8)8 )8 &	8
 
8;
2'98'!
rR   r   c           
     "   U u  p#UR                  S5      (       aq  [        [        S5      (       d  [        S5      e[        R                  " [        R                  5      n[        UR                  5       5         UR                  U5        U$ [        R                  n[        R                  (       a  US:w  a  [        R                  nSn[        R                  " X#U[        R                  5       GH  nUu  ppn [        R                  " X[        [        SS5      -  U
5      n[        UR                  5       5         UR!                  [        R"                  [        R$                  S5        [&        R(                  " 5       nUc  UR*                  nOUS::  a  [        R,                  " S	5      eUR/                  U5        UR!                  [        R0                  [        R2                  S
5        [5        U5        UR                  U5        Us  $    Ub  Ue[        S5      e! [         a    UR                  5         e f = f! [         a    [        R                  " XU
5      n GN?f = f! [         a  nUnUR                  5          SnAGM  SnAff = f)zGiven (host, port) and PoolOptions, connect and return a socket object.

Can raise socket.error.

This is a modified version of create_connection from CPython >= 2.7.
z.sockAF_UNIXz-UNIX-sockets are not supported on this system	localhostNSOCK_CLOEXECr   rj   r   Tzgetaddrinfo failed)endswithrx   rq   r   r  rQ   filenoconnectr^   r  AF_INEThas_ipv6	AF_UNSPECgetaddrinfoSOCK_STREAMry   r|   r{   TCP_NODELAYr   r  r   r   r   
SOL_SOCKETSO_KEEPALIVErv   )r   r   r   r   rs   familyerrresafsocktypeprotodummysar   es                  rP   _create_connectionr    s    JD }}Wvy))#$STT}}V^^,'6	LLK ^^F4;.!!
C!!$ff6H6HI),&eB	6==PQ0R%RTYZD 	(6	OOF..0B0BAFoo'G!11Ann[11OOG$OOF--v/B/BDI &LLK3 J< 	 *++c  	JJL	&  	6 ==u5D	6&  	CJJLL	s7   9H :)H>=CI&H;>!I#"I#&
J0J		Jc           	     Z   [        X5      nUR                  nUc  UR                  UR                  5        U$ U S   n [        (       a  [
        (       a  UR                  X$S9nO[        US5      (       a  UR                  X$S9nO[        R                  " 5       nUR                  S[        R                  " UR                  X$S95      nOs[
        (       a  UR                  U5      nOV[        US5      (       a  UR                  U5      nO3[        R                  " 5       nUR                  SUR                  U5      n UR(                  (       aF  UR*                  (       d5  UR,                  (       d$   [.        R0                  " WR3                  5       US9  WR                  UR                  5        U$ ! [         a    UR                  5         e [         ["        4 a0  nUR                  5         [%        U5      n['        XSUS9   SnANSnAff = f! [         a    WR                  5         e f = f)zGiven (host, port) and PoolOptions, return a configured socket.

Can raise socket.error, ConnectionFailure, or _CertificateError.

Sets socket's SSL and timeout options.
Nr   )server_hostnamea_wrap_socketzSSL handshake failed: r  )hostname)r  _ssl_contextr   r   r1   _IS_SYNCwrap_socketrx   r   asyncioget_running_looprun_in_executor	functoolspartialr    r  r^   r2   r   r   verify_modecheck_hostnametls_allow_invalid_hostnamessslmatch_hostnamegetpeercert)	r   r   rs   ssl_contextr   ssl_sockloopexcr   s	            rP   _configured_socketr  W  s    g/D&&K../1:D#c 7x&2242N;88*888TH"335D#33!))+*A*A4^ H
 x&2248;88*88>H"335D#33D+:Q:QSWXH 	**33	x335E
 ../O1  

 	X c

 'w/!'0HZabc ! 	NN	sB   %F1 $ F1 AF1 
F1 '"F1 
2F1 1#H 1*H&HHH*c                      \ rS rSrSrSrg)_PoolClosedErrori  zRInternal error raised when a thread tries to get a connection from a
closed pool.
rT   N)r   r   r   r   r  r   rT   rR   rP   r  r    s    rR   r  c                  F    \ rS rSrS	S jrS
S jrSS jrSS jrSS jrSr	g)_PoolGenerationi  c                P    [         R                  " [        5      U l        SU l        g r]  )collectionsdefaultdictr]   _generations_generationr   s    rP   r   _PoolGeneration.__init__  s    1<1H1H1MrR   c                >    Uc  U R                   $ U R                  U   $ )z,Get the generation for the given service_id.r  r  r   r   s     rP   rQ  _PoolGeneration.get  s%    ###  ,,rR   c                    U R                   $ )z"Get the Pool's overall generation.)r  r   s    rP   r   _PoolGeneration.get_overall  s    rR   c                    U =R                   S-  sl         Uc+  U R                   H  nU R                  U==   S-  ss'   M     gU R                  U==   S-  ss'   g)z2Increment the generation for the given service_id.rj   Nr   r!  s     rP   inc_PoolGeneration.inc  sW    A"//
!!*-2- 0 j)Q.)rR   c                (    XR                  U5      :g  $ )z?Return if the given generation for a given service_id is stale.)rQ  r   r   r   s      rP   stale_PoolGeneration.stale  s    hhz***rR   r   Nr   )r   Optional[ObjectId]r   r]   r  )r   r,  r   r   r   r]   r   r,  r   r   )
r   r   r   r   r   rQ  r   r&  r*  r   rT   rR   rP   r  r    s    - /+rR   r  c                       \ rS rSrSrSrSrSrg)	PoolStatei  rj         rT   N)r   r   r   r   PAUSEDREADYCLOSEDr   rT   rR   rP   r/  r/    s    FEFrR   r/  c                  R   \ rS rSr  S       SS jjrSS jr\SS j5       r   S         SS jjrSS jr	 S     SS jjr
SS	 jrSS
 jrSS jrS S jrS!S"S jjr\R"                   S!   S#S jj5       rS$S jr S!     S%S jjrS&S jrS'S jrS(S jrSS jrSrg))r  i  Nc                   UR                   (       a  [        R                  U l        O[        R                  U l        SU l        [        R                  " 5       U l        [        5       U l
        [        5       n[        U5      U l        SU l        SU l        SU l        [#        5       U l        [&        R(                  " 5       U l        Xl        X l        X0l        U R0                  =(       a?    U R.                  R2                  SL=(       a     U R.                  R2                  R4                  U l        U R0                  U l        [8        R:                  " U5      U l        SU l        U R.                  R@                  U l         U R@                  (       d  [C        S5      U l         [8        R:                  " U5      U l"        U R.                  RF                  U l$        SU l%        X@l&        U R4                  (       a]  U R.                  R2                  c   eU R.                  R2                  RO                  U R,                  U R.                  RP                  5        U R6                  (       a  [R        RT                  " [V        RX                  5      (       a[  [[        [R        4U RL                  [\        R^                  U R,                  S   U R,                  S   S.U R.                  RP                  D6  SU l0        [        5       U l1        SU l2        SU l3        g)z
:param address: a (hostname, port) tuple
:param options: a PoolOptions instance
:param handshake: whether to call hello for each new Connection
rj   r   Ninfr  r  r  r  )4pause_enabledr/  r2  stater3  _check_interval_secondsr  dequeconnssetactive_contextsr#   r$   lockactive_socketsnext_connection_idr   r  r   osgetpidpidr   r   	handshaker   r   r   	threading	Condition	size_condrequestsmax_pool_sizer  _max_connecting_condmax_connecting_max_connecting_pendingr   publish_pool_creatednon_default_optionsr%   r  r  r  r'   r&   POOL_CREATEDoperation_count_Pool__pinned_socketsncursorsntxns)r   r   r   rF  	client_id_locks         rP   r   Pool.__init__  s8      "))DJ"DJ ()$ )4(9(9(;
:=%%L	"#+/
 #$99;	" NN <		**$6<		**;; 	
 $(>> 
 #,,U3!YY44!!!&uD %.$7$7$>!#yy77#  99--999II&&;;dii;; ##(:(G(G(V(V"0==<<?<<? ))// %& 25
rR   c           	     b   U R                      U R                  [        R                  :w  a  [        R                  U l        U R                  (       aH  U R
                  R                  c   eU R
                  R                  R                  U R                  5        U R                  (       al  [        R                  " [        R                  5      (       aC  [        [        U R                  [         R"                  U R                  S   U R                  S   S9  S S S 5        g ! , (       d  f       g = f)Nr   rj   r8  )r@  r:  r/  r3  r   r   r   publish_pool_readyr   r   r%   r  r  r  r'   r   r&   
POOL_READYr   s    rP   r   
Pool.ready  s    YYzzY__,&__
((9955AAAII..AA$,,O++0B0O0OPWP]P]0^0^*!% 8 C C#'<<?#'<<? YYs   D
D  
D.c                <    U R                   [        R                  :H  $ rZ   )r:  r/  r4  r   s    rP   r   Pool.closed.  s    zzY----rR   c           	         U R                   nU R                     U R                  (       a
   S S S 5        g U R                  R                  (       aC  U(       a<  U R                  R
                  (       d!  U R                   [        R                  soPl         U R                  R                  U5        [        R                  " 5       nU R                  U:w  a  X`l        SU l        SU l        Uc'  U R                  [         R"                  " 5       sopl        Oy[         R"                  " 5       n[         R"                  " 5       n	U R                   H7  n
U
R$                  U:X  a  UR'                  U
5        M&  U	R'                  U
5        M9     UnXl        U(       a  [        R(                  U l         U R*                  R-                  5         U R                  R-                  5         U(       a#  U R.                   H  nUR1                  5         M     S S S 5        U R                  R2                  nU(       a  W H"  n
U
R5                  [6        R8                  5        M$     U R:                  (       a   Uc   eUR=                  U R>                  5        U R@                  (       an  [B        RD                  " [F        RH                  5      (       aD  [K        [B        U RL                  [N        R8                  U R>                  S   U R>                  S   S9  g g g U[        R                  :w  a  U R:                  (       a   Uc   eURQ                  U R>                  UUS9  U R@                  (       am  [B        RD                  " [F        RH                  5      (       aD  [K        [B        U RL                  [N        RR                  U R>                  S   U R>                  S   US9  W H"  n
U
R5                  [6        RT                  5        M$     g ! , (       d  f       GN= f)Nr   rj   r8  )r   interrupt_connections)r  r  r  r  	serviceId)+r:  rI  r   r   r9  r  r/  r2  r   r&  rC  rD  rE  rA  rS  r=  r  r<  r   appendr4  rL  
notify_allr?  r   r   r  r*   POOL_CLOSEDr   publish_pool_closedr   r   r%   r  r  r  r'   r   r&   publish_pool_clearedPOOL_CLEAREDr  )r   r  pauser   ra  	old_statenewpidsocketsdiscardkeepr   contextr   s                rP   _resetPool._reset2  s    JJ	^^{{ ^ yy&&59P9P(,

I4D4D%	:HHLL$YY[Fxx6!!&'#'($!&*jj+2C2C2E#-8->->-@*5*;*;*= JJD*4t,D)	 '
 "!
&--
%%002NN%%'$#33GNN$  4? D II..	  6 B BC  $$ ,,,--dll;'',>,K,KGMM,Z,Z&!__4@@#||A#||A -[' I,,,(($00022#-.C 3 
 ++0B0O0OPWP]P]0^0^*!% 8 E E#'<<?#'<<?",   6 < <=  M ^s   O.GO..
O=c                    Xl         U R                     U R                   H  nUR                  U R                   5        M      SSS5        g! , (       d  f       g= f)zHUpdates the is_writable attribute on all sockets currently in the
Pool.
N)r   r@  r=  r  )r   r   _sockets      rP   r  Pool.update_is_writable  s=     'YY::**4+;+;< & YYs   /A
Ac                $    U R                  SXS9  g )NF)r  r   ra  rp  )r   r   ra  s      rP   reset
Pool.reset  s     	%JdrR   c                $    U R                  SSS9  g )NF)r  ri  rv  r   s    rP   reset_without_pausePool.reset_without_pause  s    %u-rR   c                "    U R                  SS9  g )NT)r  rv  r   s    rP   r  
Pool.close  s    $rR   c                8    U R                   R                  X5      $ rZ   )r   r*  r)  s      rP   stale_generationPool.stale_generation  s    xx~~c..rR   c                   U R                      U R                  [        R                  :w  a
   SSS5        g SSS5        U R                  R
                  b  U R                      U R                  (       a  U R                  S   R                  5       U R                  R
                  :  a  U R                  R                  5       nUR                  [        R                  5        U R                  (       a7  U R                  S   R                  5       U R                  R
                  :  a  M  SSS5         U R                     [        U R                  5      U R                  -   U R                  R                  :  a
   SSS5        gU R                   U R                  R                  :  a
   SSS5        gU =R                   S-  sl        SSS5        Sn U R"                     U R$                  U R&                  :  a   SSS5        U(       aD  U R"                     U =R$                  S-  sl        U R"                  R)                  5         SSS5        U R                     U =R                   S-  sl        U R                  R)                  5         SSS5        gU =R$                  S-  sl        SnSSS5        U R+                  5       nU R                      U R,                  R/                  5       U:w  a  UR                  [        R0                  5         SSS5        U(       aD  U R"                     U =R$                  S-  sl        U R"                  R)                  5         SSS5        U R                     U =R                   S-  sl        U R                  R)                  5         SSS5        gU R                  R3                  U5        U R4                  R7                  UR8                  5        SSS5        U(       aD  U R"                     U =R$                  S-  sl        U R"                  R)                  5         SSS5        U R                     U =R                   S-  sl        U R                  R)                  5         SSS5        GMK  ! , (       d  f       GNN= f! , (       d  f       GNm= f! , (       d  f       GN= f! , (       d  f       GNv= f! , (       d  f       g= f! , (       d  f       GN5= f! , (       d  f       GN= f! , (       d  f       g= f! , (       d  f       GN/= f! , (       d  f       N= f! , (       d  f       N= f! U(       aV  U R"                     U =R$                  S-  sl        U R"                  R)                  5         SSS5        O! , (       d  f       O= fU R                     U =R                   S-  sl        U R                  R)                  5         SSS5        f ! , (       d  f       f = f= f)zRemoves stale sockets then adds new ones if pool is too small and
has not been reset. The `reference_generation` argument specifies the
`generation` at the point in time this operation was requested on the
pool.
Nr   Trj   F)r@  r:  r/  r3  r   max_idle_time_secondsr=  r  popr  r*   IDLErI  lenrA  min_pool_sizerJ  rL  rO  rN  notifyr  r   r   r  
appendleftr?  rm  r   )r   reference_generationr   incrementeds       rP   remove_stale_socketsPool.remove_stale_sockets  s    YYzzY__, Y,  99**6JJ

288:TYY=\=\\::>>+DOO$:$?$?@	 JJ

288:TYY=\=\\  tzz?T%8%88DII<S<SS   ==DII$;$;;   "    K,.. }}(<(<<	 /" 22*1188: 3 ^^MMQ&MNN))+ $^% MMQ&M"&K / ||~YY xx++-1EE(>(D(DE  22*1188: 3 ^^MMQ&MNN))+ $^ JJ))$/((001D1DE  22*1188: 3 ^^MMQ&MNN))+ $C  Y
   8 32 $^/ /.& 32 $^ Y 32 $^ 22*1188: 322 ^^MMQ&MNN))+ $^^s    Q>"CR?<R"%R"2R"U  S:U  0R40SS)$U  ?TU  '0S)+0S;$A T$U  ?0T0T/>
R
R"
R14
S
S
S&!U  )
S8;
T	
TU  
T,/
T= W40V	W4
VW4*0W#	W4#
W1-W4c                   U R                      U R                  nU =R                  S-  sl        SSS5        U R                  R                  nU R                  (       a!  Uc   eUR                  U R                  W5        U R                  (       am  [        R                  " [        R                  5      (       aD  [        [        U R                  [        R                  U R                  S   U R                  S   WS9   [!        U R                  U R                  5      n[;        X@U R                  W5      nU R                      U R<                  R?                  UR@                  5        SSS5         U RB                  (       a!  URE                  5         URF                  U l#        U(       a  URI                  USS9  URK                  5         U$ ! , (       d  f       GN= f! ["         Ga5  nU R                  (       a0  Uc   eUR%                  U R                  W[&        R(                  5        U R                  (       a  [        R                  " [        R                  5      (       ak  [        [        U R                  [        R*                  U R                  S   U R                  S   W[-        [&        R(                  5      [&        R(                  S9  [/        U[0        [2        [4        45      (       a)  [7        U R                  5      n[9        U R                  XVS9  e SnAff = f! , (       d  f       GN= f! ["         a!    URM                  [&        R(                  5        e f = f)	zConnect to Mongo and return a new Connection.

Can raise ConnectionFailure.

Note that the pool does not keep a reference to the socket -- you
must call checkin() when you're done with it.
rj   Nr   r  r  r  r  r  r  r  F)completed_handshake)'r@  rB  r   r   r   publish_connection_createdr   r   r%   r  r  r  r'   r   r&   CONN_CREATEDr  rt  r  r*   r  r  r(   r   r  r^   r2   r   r   r   r?  addr   rF  r&  r   contribute_socketr  r  )r   handlerconn_idr   rs   r   r   r   s           rP   r  Pool.connect  su    YY--G##q(#  II..	  (((00wG##(:(G(G(V(V"0==<<?<<?#*	%dllDII>D0 $dllG<YY  $$T%8%89 
	~~

#'#3#3 ))$E)J
 u Y(  	$$ ,,,33LL'+A+G+G '',>,K,KGMM,Z,Z&!__4@@#||A#||A'.;<R<X<XY066	 %'7H!=>>.tyy9)$,,W+	0 Y  	OO2889	s=   "G> G &L 0AL2 
GL(D0LL 
L/2+Mc           
   #  ,  #    U R                   R                  n[        R                  " 5       nU R                  (       a   Uc   eUR                  U R                  5        U R                  (       al  [        R                  " [        R                  5      (       aC  [        [        U R                  [        R                  U R                  S   U R                  S   S9  U R!                  X1S9n[        R                  " 5       U-
  nU R                  (       a,  Uc   eUR#                  U R                  UR$                  U5        U R                  (       ax  [        R                  " [        R                  5      (       aO  [        [        U R                  [        R&                  U R                  S   U R                  S   UR$                  US9   U R(                     U R*                  R-                  UR.                  5        SSS5        Uv   UR2                  (       aF  U R(                     U R@                  R-                  U5        U =RB                  S-  sl!        SSS5        gUR4                  (       aF  U R(                     U R@                  R-                  U5        U =RD                  S-  sl"        SSS5        gUR<                  (       a  U R?                  U5        gg! , (       d  f       N= f! [0         az    UR2                  =(       d    UR4                  nU(       a)  [6        R8                  " 5       u  pxn	UR;                  Xx5        U(       d"  UR<                  (       a  U R?                  U5        e f = f! , (       d  f       g= f! , (       d  f       g= f7f)a  Get a connection from the pool. Use with a "with" statement.

Returns a :class:`Connection` object wrapping a connected
:class:`socket.socket`.

This method should always be used in a with-statement::

    with pool.get_conn() as connection:
        connection.send_message(msg)
        data = connection.receive_message(op_code, request_id)

Can raise ConnectionFailure or OperationFailure.

:param handler: A _MongoClientErrorHandler.
Nr   rj   r8  r  r  )#r   r   r   r   r   $publish_connection_check_out_startedr   r   r%   r  r  r  r'   r   r&   CHECKOUT_STARTED	_get_connpublish_connection_checked_outr   CHECKOUT_SUCCEEDEDr@  r?  r  r   rt  r   r   sysexc_infohandler   r  rT  rV  rU  )
r   r  r   checkout_started_timer   r  pinnedexc_typeexc_valrd   s
             rP   checkoutPool.checkout  sy    & II..	 $ 0  (((::4<<H##(:(G(G(V(V"0AA<<?<<? ~~3~E>>#&;;  (((44T\\477HU##(:(G(G(V(V"0CC<<?<<?#'77#	$$(()<)<= J ??%%))$/

a
  %%))$/"  [[LL 3   	
 __:(:(:F (+||~$1x1dkkT"	  sg   GN
K+ &K<K+ N%1M2&N<1N--N
K($K+ +BM//N2
N <N
NNc                   U R                   [        R                  :w  GaK  U(       Ga  [        R                  " 5       U-
  nU R
                  (       aX  U R                  R                  c   eU R                  R                  R                  U R                  [        R                  U5        U R                  (       a}  [        R                  " [        R                   5      (       aT  [#        [        U R$                  [&        R(                  U R                  S   U R                  S   S[        R                  US9  [+        U R                  5      n[-        U R                  [/        S5      US9  g g )Nr   rj   <An error occurred while trying to establish a new connectionr  r  r  r  r  r   r  zconnection pool pausedr  )r:  r/  r3  r   r   r   r   r   #publish_connection_check_out_failedr   r)   
CONN_ERRORr   r%   r  r  r  r'   r   r&   CHECKOUT_FAILEDr   r   r   )r   r  
emit_eventr  r   s        rP   _raise_if_not_readyPool._raise_if_not_readye  s   ::(>>+.CC((9955AAAII..RR&D&O&OQY ++0B0O0OPWP]P]0^0^*!% 8 H H#'<<?#'<<?]<GG#+	 +4995G%m,DEW^+ )rR   c                   U R                   [        R                  " 5       :w  a  U R                  5         U R                  (       Ga  [
        R                  " 5       U-
  nU R                  (       aX  U R                  R                  c   eU R                  R                  R                  U R                  [        R                  U5        U R                  (       a}  [        R                   " ["        R$                  5      (       aT  ['        [        U R(                  [*        R,                  U R                  S   U R                  S   S[        R                  US9  [/        S5      eU R0                     U =R2                  S-  sl        SSS5        [4        R6                  " 5       (       a  [4        R8                  " 5       nOJU R                  R:                  (       a-  [
        R                  " 5       U R                  R:                  -   nOSnU R<                     U R?                  USS9  U R@                  U RB                  :  d  [E        U R<                  U5      (       dE  U R@                  U RB                  :  a  U R<                  RG                  5         U RI                  U5        U R?                  USS9  U R@                  U RB                  :  d  M  U =R@                  S-  sl         SSS5        SnS	nS	n U R0                     U =RJ                  S-  sl%        SnSSS5        UGc  U RL                     U R?                  US	S9  U RN                  (       d  U RP                  U RR                  :  d  [E        U RL                  U5      (       dX  U RN                  (       d  U RP                  U RR                  :  a  U RL                  RG                  5         SnU RI                  U5        U R?                  US	S9  U RN                  (       d  U RP                  U RR                  :  d  M   U RN                  RU                  5       nSSS5        U(       a  U RY                  U5      (       a  SnGMA  OT U R[                  US
9nU RL                     U =RP                  S-  sl(        U RL                  RG                  5         SSS5        Uc  GM  SUl3        U$ ! , (       d  f       GNA= f! , (       d  f       GN= f! , (       d  f       GN= f! [V         a    U =RP                  S-  sl(         Nf = f! , (       d  f       N= f! , (       d  f       N= f! U RL                     U =RP                  S-  sl(        U RL                  RG                  5         SSS5        f ! , (       d  f       f = f= f! [\         Ga    U(       a  UR_                  [`        Rb                  5        U R<                     U =R@                  S-  sl         U(       a  U =RJ                  S-  sl%        U R<                  RG                  5         SSS5        O! , (       d  f       O= fU(       Gd  [
        R                  " 5       U-
  nU R                  (       aX  U R                  R                  c   eU R                  R                  R                  U R                  [        Rd                  U5        U R                  (       a}  [        R                   " ["        R$                  5      (       aT  ['        [        U R(                  [*        R,                  U R                  S   U R                  S   S[        Rd                  US9  e f = f)z8Get or create a Connection. Can raise ConnectionFailure.Nr   rj   zConnection pool was closedr  z?Attempted to check out a connection from closed connection poolT)r  Fr  r  )4rE  rC  rD  rz  r   r   r   r   r   r   r  r   r)   re  r   r%   r  r  r  r'   r   r&   r  r  r@  rS  r   r   get_deadlinewait_queue_timeoutrI  r  rJ  rK  r   r  _raise_wait_queue_timeoutrA  rL  r=  rO  rN  popleft
IndexError	_perishedr  rt  r  r*   r  r  r   )r   r  r  r  r   r   r  emitted_events           rP   r  Pool._get_conn  sN    88ryy{"$$&;;;~~'*??H$$yy11===		**NNLL"@"L"Lh '',>,K,KGMM,Z,Z&!__4DD#||A#||A78DD'	 #Q  YY  A%   ))+HYY))~~'$))*F*FFHH^^$$%:t$L}}t'9'99!$..(;; }}t'9'99--/223HI(()>4(P }}t'9'99 MMQM  >	##q(#"  , ..,,-Bu,U#zzT]]T=Q=Q-Q)$*C*CXNN  $zzT]]T=Q=Q-Q $ 9 9 @ @ B,0M ::;PQ001FSX0Y  $zzT]]T=Q=Q-Q+#zz113 /  ~~d++#  ,?#||G|<!66 MMQ.M 55<<> 77 ,x y Y ^" ( & +*+ /.0 76T66 MMQ.M 55<<> 766  	 6 < <="''1,'%%'	   !>>+.CC((9955AAAII..RR&D&O&OQY ++0B0O0OPWP]P]0^0^*!% 8 H H#'<<?#'<<?]<GG#+	 9	s   ,R<B5SS+V 7S V 'C*TS2.+V T9 )V 50T(%V <
S
S 
S/*V 2TTTT
T%!V (
T62V 9V0U?6	V?
V	VV =]AX%	]%
X3	/D ]c                   UR                   nUR                  nSUl        SUl         SUl        U R                  R	                  U5        U R
                  R                  nU R                     U R                  R	                  UR                  5        SSS5        U R                  (       a+  Uc   eUR                  U R                  UR                  5        U R                  (       aw  [        R                   " ["        R$                  5      (       aN  ['        [        U R(                  [*        R,                  U R                  S   U R                  S   UR                  S9  U R.                  [0        R2                  " 5       :w  a  U R5                  5         GOU R6                  (       a!  UR9                  [:        R<                  5        GOUR6                  (       a  U R                  (       a:  Uc   eUR?                  U R                  UR                  [:        R@                  5        U R                  (       a  [        R                   " ["        R$                  5      (       au  ['        [        U R(                  [*        RB                  U R                  S   U R                  S   UR                  [E        [:        R@                  5      [:        R@                  S9  OU R                     U RG                  URH                  URJ                  5      (       a   UR9                  [:        RL                  5        OiURO                  5         URQ                  [S        U RT                  5      5        U RV                  RY                  U5        U RZ                  R]                  5         SSS5        U R^                     U(       a  U =R`                  S-  sl0        OU(       a  U =Rb                  S-  sl1        U =Rd                  S-  sl2        U =Rf                  S-  sl3        U =Rh                  S-  sl4        U R^                  R]                  5         SSS5        g! , (       d  f       GN= f! , (       d  f       N= f! , (       d  f       g= f)zvReturn the connection to the pool, or if it's closed discard it.

:param conn: The connection to check into the pool.
FNr   rj   r  r  )5r   r   r   rT  rm  r   r   r@  r?  r   r   publish_connection_checked_inr   r   r   r%   r  r  r  r'   r   r&   	CHECKEDINrE  rC  rD  rz  r   r  r*   re  r  r  r  r(   r  r   r   r  r  r  r   r   r=  r  rL  r  rI  rV  rU  rJ  rA  rS  )r   r   txncursorr   s        rP   r  Pool.checkin  s   
 oo##"%%d+II..	YY  (()<)<=   (((33DLL$''J##(:(G(G(V(V"0::<<?<<?#'77 88ryy{"$$&{{ 6 B BC(($00077dgg/E/K/K ++0B0O0OPWP]P]0^0^*!% 8 D D#'<<?#'<<?+/77?@V@\@\]4::	 YY ,,T__dooNN(>(D(DE557//T5E5E0FG

--d31188:  ^^

a
"MMQM1$  A% NN!!# ^e YL Y ^s&   +&QB5Q%BQ$
Q
Q!$
Q2c                   UR                  5       nU R                  R                  b9  X R                  R                  :  a   UR                  [        R
                  5        gU R                  bT  U R                  S:X  d  X R                  :  a5  UR                  5       (       a   UR                  [        R                  5        gU R                  UR                  UR                  5      (       a   UR                  [        R                  5        gg)aY  Return True and close the connection if it is "perished".

This side-effecty function checks if this socket has been idle for
for longer than the max idle time, or if the socket has been closed by
some external network error, or if the socket's generation is outdated.

Checking sockets lets us avoid seeing *some*
:class:`~pymongo.errors.AutoReconnect` exceptions on server
hiccups, etc. We only check if the socket was closed by an external
error if it has been > 1 second since the socket was checked into the
pool, to keep performance reasonable - we can't avoid AutoReconnects
completely anyway.
Tr   F)r  r   r  r  r*   r  r;  r  r  r  r   r   r  )r   r   r  s      rP   r  Pool._perishedE  s     !224 II++7!II$C$CCOO2778''3((A-1BEaEa1a!! 6 < <=  $//BBOO2889rR   c                   U R                   R                  n[        R                  " 5       U-
  nU R                  (       a0  Uc   eUR                  U R                  [        R                  U5        U R                  (       a}  [        R                  " [        R                  5      (       aT  [        [        U R                  [         R"                  U R                  S   U R                  S   S[        R                  US9  [$        R&                  " 5       =(       d    U R                   R(                  nU R                   R*                  (       al  U R,                  U R.                  -
  U R0                  -
  n[3        SR5                  U R                   R6                  U R.                  U R0                  UU5      5      e[3        SU R                   R6                   SU 35      e)Nr   rj   zBWait queue timeout elapsed without a connection becoming availabler  zTimeout waiting for connection from the connection pool. maxPoolSize: {}, connections in use by cursors: {}, connections in use by transactions: {}, connections in use by other operations: {}, timeout: {}zMTimed out while checking out a connection from connection pool. maxPoolSize: z, timeout: )r   r   r   r   r   r  r   r)   TIMEOUTr   r%   r  r  r  r'   r   r&   r  r   r   r  r  rA  rU  rV  r   r  rK  )r   r  r   r  r   	other_opss         rP   r  Pool._raise_wait_queue_timeouti  sp   II..	>>#&;;  (((99<DDh ##(:(G(G(V(V"0@@<<?<<?[4<<#	 ##%E)E)E99""++dmm;djjHI'7 8>vII++MMJJ8	  $ II334KyJ
 	
rR   c                L    U R                    H  nUR                  S 5        M     g rZ   )r=  r  )r   r   s     rP   __del__Pool.__del__  s     JJDOOD! rR   )__pinned_socketsr;  r   rN  rL  rO  r?  rA  r   r=  r   r   r   rF  r   r@  rK  rU  rB  rV  rS  r   rE  rJ  rI  r:  )TN)r   rF   r   r,   rF  r   rW  r,  r   r   )TNF)
r  r   ri  r   r   r,  ra  r   r   r   )r   zOptional[bool]r   r   r   )r   r,  ra  r   r   r   r-  )r  r]   r   r   rZ   )r  "Optional[_MongoClientErrorHandler]r   r   )r  r  r   zGenerator[Connection, None])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   r   r   r   r   r   r   r   rp  r  rw  rz  r  r  r  r  
contextlibcontextmanagerr  r  r  r  r  r  r  r   rT   rR   rP   r  r    s\   
 (,TT T 	T
 &Tl" . . )-&+O>O> O> '	O>
  $O> 
O>b= TYe,eLPe	e
. /7,rBH <@K9K	$K KZ6 [_|%*|5W|	||F$P"H%
N"rR   r  )rN   r]   r   r   )rs   socket.socketr}   r   r~   r]   r   r   )rs   r  r   r   )NN)
r   r   r   r  r   r  r   Optional[dict[str, float]]r   r	   )r   zthreading.Conditionr   r  r   r   )r   r,   r   zdict[str, float])r   r  r   r   )r   rF   r   r,   r   r  )r   rF   r   r,   r   r  )
__future__r   r  r  r  r  r  rC  rq   r  r  rG  r   r   typingr   r   r   r   r   r	   r
   r   r   bsonr   pymongor   r   pymongo.commonr   r   r   r   r   pymongo.errorsr   r   r   r   r   r   r   r   r   r   r   r    pymongo.hellor!   r"   pymongo.lockr#   r$   pymongo.loggerr%   r&   r'   r(   pymongo.monitoringr)   r*   pymongo.network_layerr+   pymongo.pool_optionsr,   pymongo.read_preferencesr-   pymongo.server_apir.   pymongo.server_typer/   pymongo.socket_checkerr0   pymongo.ssl_supportr1   r2   "pymongo.synchronous.client_sessionr3   pymongo.synchronous.helpersr4   pymongo.synchronous.networkr5   r6   r7   bson.objectidr8   pymongo.compression_supportr9   r:   r;   pymongo.messager<   r=   pymongo.pyopenssl_contextr>   pymongo.read_concernr?   r@   pymongo.synchronous.authrA   rB    pymongo.synchronous.mongo_clientrC   rD   pymongo.typingsrE   rF   rG   pymongo.write_concernrH   rL   rI   rJ   rK   rQ   ImportErrorr  rm   ro   r   platform_winregr[   re   OpenKeyHKEY_LOCAL_MACHINEr`   rl   rn   r^   rv   r   r   r   r   r   r   r   r  r  r  r  r/  r  rT   rR   rP   <module>r     sT   #      	  
 
   
 
 
 ' )     - ,  * , 3 . + 0 1 N 6 @!& 
 12045@VCC2E99/    <<7 
(^^%%'\
#)##H '-c3F'M$	
M? !%26	,,, , 0	,
 ,:#
	 M
 M
`D,N?D| + +> O" O"k  EE	E"  
 

  (  '#' 	(sT   H( /H9 7I I	)I (H65H69
II	
II I 
I'&I'