
    l8'h                      d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlZd dlZd dlmZmZmZmZmZmZmZmZmZ d dlmZ d dlmZmZ d dlmZ d dlm Z  d dl!m"Z"m#Z# d d	l$m%Z%m&Z&m'Z'm(Z(m)Z) d d
l*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6 d dl7m8Z8m9Z9 d dl:m;Z;m<Z<m=Z= d dl>m?Z?m@Z@mAZAmBZB d dlCmDZDmEZE d dlFmGZG d dlHmIZI d dlJmKZK d dlLmMZM d dlNmOZO d dlPmQZQ d dlRmSZSmTZT erTd dlmUZU d dlVmWZW d dlXmYZY d dlmZZZ d dl[m\Z\m]Z] d dl^m_Z_m`Z`maZa d dlbmcZcmdZd d dlemfZf d dlgmhZh d dlJmiZi d d ljmkZkmlZlmmZm d d!lnmoZo 	 d d"lpmqZqmrZrmsZsmpZp dEd#Ztd%Zvd&Zwd'Zxd(Zye
j                  d)k(  rG	 d dl{Z|d* Z}	  e|j                  e|j                  d+      5 Z e}ed,d-      Z e}ed.d/      Zddd       d0 ZndFd1ZdGd2Z	 	 dH	 	 	 	 	 	 	 	 	 dId3ZdJd4ZdKd5ZdLd6Z G d7 d8      Z G d9 d:      ZdMd;Z	 	 	 	 	 	 dNd<Z G d= d>e4      Z G d? d@      Z G dA dB      Z G dC dD      Zy# eu$ r dEd$ZtY w xY w# eu$ r d dl|Z|Y w xY w# 1 sw Y   xY w# e$ r d-Zd/ZY w xY w)O    )annotationsN)	TYPE_CHECKINGAnyAsyncGeneratorMappingMutableMappingNoReturnOptionalSequenceUnion)DEFAULT_CODEC_OPTIONS)_csothelpers_shared)_validate_session_write_concern)_handle_reauth)commandreceive_message)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)_ACondition_ALock_create_lock)_CONNECTION_LOGGER_ConnectionStatusMessage
_debug_log _verbose_connection_error_reason)ConnectionCheckOutFailedReasonConnectionClosedReason)async_sendall)PoolOptions)ReadPreference)_add_to_command)SERVER_TYPE)SocketChecker)HAS_SNISSLError)CodecOptions)ObjectId)_AuthContext)AsyncClientSession)AsyncMongoClient_MongoClientErrorHandler)SnappyContextZlibContextZstdContext)_OpMsg_OpReply)_sslConn)ReadConcern)_ServerMode)ClusterTime_Address_CollationIn)WriteConcern)F_GETFDF_SETFD
FD_CLOEXECfcntlc                T    t        | t              }t        | t        |t        z         y)z8Set the close-on-exec flag on the given file descriptor.N)rM   rJ   rK   rL   )fdflagss     U/var/www/html/trade_iq/venv/lib/python3.12/site-packages/pymongo/asynchronous/pool.py_set_non_inheritable_non_atomicrR   l   s    b'"b'5:-.    c                     y)z6Dummy function for platforms that don't provide fcntl.N )rO   s    rQ   rR   rR   u   s    rS   Fx   
   	   win32c                z    	 t        j                  | |      \  }}t        |      S # t        t        f$ r |cY S w xY wN)winregQueryValueExintOSError
ValueError)keynamedefaultvalue_s        rQ   _queryrf      sB    	**35HE1u:$ 	 N	s   #& ::z2SYSTEM\CurrentControlSet\Services\Tcpip\ParametersKeepAliveTimei m KeepAliveInterval  c                    t        t        t        dz        }t        t        t        dz        }|t        k  s	|t        k  r$| j                  t        j                  d||f       y y )Nri      )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      rQ   _set_keepalive_timesrw      sZ    *,=,DE24F4MN))[;S-SJJv001g{2KL .TrS   c                    t        t        |      rYt        t        |      }	 | j                  t        j                  |      }||kD  r"| j                  t        j                  ||       y y y # t        $ r Y y w xY wr[   )hasattrrr   getattr
getsockoptIPPROTO_TCP
setsockoptr_   )rt   
tcp_option	max_valuesockoptrc   s        rQ   _set_tcp_optionr      sq    6:&fj1G //&*<*<gFY&OOF$6$6K ' '  s   AA+ +	A76A7c                j    t        | dt               t        | dt               t        | dt               y )NTCP_KEEPIDLETCP_KEEPINTVLTCP_KEEPCNT)r   rn   rp   _MAX_TCP_KEEPCNT)rt   s    rQ   rw   rw      s)    n.?@o/ABm-=>rS   c                   | \  }}|	d|||fz  }n| d| }|r||z   }d|vr|t        |      z  }t        |t        j                        rt	        |      |t        |t
              rdt        |      v rt	        |      |t        |      |)z9Convert a socket.error to ConnectionFailure and raise it.z	%s:%d: %s: zconfigured timeouts	timed out)format_timeout_details
isinstancerr   timeoutr   r7   strr   )addresserror
msg_prefixtimeout_detailshostportmsgs          rQ   _raise_connection_failurer      s     JD$T4//b 3C'%o66%(S!u,	E8	$E
)B
 S!u,C e+rS   c                v   K   |r|t        j                         z
  nd }| j                  |       d {   S 7 wr[   )time	monotonicwait)	conditiondeadliner   s      rQ   
_cond_waitr      s0     -5h))4G((((s   0979c                    i }t        j                         }| j                  }| j                  }|r|dz  |d<   |r
|s|dz  |d<   |r|dz  |d<   |S )Nri   	timeoutMSsocketTimeoutMSconnectTimeoutMS)r   get_timeoutsocket_timeoutconnect_timeout)optionsdetailsr   r   r   s        rQ   _get_timeout_detailsr      si    G!G++N--O&~g%3d%:!"&5&<"#NrS   c                b    d}| r*|dz  }dD ]  }|| v s|d| d| |    dz  } |d d }|dz  }|S )	N z (configured timeouts:)r   r   r    r   zms,)rU   )r   resultr   s      rQ   r   r      sf    F**K 	?G'!AgYb)9(:#>>	? #MrS   c                  .    e Zd ZddZddZedd       Zy)_CancellationContextc                    d| _         y NF
_cancelledselfs    rQ   __init__z_CancellationContext.__init__   s	    rS   c                    d| _         y)zCancel this context.TNr   r   s    rQ   cancelz_CancellationContext.cancel   s	    rS   c                    | j                   S )zWas cancel called?r   r   s    rQ   	cancelledz_CancellationContext.cancelled   s     rS   NreturnNoner   bool)__name__
__module____qualname__r   r   propertyr   rU   rS   rQ   r   r      s        rS   r   c                     e Zd Z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eej                   eddddddddddddf	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d+d       Zd,dZd-dZd.dZd/dZ	 	 	 	 	 	 	 	 d0dZd1d2dZ	 	 	 	 	 	 d3dZd4dZd'dZd5dZ	 	 	 	 	 	 	 	 d6dZd7dZd'dZd8dZ d9dZ!d:dZ"d;d Z#d;d!Z$d<d"Z%d=d#Z&y)>AsyncConnectionzStore 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                   t        j                  |      | _        || _        || _        || _        d| _        t        j                         | _	        d| _
        d| _        t        | _        t        | _        t         | _        t$        | _        d| _        d| _        d| _        d| _        |j0                  j2                  | _        |j6                  | _        |j8                  | _        |j0                  j:                  | _        d | _        tA               | _!        d | _"        d | _#        d | _$        |jJ                  | _&        | jL                  jO                         | _(        d| _)        tU               | _+        |j0                  | _        d| _,        d | _-        d | _.        d| _/        d| _0        d| _1        | j0                  jd                  | _3        d| _4        |jj                  | _5        t        j                         | _6        y )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_contextr5   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        rQ   r   zAsyncConnection.__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//!^^-rS   c                h    || j                   k(  ry|| _         | j                  j                  |       y)z?Cache last timeout to avoid duplicate calls to conn.settimeout.N)r   r   
settimeout)r   r   s     rQ   set_conn_timeoutz AsyncConnection.set_conn_timeout<  s-    d'''#		W%rS   c                   t        j                         }|2| j                  s%| j                  | j                  j
                         y t        j                         }|| j                  }||z
  }|dk  rIt        | j                        }t        |      }d|dd|dd| }t        |dd|dd| j                        |t        |dz        |d	<   | j                  |       |S )
Nr   z5operation would exceed time limit, remaining timeout:z.5fz <= network round trip time:r   2   okerrmsgcoderi   	maxTimeMS)r   	remainingr   r   r   r   get_rttr   r   r   r   r   r^   )	r   clientcmdr   rttmax_time_msr   	formattedr   s	            rQ   apply_timeoutzAsyncConnection.apply_timeoutC  s     //#?$$%%dii&>&>?mmo;""Cm?2499=O.?ILWUXMYuvyz}u~~  AJ  @K  LF"FB7%%	  ?";#56Cg&rS   c                .    d| _         | j                  rJ y NT)r   r   r   s    rQ   pin_txnzAsyncConnection.pin_txnb  s    %%%%%rS   c                .    d| _         | j                  rJ y r  )r   r   r   s    rQ   
pin_cursorzAsyncConnection.pin_cursorf  s    !??""?rS   c                   K   | j                         }|r|j                  |        d {    y | j                  t        j                         y 7 %wr[   )r   checkin
close_connr/   STALE)r   r   s     rQ   unpinzAsyncConnection.unpinj  s>     }},,t$$$OO2889 %s   'AA&Ac                    | j                   j                  s"| j                  s| j                   j                  rd| _        t
        j                  diS t
        j                  dddiS )NTrk   helloOk)r   
server_apir   load_balancedr   r&   CMD
LEGACY_CMDr   s    rQ   	hello_cmdzAsyncConnection.hello_cmdq  sO     994==DII4K4K"&DOOQ''**Ay$??rS   c                D   K   | j                  d d d        d {   S 7 wr[   )_hellor   s    rQ   hellozAsyncConnection.helloz  s     [[tT2222s     c                4  K   | j                         }| j                   }d}|rad| _        | j                  j                  |d<   | j                  r| j                  j
                  |d<   | j                  j                  rbd|d<   n\|Z||d<   |J t        |dz        |d<   d}| j                  j                  r(| j                  | j                  j                  |z          |s|||d	<   | j                  j                  }|r|j                  d
k(  r+|j                  r|j                  dz   |j                  z   |d<   ddlm} |j                   j#                  || j$                        }	|	r|	j'                         }
|
|
|d<   nd }	|rt)        j*                         }| j-                  d|d|       d {   }|rt)        j*                         z
  | _        t1        ||      }|j2                  | _        |j4                  | _        |j6                  | _        |j8                  | _        |j:                  | _        |j<                  d uxr |j>                  | _         |j<                  | _        |jB                  | _!        |jD                  tF        jH                  tF        jJ                  tF        jL                  tF        jN                  tF        jP                  fv | _)        |jD                  tF        jT                  k(  | _+        |jD                  tF        jX                  k(  | _-        |r8| j                  r,| j                  j]                  |j
                        }|| _/        d| _0        |jb                  | _2        |r|jf                  | _4        |	r(|	jk                  |       |	jm                         r|	| _7        | j                  j                  rR|jp                  sts        d      |jp                  | _8        | jt                  jw                  | jp                        | _<        |S 7 cw)NFTr   compressionloadBalancedtopologyVersionri   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.asynchronousr#  r:   from_credentialsr   speculate_commandr   r   r   r   r%   r   r   r   r   r   logical_session_timeout_minutesis_readabler   r   server_typer4   	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_handshaker(  credsr#  r   speculative_authenticatestartdocr  ctxs                  rQ   r  zAsyncConnection._hello}  s     nn#'#;#;;	'+D$ II..CM((%)%>%>%J%JM"yy&&&*N#)%5C!"&222$'(;d(B$CC !Iyy((%%dii&?&?BU&UV#(@".C		&&)+,1LL3,>,O()1((99%NH+3+E+E+G(+75MC12HNN$ELL#eU^L__#~~/%7DcY/ ,, % 6 6"00 % 6 6$)$>$>!11=S%BSBS 	 ?D>c>c,((!!##!!-
 
 #..+2H2HH**k.@.@@D$=$=++CCEDUDUVC'*D$"$)$7$7!$)$>$>D!##E*++- (99""##(A  $..DO"mm//@DOW `s   F0P2P3I#Pc                   K   | j                  d        d {   }|j                  | _        |j                         }|d   }t        j                  || j
                         |S 7 LwNr   )r   r   unpack_responser   _check_command_responser   )r   replyunpacked_docsresponse_docs       rQ   _next_replyzAsyncConnection._next_reply  s`     **400!..--/$Q'..|T=R=RS 1s   A&A$AA&TNFc                  K   | j                  ||       t        ||      }t        |t              st	        |      }||j
                  s|
t        d      | j                  |       |r|j                  ||||        | j                  |||       |r| j                  nd}t        |xr |j
                         }| j                  r| j                  |       	 t        | ||| j                  ||||||| j                   || j"                  ||	|
| j$                  | j                  ||||       d{   S 7 # t&        t(        f$ r  t*        $ r}| j-                  |       Y d}~yd}~ww xY ww)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 AsyncClientSession instance.
        :param client: optional AsyncMongoClient 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_fieldsr'  write_concern)validate_sessionr   r   r   dictacknowledgedr   add_server_api	_apply_tosend_cluster_timer   r   r   _raise_if_not_writabler   r   r   r   r   r!   r    BaseExceptionr   )r   dbnamespecread_preferencecodec_optionscheckallowable_errorsread_concernr\  rV  rW  sessionr   retryable_writer&  r[  r'  r   rZ  r   s                       rQ   r   zAsyncConnection.command  sv    R 	fg.1'=I $.:D%)C)CyGX$%Z[[D!dO_dKtWf5&4DNN$	mNM4N4N0NO''7	2  ""*C# $ 8 8..-' /+-   0 !/2 	 	2**511	2sC   CE,AD6 /D40D6 3E,4D6 6E)E$E,$E))E,c                  K   | j                   )|| j                   kD  rt        d|| j                   fz        	 t        | j                  |       d{    y7 # t        $ r}| j                  |       Y d}~yd}~ww xY ww)z}Send 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   r0   r   rd  r   )r   messagemax_doc_sizer   s       rQ   send_messagezAsyncConnection.send_message8  s     
 )lT=O=O.O"?BNPTPbPbAcd 
	2		7333 	2**511	2s@   6BA AA BA 	A>#A94B9A>>Bc                   K   	 t        | || j                         d{   S 7 # t        $ r}| j                  |       Y d}~yd}~ww xY ww)zzReceive a raw BSON message or raise ConnectionFailure.

        If any exception is raised, the socket is closed.
        N)r   r   rd  r   )r   
request_idr   s      rQ   r   zAsyncConnection.receive_messageH  sF     
	2(z4;P;PQQQQ 	2**511	2s5   A% #% A% 	A	AAA		Ac                B    |r| j                   st        ddddd      yy)z^Raise NotPrimaryError on unacknowledged write if this socket is not
        writable.
        znot primaryr   i{'  r   N)r   r    )r   rZ  s     rQ   rc  z&AsyncConnection._raise_if_not_writableR  s+     $"2"2!-]\a1bcc #3>rS   c                f   K   | j                  d       | j                  ||       d{    y7 w)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)rc  rq  )r   r   rp  s      rQ   unack_writezAsyncConnection.unack_writeZ  s,      	##D)\222s   '1/1c                   K   | j                  |d       d{    | j                  |       d{   }|j                  |      }t        j                  || j
                         |S 7 P7 9w)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   N)rq  r   command_responser   rP  r   )r   rs  r   rh  rQ  r   s         rQ   write_commandzAsyncConnection.write_commande  sg      Q'''**:66''6 	..vt7L7LM 	(6s   A-A)A-A+8A-+A-c           	       K   |r| j                   rd| _        d| _        | j                  s1| j                  j                  }|r"ddlm} |j                  || |       d{    d| _        t        j                         | j                  z
  }| j                  r?| j                  J | j                  j                  | j                  | j                  |       | j                   rwt#        j$                  t&        j(                        rSt+        t"        | j,                  t.        j0                  | j                  d   | j                  d   | j                  |       yyyy7 w)	zhAuthenticate to the server if needed.

        Can raise ConnectionFailure or OperationFailure.
        NFr   r"  )reauthenticateTrk   clientIdro  
serverHost
serverPortdriverConnectionId
durationMS)r   r   r   r   r+  r/  r#  authenticater   r   r   r   r   publish_connection_readyr   r   r   r*   isEnabledForloggingDEBUGr,   r   r+   
CONN_READY)r   r{  rH  r#  durations        rQ   r  zAsyncConnection.authenticatew  s     '' $DJzzII**E5''tN'SSSDJ~~'$*<*<<H$$~~11177dggxX'',>,K,KGMM,Z&!__4??#||A#||A'+ww' -[' 
 Ts   AE !E"C=E c                <    |r|j                   |urt        d      yy)zValidate this session before use with client.

        Raises error if the client is not the one that created the session.
        z>Can only use session with the AsyncMongoClient that started itN)_clientr   )r   r   rl  s      rQ   r]  z AsyncConnection.validate_session  s-     f,&T  - rS   c                   | j                   ry| j                          |r| j                  r?| j                  J | j                  j	                  | j
                  | j                  |       | j                  rt        j                  t        j                        r]t        t        | j                  t        j                  | j
                  d   | j
                  d   | j                  t!        |      |       yyyy)z$Close this connection with a reason.Nr   rk   r}  ro  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     rQ   r  zAsyncConnection.close_conn  s    ;;$$~~11188twwPVW'',>,K,KGMM,Z&!__4@@#||A#||A'+ww;FC 	 -['	 rS   c                    | j                   ryd| _         | j                  j                          	 | j                  j	                          y# t
        $ r Y yw xY w)zClose this connection.NT)r   r   r   r   close	Exceptionr   s    rQ   r  zAsyncConnection._close_conn  sJ    ;;""$	IIOO 		s   A 	AAc                L    | j                   j                  | j                        S )z?Return True if we know socket has been closed, False otherwise.)r   socket_closedr   r   s    rQ   conn_closedzAsyncConnection.conn_closed  s    ""00;;rS   c                .    |r|j                  ||       yy)zAdd $clusterTime.N)_send_cluster_time)r   r   rl  r   s       rQ   rb  z!AsyncConnection.send_cluster_time  s     %%gw7 rS   c                r    | j                   j                  r!t        || j                   j                         yy)zAdd server_api parameters.N)r   r  r3   )r   r   s     rQ   r`  zAsyncConnection.add_server_api  s(    99GTYY%9%9:  rS   c                6    t        j                         | _        y r[   r   r   r   r   s    rQ   update_last_checkin_timez(AsyncConnection.update_last_checkin_time  s    !%!1rS   c                    || _         y r[   )r   )r   r   s     rQ   update_is_writablez"AsyncConnection.update_is_writable  s
    &rS   c                D    t        j                         | j                  z
  S )z9Seconds since this socket was last checked into its pool.r  r   s    rQ   idle_time_secondsz!AsyncConnection.idle_time_seconds  s    ~~$"8"888rS   c                    | j                   rd }nt        j                  }| j                  |       t	        |t
        t        t        f      r.t        | j                        }t        | j                  ||       y  )Nr   )r   r/   ERRORr  r   IOErrorr_   r7   r   r   r   r   )r   r   r  r   s       rQ   r   z)AsyncConnection._raise_connection_failure  sY      ::F+11Fegw9:*4995G%dllE7SrS   c                4    | j                   |j                   k(  S r[   )r   r   others     rQ   __eq__zAsyncConnection.__eq__  s    yyEJJ&&rS   c                    | |k(   S r[   rU   r  s     rQ   __ne__zAsyncConnection.__ne__  s    5=  rS   c                ,    t        | j                        S r[   )hashr   r   s    rQ   __hash__zAsyncConnection.__hash__  s    DIIrS   c                    dj                  t        | j                        | j                  xr dxs dt	        |             S )NzAsyncConnection({}){} at {}z CLOSEDr   )formatreprr   r   r   r   s    rQ   __repr__zAsyncConnection.__repr__
  s8    ,33OKK%I+tH
 	
rS   )r   Union[socket.socket, _sslConn]r   Poolr   ztuple[str, int]r   r^   )r   Optional[float]r   r   )r   r<   r  z"Optional[MutableMapping[str, Any]]r   r  r   )r   dict[str, Any])r   r%   )rD  zOptional[ClusterTime]rE  zOptional[Any]rF  Optional[int]r   zHello[dict[str, Any]])"re  r   rf  MutableMapping[str, Any]rg  rE   rh  r8   ri  r   rj  z#Optional[Sequence[Union[str, int]]]rk  zOptional[ReadConcern]r\  zOptional[WriteConcern]rV  r   rW  zOptional[_CollationIn]rl  Optional[AsyncClientSession]r   Optional[AsyncMongoClient]rm  r   r&  r   r[  zOptional[Mapping[str, Any]]r'  r   r   r  )ro  bytesrp  r^   r   r   )rs  r  r   zUnion[_OpReply, _OpMsg])rZ  r   r   r   )r   r  rp  r^   r   r   )rs  r^   r   r  rh  r8   r   r  )F)r{  r   r   r   )r   r  rl  r  r   r   )r  Optional[str]r   r   r   )r   r  rl  r  r   r  r   r   )r   r  r   r   )r   r   r   r   )r   float)r   rd  r   r	   )r  r   r   r   r   r^   )r   r   )'r   r   r   __doc__r   r   r  r  r
  r  r  r  r  rT  r   r2   PRIMARYr   r   rq  r   rc  rv  ry  r  r]  r  r  r  rb  r`  r  r  r  r   r  r  r  r  rU   rS   rQ   r   r      se   1.21.:>1.IX1.^a1.f&&-O	>&#:@3W+W (W +	W
 
Wr 
 (6'='=&;@D.204*/,004-1 %#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	3$):F	$ D0;W	*<8)8 .8 +	8
 
8;
2'98'!
rS   r   c           
        | \  }}|j                  d      rkt        t        d      st        d      t        j                  t        j                        }t        |j                                	 |j                  |       |S t        j                  }t        j                  r|dk7  rt        j                  }d}t        j                  |||t        j                        D ]  }|\  }}	}
}}	 t        j                  ||	t        t        dd      z  |
      }t        |j                                	 |j!                  t        j"                  t        j$                  d       t'        j(                         }||j*                  }n|dk  rt        j,                  d	      |j/                  |       |j!                  t        j0                  t        j2                  d
       t5        |       |j                  |       |c S  ||t        d      # t        $ r |j                           w xY w# t        $ r t        j                  ||	|
      }Y 7w xY w# t        $ r}|}|j                          Y d}~d}~ww xY w)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   rk   r   Tzgetaddrinfo failed)endswithry   rr   r   r  rR   filenoconnectr_   r  AF_INEThas_ipv6	AF_UNSPECgetaddrinfoSOCK_STREAMrz   r}   r|   TCP_NODELAYr   r   r   r   r   
SOL_SOCKETSO_KEEPALIVErw   )r   r   r   r   rt   familyerrresafsocktypeprotodummysar   es                  rQ   _create_connectionr    s    JD$ }}Wvy)#$STT}}V^^,'6	LLK ^^F4;.!!
C!!$ff6H6HI ),&HeUB	6==XPQ0R%RTYZD 	(6	OOF..0B0BAFoo'G!11Ann[11OOG$OOF--v/B/BDI &LLK3< 	 *++c  	JJL	&  	6 ==Xu5D	6&  	CJJLL	s7   /H ,)H)/C	IH&) II	I6I11I6c                z  K   t        | |      }|j                  }||j                  |j                         |S | d   }	 t        rt
        r|j                  ||      }nt        |d      r|j                  ||       d{   }nt        j                         }|j                  dt        j                  |j                  ||             d{   }nwt
        r|j                  |      }n_t        |d      r|j                  |       d{   }n9t        j                         }|j                  d|j                  |       d{   }|j(                  r>|j*                  s2|j,                  s&	 t/        j0                  j3                         |       j                  |j                         |S 7 37 7 7 r# t        $ r |j                           t         t"        f$ r4}|j                          t%        |      }t'        | |d|       Y d}~d}~ww xY w# t        $ r j                           w xY ww)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   r6   _IS_SYNCwrap_socketry   r  asyncioget_running_looprun_in_executor	functoolspartialr$   r  r_   r7   r   r   verify_modecheck_hostnametls_allow_invalid_hostnamessslmatch_hostnamegetpeercert)	r   r   rt   ssl_contextr   ssl_sockloopexcr   s	            rQ   _configured_socketr  Y  s
     gw/D&&K../1:D#c &2242N;8%0%>%>tUY%>%ZZH"335D%)%9%9!))+*A*A4Y]^&  H
 &2248;8%0%>%>t%DDH"335D%)%9%9$@W@WY]%^^H 	**33	x335E
 ../OQ  [   E  _ 

 	X c

 'w/!'30HZabbc ! 	NN	s   =H; AF> F5AF> F8=F> F:9F> 	F<
F> $H;3%H H;5F> 8F> :F> <F> >(H&*HH;HH;H88H;c                      e Zd ZdZy)_PoolClosedErrorzZInternal error raised when a thread tries to get a connection from a
    closed pool.
    N)r   r   r   r  rU   rS   rQ   r  r    s    rS   r  c                  4    e Zd ZddZddZd	dZd
dZddZy)_PoolGenerationc                N    t        j                  t              | _        d| _        y rN  )collectionsdefaultdictr^   _generations_generationr   s    rQ   r   z_PoolGeneration.__init__  s    1<1H1H1MrS   c                <    || j                   S | j                  |   S )z,Get the generation for the given service_id.r  r  r   r   s     rQ   rC  z_PoolGeneration.get  s%    ###  ,,rS   c                    | j                   S )z"Get the Pool's overall generation.)r  r   s    rQ   r   z_PoolGeneration.get_overall  s    rS   c                    | xj                   dz  c_         |)| j                  D ]  }| j                  |xx   dz  cc<    y| j                  |xx   dz  cc<   y)z2Increment the generation for the given service_id.rk   Nr  r  s     rQ   incz_PoolGeneration.inc  s\    A"// 3
!!*-2-3 j)Q.)rS   c                *    || j                  |      k7  S )z?Return if the given generation for a given service_id is stale.)rC  r   r   r   s      rQ   stalez_PoolGeneration.stale  s    dhhz***rS   Nr   )r   Optional[ObjectId]r   r^   r  )r   r  r   r   r   r^   r   r  r   r   )r   r   r   r   rC  r   r  r  rU   rS   rQ   r  r    s    - /+rS   r  c                      e Zd ZdZdZdZy)	PoolStaterk         N)r   r   r   PAUSEDREADYCLOSEDrU   rS   rQ   r  r    s    FEFrS   r  c                     e Zd Z	 	 d	 	 	 	 	 	 	 ddZddZedd       Z	 	 	 d	 	 	 	 	 	 	 	 	 ddZddZ	 d	 	 	 	 	 ddZ	ddZ
dd	Zdd
ZddZdd dZej                   	 d	 	 	 d!d       Zd"dZ	 d	 	 	 	 	 d#dZd$dZd%dZd&dZddZy)'r  Nc                   |j                   rt        j                  | _        nt        j                  | _        d| _        t        j                         | _        t               | _
        t               }t        |      | _        d| _        d| _        d| _        t#               | _        t'        j(                         | _        || _        || _        || _        | j0                  xr: | j.                  j2                  duxr  | j.                  j2                  j4                  | _        | j0                  | _        t9        t;        j<                  |            | _        d| _         | j.                  jB                  | _!        | jB                  stE        d      | _!        t9        t;        j<                  |            | _#        | j.                  jH                  | _%        d| _&        || _'        | j4                  r\| j.                  j2                  J | j.                  j2                  jQ                  | j,                  | j.                  jR                         | j6                  r~tU        jV                  tX        jZ                        r[t]        tT        f| jN                  t^        j`                  | j,                  d   | j,                  d   d| j.                  jR                   d| _1        t               | _2        d| _3        d| _4        y)z
        :param address: a (hostname, port) tuple
        :param options: a PoolOptions instance
        :param handshake: whether to call hello for each new AsyncConnection
        rk   r   Ninfr}  ro  r~  r  )5pause_enabledr  r  stater	  _check_interval_secondsr  dequeconnssetactive_contextsr)   r(   lockactive_socketsnext_connection_idr   r  r   osgetpidpidr   r   	handshaker   r   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   r  	client_id_locks         rQ   r   zPool.__init__  sG      "))DJ"DJ ()$ )4(9(9(;
:=%5M	"#+/
 #$99;	" NN <		**$6<		**;; 	
 $(>> 
 %Y%8%8%?@!YY44!!!&uD %0	0C0CE0J$K!#yy77#  99--999II&&;;dii;; ##(:(G(G(V"0==<<?<<? ))// %& 7:e
rS   c           	     ~  K   | j                   4 d {    | j                  t        j                  k7  rt        j                  | _        | j                  rG| j
                  j                  J | j
                  j                  j                  | j                         | j                  rit        j                  t        j                        rFt        t        | j                  t         j"                  | j                  d   | j                  d          d d d       d {    y 7 7 # 1 d {  7  sw Y   y xY ww)Nr   rk   r  )r  r  r  r	  r   r   r   publish_pool_readyr   r   r*   r  r  r  r,   r   r+   
POOL_READYr   s    rQ   r   z
Pool.ready!  s     99 	 	zzY__,&__
((9955AAAII..AA$,,O++0B0O0OPWP]P]0^*!% 8 C C#'<<?#'<<?	 	 	 	 	 	 	sE   D=D#D=C;D(D=D&D=&D=(D:.D1/D:6D=c                <    | j                   t        j                  k(  S r[   )r  r  r
  r   s    rQ   r   zPool.closed2  s    zzY----rS   c                  K   | j                   }| j                  4 d {    | j                  r	 d d d       d {    y | j                  j                  r:|r8| j                  j
                  s"| j                   t        j                  c}| _         | j                  j                  |       t        j                         }| j                  |k7  r|| _        d| _        d| _        |'| j                  t!        j"                         c}| _        ntt!        j"                         }t!        j"                         }	| j                  D ]4  }
|
j$                  |k(  r|j'                  |
       $|	j'                  |
       6 |}|	| _        |rt        j(                  | _         | j*                  j-                          | j                  j-                          |r!| j.                  D ]  }|j1                           d d d       d {    | j                  j2                  }|rD ]!  }
|
j5                  t6        j8                         # | j:                  r|J |j=                  | j>                         | j@                  rktC        jD                  tF        jH                        rGtK        tB        | jL                  tN        j8                  | j>                  d   | j>                  d          y y y |t        j                  k7  r| j:                  r"|J |jQ                  | j>                  ||       | j@                  rjtC        jD                  tF        jH                        rGtK        tB        | jL                  tN        jR                  | j>                  d   | j>                  d   |       D ]!  }
|
j5                  t6        jT                         # y 7 7 7 # 1 d {  7  sw Y   xY ww)Nr   rk   r  )r   interrupt_connections)r}  ro  r~  r  	serviceId)+r  r  r   r   r  r  r  r  r   r  r  r  r  r  r)  r  r  r  r   appendr
  r"  
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   r4  	old_statenewpidsocketsdiscardkeepr   contextr   s                rQ   _resetzPool._reset6  s$     JJ	>>  	%  	%{{ 	%  	%  	% yy&&59P9P(,

I4D4D%	4:HHLL$YY[Fxx6!!&'#'($!&*jj+2C2C2E#-8->->-@*5*;*;*= JJ *D*4t,D)	*
 "!
&--
%%002NN%%'$#33 %GNN$%? 	%  	%D II..	  D 6 B BCD$$ ,,,--dll;'',>,K,KGMM,Z&!__4@@#||A#||A -[' I,,,(($00022#-.C 3 
 ++0B0O0OPWP]P]0^*!% 8 E E#'<<?#'<<?",   > 6 < <=>M 	%  	%  	%  	%  	%  	%sa   ON?OOOOOF.O0O;O<GOOOOOOOc                   K   || _         | j                  4 d{    | j                  D ]  }|j                  | j                           ddd      d{    y7 A7 # 1 d{  7  sw Y   yxY ww)zXUpdates the is_writable attribute on all sockets currently in the
        Pool.
        N)r   r  r  r  )r   r   _sockets      rQ   r  zPool.update_is_writable  sm      '99 	= 	=:: =**4+;+;<=	= 	= 	= 	= 	= 	= 	=sD   A5AA5-A A5AA5A5 A2&A)'A2.A5c                H   K   | j                  d||       d {    y 7 w)NF)r  r   r4  rC  )r   r   r4  s      rQ   resetz
Pool.reset  s+      kkJF[  
 	
 	
s   " "c                F   K   | j                  dd       d {    y 7 w)NF)r  r<  rG  r   s    rQ   reset_without_pausezPool.reset_without_pause  s     kkUk333s   !!c                D   K   | j                  d       d {    y 7 w)NT)r  rG  r   s    rQ   r  z
Pool.close  s     kkk%%%s     c                :    | j                   j                  ||      S r[   )r   r  r   s      rQ   stale_generationzPool.stale_generation  s    xx~~c:..rS   c           	       K   | j                   4 d{    | j                  t        j                  k7  r	 ddd      d{    yddd      d{    | j                  j
                  | j                   4 d{    | j                  r| j                  d   j                         | j                  j
                  kD  rz| j                  j                         }|j                  t        j                         | j                  r5| j                  d   j                         | j                  j
                  kD  rzddd      d{    	 | j                  4 d{    t        | j                        | j                  z   | j                  j                  k\  r	 ddd      d{    y| j                   | j                  j                  k\  r	 ddd      d{    y| xj                   dz  c_        ddd      d{    d}	 | j"                  4 d{    | j$                  | j&                  k\  r	 ddd      d{    |rT| j"                  4 d{    | xj$                  dz  c_        | j"                  j)                          ddd      d{    | j                  4 d{    | xj                   dz  c_        | j                  j)                          ddd      d{    y| xj$                  dz  c_        d}ddd      d{    | j+                          d{   }| j                   4 d{    | j,                  j/                         |k7  r|j                  t        j0                         	 ddd      d{    |rT| j"                  4 d{    | xj$                  dz  c_        | j"                  j)                          ddd      d{    | j                  4 d{    | xj                   dz  c_        | j                  j)                          ddd      d{    y| j                  j3                  |       | j4                  j7                  |j8                         ddd      d{    |rT| j"                  4 d{    | xj$                  dz  c_        | j"                  j)                          ddd      d{    | j                  4 d{    | xj                   dz  c_        | j                  j)                          ddd      d{    7 )7 7 # 1 d{  7  sw Y   xY w7 7 # 1 d{  7  sw Y   (xY w7 7 7 7 ~# 1 d{  7  sw Y   xY w7 7 X7 D7 # 1 d{  7  sw Y   xY w7 7 # 1 d{  7  sw Y   yxY w7 # 1 d{  7  sw Y   xY w7 7 7 e7 Q7 # 1 d{  7  sw Y   &xY w7 7 # 1 d{  7  sw Y   yxY w7 # 1 d{  7  sw Y   xY w7 7 j# 1 d{  7  sw Y   {xY w7 n7 2# 1 d{  7  sw Y   CxY w# |rl| j"                  4 d{  7   | xj$                  dz  c_        | j"                  j)                          ddd      d{  7   n# 1 d{  7  sw Y   nxY w| j                  4 d{  7   | xj                   dz  c_        | j                  j)                          ddd      d{  7   w # 1 d{  7  sw Y   w xY wxY ww)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   Trk   F)r  r  r  r	  r   max_idle_time_secondsr  r  popr  r/   IDLEr  lenr  min_pool_sizer   r"  r%  r$  notifyr  r   r   r  
appendleftr  r@  r   )r   reference_generationr   incrementeds       rQ   remove_stale_socketszPool.remove_stale_sockets  s     99 	 	zzY__,	 	 	 	 	 99**6yy A AJJ

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

288:TYY=\=\\A A ~~ # #tzz?T%8%88DII<S<SS# # # ==DII$;$;;# # # "# #  K,44 ' ' }}(<(<<	' '" #88 ; ;*1188:; ;  >> , ,MMQ&MNN))+, , ,% MMQ&M"&K' ' "\\^+99 F F xx++-1EE(>(D(DEF F #88 ; ;*1188:; ;  >> , ,MMQ&MNN))+, , , JJ))$/((001D1DEF F #88 ; ;*1188:; ;  >> , ,MMQ&MNN))+, ,C 	 	 	 	 	 	
A A A A A# # # # # # #' '&; ; ; ; ;, , , , ,/' ' ' ' ,F F; ; ; ; ;, , , , ,F F F F; ; ; ; ;, , , , , #88 ; ;*1188:; ; ; ; ;  >> , ,MMQ&MNN))+, , , , ,s)  ]T<]U]T?]U*]=U>]B:U!<]U]U7]!;V]'U:(]-$V]U=]"V7]V ]
Z  VZ  W9Z  VZ  	]V]0V%]V"]/V;0]30W#].V>/]4WZ  WZ  .W//Z  W2Z  >X2Z  W5Z  ]'W8(]+0W>]&W;'];X<]?0X/]:X;] A X2 Z  X/Z  ]"Y#]&0Y]!Y"]6Y$7]:0Y**]5Y'6]?]]UUU	]]!U4'U*(U4/	]:]=] ]V	V
V]Z  Z  ]"]%V8+V.,V83	]>]WW
W]Z  W,W" W,'	Z  2Z  5Z  8];]>XXX	]]X, X#!X,(]/Z  2Y8X;9Y Z  ]]Y!YY!	]']*Y=0Y31Y=8] ]Z
]0[][][, [#![,(]?\
 ]0]4]?] ]]]]]]c                &  K   | j                   4 d{    | j                  }| xj                  dz  c_        ddd      d{    | j                  j                  }| j                  r |J |j                  | j                         | j                  rjt        j                  t        j                        rGt        t        | j                  t        j                  | j                  d   | j                  d          	 t!        | j                  | j                         d{   }t;        || | j                        }| j                   4 d{    | j<                  j?                  |j@                         ddd      d{    	 | jB                  r)|jE                          d{    |jF                  | _#        |r|jI                  |d       |jK                          d{    |S 7 7 # 1 d{  7  sw Y   xY w7 # t"        $ r&}| j                  r/|J |j%                  | j                  t&        j(                         | j                  rt        j                  t        j                        rnt        t        | j                  t        j*                  | j                  d   | j                  d   t-        t&        j(                        t&        j(                         t/        |t0        t2        t4        f      r-t7        | j                        }t9        | j                  ||        d}~ww xY w7 7 # 1 d{  7  sw Y   xY w7 7 w# t"        $ r! |jM                  t&        j(                          w xY ww)	zConnect to Mongo and return a new AsyncConnection.

        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.
        Nrk   r   r}  ro  r~  r  r  r  r  F)completed_handshake)'r  r  r   r   r   publish_connection_createdr   r   r*   r  r  r  r,   r   r+   CONN_CREATEDr  rd  r  r/   r  r  r-   r   r  r_   r7   r   r   r   r  addr   r  r  r   contribute_socketr  r  )r   handlerconn_idr   rt   r   r   r   s           rQ   r  zPool.connect  s     99 	) 	)--G##q(#	) 	) II..	  (((00wG##(:(G(G(V"0==<<?<<?#*	+DLL$))DDD0 tT4<<A99 	: 	:  $$T%8%89	: 	:
	~~jjl""#'#3#3 ))$E)J##%%%
 u	) 	) 	) 	) 	)& E 	$$ ,,,33LL'+A+G+G '',>,K,KGMM,Z&!__4@@#||A#||A'.;<R<X<XY066	 %'7H!=>.tyy9)$,,wW+	0	: 	: 	: 	: 	: #
 & 	OO2889	s   NG1N"G7NG4B<N#H %H&H *(NMN&M<NMNM$ ,M-=M$ *M!+M$ /N4N7H
=H >H
NH 
L?D!L::L??NNMMMNM$ !M$ $*NNc           	      K   | j                   j                  }t        j                         }| j                  r|J |j                  | j                         | j                  rit        j                  t        j                        rFt        t        | j                  t        j                  | j                  d   | j                  d          | j!                  ||       d{   }t        j                         |z
  }| j                  r+|J |j#                  | j                  |j$                  |       | j                  rut        j                  t        j                        rRt        t        | j                  t        j&                  | j                  d   | j                  d   |j$                  |       	 | j(                  4 d{    | j*                  j-                  |j.                         ddd      d{    | |j2                  rV| j(                  4 d{    | j@                  j-                  |       | xjB                  dz  c_!        ddd      d{    y|j4                  rV| j(                  4 d{    | j@                  j-                  |       | xjD                  dz  c_"        ddd      d{    y|j<                  r| j?                  |       d{    yy7 7 -7 # 1 d{  7  sw Y   xY w# t0        $ ry |j2                  xs |j4                  }|r3t7        j8                         \  }}}	|j;                  ||       d{  7   |s&|j<                  r| j?                  |       d{  7    w xY w7 r7 5# 1 d{  7  sw Y   yxY w7 +7 # 1 d{  7  sw Y   yxY w7 ޭw)a  Get a connection from the pool. Use with a "with" statement.

        Returns a :class:`AsyncConnection` 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   rk   r  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   rd  r   r   sysexc_infohandler   r  r*  r,  r+  )
r   r`  r   checkout_started_timer   r  pinnedexc_typeexc_valre   s
             rQ   checkoutzPool.checkout  s    & II..	 $ 0  (((::4<<H##(:(G(G(V"0AA<<?<<? ^^$97^KK>>#&;;  (((44T\\477HU##(:(G(G(V"0CC<<?<<?#'77#	yy > >$$(()<)<=> >J ??yy    %%))$/

a
      yy # #%%))$/"# # # [[,,t$$$ U L"> > > > >  	
 __:(:(:F (+||~$'1nnXw777dkkll4(((	         # # # # # %s  C!O#K2$CO8L K5	L &K:2L =K8>	L O#N$O'1NO#N$!ON0O	1N5:ON3%O+O
,O5L 8L :L LLL AN"M%#'N
NNOON-!N$"N-)O3O5O;N><OOc           
        | j                   t        j                  k7  r:|r t        j                         |z
  }| j
                  rW| j                  j                  J | j                  j                  j                  | j                  t        j                  |       | j                  rzt        j                  t        j                         rWt#        t        | j$                  t&        j(                  | j                  d   | j                  d   dt        j                  |       t+        | j                        }t-        | j                  t/        d      |       y y )Nr   rk   <An error occurred while trying to establish a new connectionr}  ro  r~  r  r  r   r  zconnection pool pausedr  )r  r  r	  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   rl  
emit_eventr  r   s        rQ   _raise_if_not_readyzPool._raise_if_not_readyk  s    ::(>>+.CC((9955AAAII..RR&D&O&OQY ++0B0O0OPWP]P]0^*!% 8 H H#'<<?#'<<?]<GG#+	 +4995G%m,DEW^+ )rS   c                  K   | j                   t        j                         k7  r| j                          d{    | j                  rt        j                         |z
  }| j                  rW| j                  j                  J | j                  j                  j                  | j                  t        j                  |       | j                  rzt        j                   t"        j$                        rWt'        t        | j(                  t*        j,                  | j                  d   | j                  d   dt        j                  |       t/        d      | j0                  4 d{    | xj2                  dz  c_        ddd      d{    t5        j6                         rt5        j8                         }nD| j                  j:                  r,t        j                         | j                  j:                  z   }nd}| j<                  4 d{    | j?                  |d       | j@                  | jB                  k  stE        | j<                  |       d{   sD| j@                  | jB                  k  r| j<                  jG                          | jI                  |       | j?                  |d       | j@                  | jB                  k  s| xj@                  dz  c_         ddd      d{    d}d	}d	}	 | j0                  4 d{    | xjJ                  dz  c_%        d}ddd      d{    || jL                  4 d{    | j?                  |d	       | jN                  s| jP                  | jR                  k  stE        | jL                  |       d{   sR| jN                  s| jP                  | jR                  k  r| jL                  jG                          d}| jI                  |       | j?                  |d	       | jN                  s| jP                  | jR                  k  s	 | jN                  jU                         }ddd      d{    |r| jY                  |      rsd};	 | j[                  |
       d{   }| jL                  4 d{    | xjP                  dz  c_(        | jL                  jG                          ddd      d{    |d|_3        |S 7 7 7 g# 1 d{  7  sw Y   xxY w7 7 7 $# 1 d{  7  sw Y   5xY w7 !7 # 1 d{  7  sw Y   xY w7 7 # tV        $ r | xjP                  dz  c_(        Y $w xY w7 # 1 d{  7  sw Y   .xY w7 7 7 # 1 d{  7  sw Y   xY w# | jL                  4 d{  7   | xjP                  dz  c_(        | jL                  jG                          ddd      d{  7   w # 1 d{  7  sw Y   w xY wxY w# t\        $ r |r|j_                  t`        jb                         | j<                  4 d{  7   | xj@                  dz  c_         |r| xjJ                  dz  c_%        | j<                  jG                          ddd      d{  7   n# 1 d{  7  sw Y   nxY w|s t        j                         |z
  }| j                  rW| j                  j                  J | j                  j                  j                  | j                  t        jd                  |       | j                  rzt        j                   t"        j$                        rWt'        t        | j(                  t*        j,                  | j                  d   | j                  d   dt        jd                  |        w xY ww)z=Get or create a AsyncConnection. Can raise ConnectionFailure.Nr   rk   zConnection pool was closedrs  z?Attempted to check out a connection from closed connection poolT)rw  Frc  rr  )4r  r  r  rJ  r   r   r   r   r   r   rt  r   r.   r8  r   r*   r  r  r  r,   r   r+   rv  r  r  r)  r   r   get_deadlinewait_queue_timeoutr  rx  r   r!  r   rT  _raise_wait_queue_timeoutr  r"  r  r%  r$  popleft
IndexError	_perishedr  rd  r  r/   r  ru  r   )r   rl  r`  r  r   r   rW  emitted_events           rQ   rf  zPool._get_conn  sI     88ryy{"**,,,;;~~'*??H$$yy11===		**NNLL"@"L"Lh '',>,K,KGMM,Z&!__4DD#||A#||A78DD'	 #Q  99 	& 	&  A% 	& 	& ))+HYY))~~'$))*F*FFHH>> 
	 
	$$%:t$L}}t'9'99'AAA }}t'9'99--/223HI(()>4(P }}t'9'99 MMQM
	 
	 >	yy # ###q(#"# # ,  44 + +,,-Bu,U#zzT]]T=Q=Q-Q%/0I0I8%TTT  $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+# ?%)\\'\%BB#'#<#< ? ? MMQ.M 55<<>? ?7 ,x i -0	& 	& 	& 	& 	&
	 B
	 
	 
	 
	"# # # # #+  U & +*++ + + +,  C? ? ? ? ?4#<#< ? ? MMQ.M 55<<>? ? ? ? ?  	 6 < <=~~ ( ("''1,'%%'	( ( ( ( ( !>>+.CC((9955AAAII..RR&D&O&OQY ++0B0O0OPWP]P]0^*!% 8 H H#'<<?#'<<?]<GG#+	 9	su  5_
S*D,_
$S-%_
(S3>_
	S0
B_
T	_
ATTA4TT _
+T,
_
7X T(X T.#X .T+/X UX 
AU2UBU2-U
X U/X /V$ VV$ 	X VX 0VX VX !
_
-_
0_
3T9S<:T	_
T_
T%TT% _
(X +X .U4T75U<	X U2
U,(U2+U,,U2/X 2V8U;9V X V$ X X V!VV!X $X5V8
6X:0W<*X5W86X<XXX
XX ;_Y_AZ-_&Z)'_-Z?	3Z64Z?	;D__
c                4	  K   |j                   }|j                  }d|_        d|_         d|_        | j                  j	                  |       | j
                  j                  }| j                  4 d{    | j                  j	                  |j                         ddd      d{    | j                  r*|J |j                  | j                  |j                         | j                  rtt        j                   t"        j$                        rQt'        t        | j(                  t*        j,                  | j                  d   | j                  d   |j                         | j.                  t1        j2                         k7  r| j5                          d{    n| j6                  r!|j9                  t:        j<                         n|j6                  r| j                  r9|J |j?                  | j                  |j                  t:        j@                         | j                  rqt        j                   t"        j$                        rMt'        t        | j(                  t*        jB                  | j                  d   | j                  d   |j                  tE        t:        j@                        t:        j@                         n| j                  4 d{    | jG                  |jH                  |jJ                        r |j9                  t:        jL                         ni|jO                          |jQ                  tS        | jT                               | jV                  jY                  |       | jZ                  j]                          ddd      d{    | j^                  4 d{    |r| xj`                  dz  c_0        n|r| xjb                  dz  c_1        | xjd                  dz  c_2        | xjf                  dz  c_3        | xjh                  dz  c_4        | j^                  j]                          ddd      d{    y7 7 # 1 d{  7  sw Y   xY w7 7 7 # 1 d{  7  sw Y   xY w7 7 @# 1 d{  7  sw Y   yxY ww)zReturn the connection to the pool, or if it's closed discard it.

        :param conn: The connection to check into the pool.
        FNr   rk   rZ  r  )5r   r   r   r*  r@  r   r   r  r  r   r   publish_connection_checked_inr   r   r   r*   r  r  r  r,   r   r+   	CHECKEDINr  r  r  rJ  r   r  r/   r8  r  r  r  r-   rM  r   r   r  r  r  r   r   r  rU  r"  rT  r  r,  r+  r   r  r)  )r   r   txncursorr   s        rQ   r  zPool.checkin  sj    
 oo##"%%d+II..	99 	> 	>  (()<)<=	> 	>  (((33DLL$''J##(:(G(G(V"0::<<?<<?#'77 88ryy{"**,,,{{ 6 B BC(($00077dgg/E/K/K ++0B0O0OPWP]P]0^*!% 8 D D#'<<?#'<<?+/77?@V@\@\]4::	  99 
; 
; ,,T__dooN(>(D(DE557//T5E5E0FG

--d31188:
; 
; >> 	$ 	$

a
"MMQM1$  A% NN!!#	$ 	$ 	$e	> 	> 	> 	> 	> -.
; 
; 
; 
; 
;	$ 	$ 	$ 	$ 	$s   A/R1Q2R5&QR&Q	'C.RQ"D>RQ%RB0Q*RQ(R(Q?)R,B	R5R RR	RQQQ	R%R(R*Q<0Q31Q<8RRR	R
RRc                   |j                         }| j                  j                  9|| j                  j                  kD  r |j                  t        j
                         y| j                  N| j                  dk(  s|| j                  kD  r0|j                         r |j                  t        j                         y| j                  |j                  |j                        r |j                  t        j                         yy)a  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   rO  r  r/   rQ  r  r  r  rM  r   r   r  )r   r   r  s      rQ   r  zPool._perishedK  s     !224 II++7!DII$C$CCOO2778''3((A-1BTEaEa1a! 6 < <=  $//BOO2889rS   c           
        | j                   j                  }t        j                         |z
  }| j                  r/|J |j                  | j                  t        j                  |       | j                  rzt        j                  t        j                        rWt        t        | j                  t         j"                  | j                  d   | j                  d   dt        j                  |       t%        j&                         xs | j                   j(                  }| j                   j*                  rl| j,                  | j.                  z
  | j0                  z
  }t3        dj5                  | j                   j6                  | j.                  | j0                  ||            t3        d| j                   j6                   d|       )Nr   rk   zBWait queue timeout elapsed without a connection becoming availablers  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   rt  r   r.   TIMEOUTr   r*   r  r  r  r,   r   r+   rv  r   r   r{  r  r  r+  r,  r#   r  r!  )r   rl  r   r  r   	other_opss         rQ   r|  zPool._raise_wait_queue_timeouto  sm   II..	>>#&;;  (((99<DDh ##(:(G(G(V"0@@<<?<<?[4<<#	 ##%E)E)E99""++dmm;djjHI'7 8>vII++MMJJ8	  $ II334KyJ
 	
rS   c                H    | j                   D ]  }|j                  d         y r[   )r  r  )r   r   s     rQ   __del__zPool.__del__  s#     JJ 	"DOOD!	"rS   )TN)r   rG   r   r1   r  r   r-  r  r   r   )TNF)
r  r   r<  r   r   r  r4  r   r   r   )r   zOptional[bool]r   r   r   )r   r  r4  r   r   r   r  )rV  r^   r   r   r[   )r`  "Optional[_MongoClientErrorHandler]r   r   )r`  r  r   z%AsyncGenerator[AsyncConnection, None])rl  r  rw  r   r   r   )rl  r  r`  r  r   r   )r   r   r   r   )r   r   r   r   )rl  r  r   r	   )r   r   r   r   r   r   r   rC  r  rH  rJ  r  rM  rX  r  
contextlibasynccontextmanagerrp  rx  rf  r  r  r|  r  rU   rS   rQ   r  r    sX   
 (,TT T 	T
 &Tl" . . )-&+O>O> O> '	O>
  $O> 
O>b= TY
,
LP
	
4&/7,rBH ##<@K%9K%	.K% $K%Z6 [_|%*|5W|	||F$P"H%
N"rS   r  )rO   r^   r   r   )rt   socket.socketr~   r   r   r^   r   r   )rt   r  r   r   )NN)
r   r   r   r  r   r  r   Optional[dict[str, float]]r   r	   )r   r'   r   r  r   r   )r   r1   r   zdict[str, float])r   r  r   r   )r   rG   r   r1   r   r  )r   rG   r   r1   r   r  )
__future__r   r  r  r  r  r  r  rr   r  ri  r  r   r   typingr   r   r   r   r   r	   r
   r   r   bsonr   pymongor   r   #pymongo.asynchronous.client_sessionr   pymongo.asynchronous.helpersr   pymongo.asynchronous.networkr   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(   r)   pymongo.loggerr*   r+   r,   r-   pymongo.monitoringr.   r/   pymongo.network_layerr0   pymongo.pool_optionsr1   pymongo.read_preferencesr2   pymongo.server_apir3   pymongo.server_typer4   pymongo.socket_checkerr5   pymongo.ssl_supportr6   r7   r8   bson.objectidr9   pymongo.asynchronous.authr:   r;   !pymongo.asynchronous.mongo_clientr<   r=   pymongo.compression_supportr>   r?   r@   pymongo.messagerA   rB   pymongo.pyopenssl_contextrC   pymongo.read_concernrD   rE   pymongo.typingsrF   rG   rH   pymongo.write_concernrI   rM   rJ   rK   rL   rR   ImportErrorr  rn   rp   r   platform_winregr\   rf   OpenKeyHKEY_LOCAL_MACHINEra   rm   ro   r_   rw   r   r   r   r   r   r   r   r  r  r  r  r  r  rU   rS   rQ   <module>r     s~   #      	  
 
   
 
 
 ' ) O 7 A     - : :  0 , 3 . + 0 1!&6F\ 
 1204CC2E99/    <<7 
(V^^%%'\
 	N#)##H '-c3F'M$		NM? !%26	,,, , 0	,
 ,:)
	 O
 O
dD,NAA +A#AH| + +> Q" Q"s  EE	E"  	N 	N
  (  '#' 	(sN   H  *H/ 2I
 H>$I
  	H,+H,/	H;:H;>II
 
	II