
    ]*i[                       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
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 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*m+Z+m,Z,m-Z-m.Z. d dl/m0Z0m1Z1 d dl2m3Z3m4Z4 d dl5m6Z6m7Z7m8Z8 d dl9m:Z:m;Z;m<Z<m=Z= d dl>m?Z?m@Z@ d dlAmBZBmCZCmDZD d dlEmFZF d dlGmHZHmIZImJZJmKZK d dlLmMZM d dlNmOZO d dlPmQZQ d dlRmSZS erLd dlmTZT d dlUmVZV d dlWmXZX d dlmYZY d dlZm[Z[m\Z\ d dl]m^Z^m_Z_m`Z` d dlambZbmcZc d dldmeZe d dlLmfZf d d lgmhZhmiZi d d!ljmkZk d"Zl G d# d$      Zm G d% d&e-      Zn G d' d(      Zo G d) d*      Zp G d+ d,      Zqy)-    )annotationsN)	TYPE_CHECKINGAnyAsyncGeneratorMappingMutableMappingNoReturnOptionalSequenceUnion)DEFAULT_CODEC_OPTIONS)_csothelpers_shared)_validate_session_write_concern)_handle_reauth)command)MAX_BSON_SIZEMAX_MESSAGE_SIZEMAX_WIRE_VERSIONMAX_WRITE_BATCH_SIZEORDERED_TYPES)	AutoReconnectConfigurationErrorDocumentTooLargeExecutionTimeoutInvalidOperationNotPrimaryErrorOperationFailurePyMongoErrorWaitQueueTimeoutError)HelloHelloCompat)_get_timeout_detailsformat_timeout_details)_async_cond_wait_async_create_condition_async_create_lock)_CONNECTION_LOGGER_ConnectionStatusMessage
_debug_log _verbose_connection_error_reason)ConnectionCheckOutFailedReasonConnectionClosedReason)AsyncNetworkingInterfaceasync_receive_messageasync_sendall)PoolOptions)	SSLErrors_CancellationContext_configured_protocol_interface_raise_connection_failure)ReadPreference)_add_to_command)SERVER_TYPE)SocketChecker)CodecOptions)ObjectId)_AuthContext)AsyncClientSession)AsyncMongoClient_MongoClientErrorHandler)SnappyContextZlibContextZstdContext)_OpMsg_OpReply)ReadConcern)_ServerMode)_Address_CollationIn)WriteConcernFc                     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)>AsyncConnectiona  Store 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
    :param is_sdam: SDAM connections do not call hello on creation
    c                
   t        j                  |      | _        || _        || _        || _        || _        d| _        t        j                         | _
        d| _        d| _        t        | _        t        | _        t"        | _        t&        | _        d| _        d| _        d| _        d| _        |j2                  j4                  | _        |j8                  | _        |j:                  | _        |j2                  j<                  | _        d | _         tC               | _"        d | _#        d | _$        d | _%        |jL                  | _'        | jN                  jQ                         | _)        d| _*        tW               | _,        |j2                  | _        d| _-        d | _.        d | _/        d| _0        d| _1        d| _2        | j2                  jf                  | _4        d| _5        |jl                  | _6        t        j                         | _7        d | _8        y )NFg        )9weakrefrefpool_refconnaddressidis_sdamclosedtime	monotonic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_contextr9   socket_checkeroidc_token_gen_idnegotiated_mechsauth_ctxgenpool_genget_overall
generationreadyr3   cancel_contextmore_to_come
service_idserver_connection_id
pinned_txnpinned_cursoractivesocket_timeoutlast_timeoutconnect_rtt
_client_idcreation_time_cluster_time)selfrP   poolrQ   rR   rS   s         S/home/alumno/antonio/venv/lib/python3.12/site-packages/pymongo/asynchronous/pool.py__init__zAsyncConnection.__init__y   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//!^^-!    c                |    || j                   k(  ry|| _         | j                  j                  j                  |       y)z?Cache last timeout to avoid duplicate calls to conn.settimeout.N)r{   rP   get_conn
settimeout)r   timeouts     r   set_conn_timeoutz AsyncConnection.set_conn_timeout   s3    d'''#		%%g.r   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: 2   okerrmsgcode  	maxTimeMS)r   	remainingrt   r   rb   rz   get_rttr|   r#   r$   r   rZ   int)	r   clientcmdr   rttmax_time_mstimeout_details	formattedr   s	            r   apply_timeoutzAsyncConnection.apply_timeout   s     //#?$$%%dii&>&>?mmo;""Cm?2499=O.?ILWUXMYuvyz}u~~  AJ  @K  LF"FB7%%	  ?";#56Cg&r   c                .    d| _         | j                  rJ y NT)rw   rx   r   s    r   pin_txnzAsyncConnection.pin_txn   s    %%%%%r   c                .    d| _         | j                  rJ y r   )rx   rw   r   s    r   
pin_cursorzAsyncConnection.pin_cursor   s    !??""?r   c                   K   | j                         }|r|j                  |        d {    y | j                  t        j                         d {    y 7 -7 wN)rO   checkin
close_connr-   STALE)r   r   s     r   unpinzAsyncConnection.unpin   sH     }},,t$$$//"8">">??? %?s!   'AA'A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 )NT   helloOk)rb   
server_apir_   load_balancedra   r"   CMD
LEGACY_CMDr   s    r   	hello_cmdzAsyncConnection.hello_cmd   sO     994==DII4K4K"&DOOQ''**Ay$??r   c                B   K   | j                  d d        d {   S 7 wr   )_hellor   s    r   hellozAsyncConnection.hello   s     [[t,,,,s   c                "  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          | 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topologyVersionr   maxAwaitTimeMS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   rX   rb   metadatarh   compressorsr   r   connect_timeoutr   _credentials	mechanismusernamesourcepymongo.asynchronousr   r<   from_credentialsrQ   speculate_commandrU   rV   r   r|   r!   rY   rZ   r[   r\   r]   logical_session_timeout_minutesis_readabler^   r_   server_typer8   	RSPrimaryRSSecondary	RSArbiterRSOtherRSGhostis_repl
Standaloneis_standaloneMongosr`   get_compression_contextri   ra   connection_idrv   sasl_supported_mechsrl   parse_responsespeculate_succeededrm   ru   r   ro   getrq   )r   topology_versionheartbeat_frequencyr   performing_handshaker   credsr   rm   speculative_authenticatestartdocr   ctxs                 r   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		&&)+,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   F'P)P*I#Pc                   K   | j                  d        d {   }|j                  | _        |j                         }|d   }t        j                  || j
                         |S 7 LwNr   )receive_messagert   unpack_responser   _check_command_responserZ   )r   replyunpacked_docsresponse_docs       r   _next_replyzAsyncConnection._next_replyJ  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-                  |       d{  7   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   
isinstancer   dictacknowledgedr   add_server_api	_apply_tosend_cluster_timerd   boolra   _raise_if_not_writabler   r`   rQ   r[   ri   r   r   BaseExceptionr5   )r   dbnamespecread_preferencecodec_optionscheckallowable_errorsread_concernr   r   r   sessionr   retryable_writer   r   r   rd   r   errors                       r   r   zAsyncConnection.commandR  sy    R 	fg.1'=I $.:D%)C)CyGX$%Z[[D!dO_dKtWf5&4DNN$	mNM4N4N0NO''7	8  ""*C# $ 8 8..-' /+-   0 !/2 	 	800777	8sO   CE5AD6 /D40D6 3E54D6 6E2E-"E%#E-(E5-E22E5c                ,  K   | j                   )|| j                   kD  rt        d|| j                   fz        	 t        | j                  j                  |       d{    y7 # t
        $ r$}| j                  |       d{  7   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   rP   r   r  r5   )r   messagemax_doc_sizer  s       r   send_messagezAsyncConnection.send_message  s     
 )lT=O=O.O"?BNPTPbPbAcd 
	8		 2 2G<<< 	800777	8sL   6B#A$ A"A$ !B"A$ $	B-BBBBBBc                   K   	 t        | || j                         d{   S 7 # t        $ r$}| j                  |       d{  7   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\   r  r5   )r   
request_idr  s      r   r   zAsyncConnection.receive_message  sI     
	8.tZAVAVWWWW 	800777	8sB   A% #% A% 	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)rY   r   )r   r   s     r   r   z&AsyncConnection._raise_if_not_writable  s+     $"2"2!-]\a1bcc #3>r   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)r   r  )r   msgr  s      r   unack_writezAsyncConnection.unack_write  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)r  r   command_responser   r   rZ   )r   r  r  r  r   results         r   write_commandzAsyncConnection.write_command  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"        t,        j.                  | 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   )reauthenticateTr   r  clientId
serverHost
serverPortdriverConnectionId
durationMS)rX   rm   rr   rb   r   r   r   authenticaterU   rV   r~   re   rd   publish_connection_readyrQ   rR   rf   r(   isEnabledForloggingDEBUGr*   r)   
CONN_READYr}   )r   r  r   r   durations        r   r"  zAsyncConnection.authenticate  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   r	  s      r   r   z AsyncConnection.validate_session  s-     f,&T  - r   c                  K   | j                   ry| j                          d{    |r| j                  r?| j                  J | j                  j	                  | j
                  | j                  |       | j                  rt        j                  t        j                        r]t        t        t        j                  | j                  | j
                  d   | j
                  d   | j                  t!        |      |       yyyy7 w)z$Close this connection with a reason.Nr   r   r  r  r  r  r   reasonr  )rT   _close_connre   rd   publish_connection_closedrQ   rR   rf   r(   r$  r%  r&  r*   r)   CONN_CLOSEDr}   r+   )r   r-  s     r   r   zAsyncConnection.close_conn  s     ;;   $$~~11188twwPVW'',>,K,KGMM,Z&4@@!__#||A#||A'+ww;FC 	 -['	  	!s   !DDC!Dc                   K   | j                   ryd| _         | j                  j                          	 | j                  j	                          d{    y7 # t
        $ r Y yw xY ww)zClose this connection.NT)rT   rs   cancelrP   close	Exceptionr   s    r   r.  zAsyncConnection._close_conn1  sS     ;;""$	))//### 		s:   /A&A AA A&A 	A# A&"A##A&c                    t         r/| j                  j                  | j                  j                        S | j                  j                         S )z?Return True if we know socket has been closed, False otherwise.)_IS_SYNCrj   socket_closedrP   r   
is_closingr   s    r   conn_closedzAsyncConnection.conn_closed>  s9    &&44TYY5G5GHH99''))r   c                .    |r|j                  ||       yy)zAdd $clusterTime.N)_send_cluster_time)r   r   r	  r   s       r   r   z!AsyncConnection.send_cluster_timeE  s     %%gw7 r   c                r    | j                   j                  r!t        || j                   j                         yy)zAdd server_api parameters.N)rb   r   r7   )r   r   s     r   r   zAsyncConnection.add_server_apiO  s(    99GTYY%9%9:  r   c                6    t        j                         | _        y r   rU   rV   rW   r   s    r   update_last_checkin_timez(AsyncConnection.update_last_checkin_timeT  s    !%!1r   c                    || _         y r   )rY   )r   rY   s     r   update_is_writablez"AsyncConnection.update_is_writableW  s
    &r   c                D    t        j                         | j                  z
  S )z9Seconds since this socket was last checked into its pool.r>  r   s    r   idle_time_secondsz!AsyncConnection.idle_time_secondsZ  s    ~~$"8"888r   c                  K   | j                   rd }nt        j                  }| j                  |       d {    t	        |t
        t        gt              r.t        | j                        }t        | j                  ||       y  7 Pw)Nr   )rr   r-   ERRORr   r   IOErrorOSErrorr2   r#   rb   r5   rQ   )r   r  r-  detailss       r   r5   z)AsyncConnection._raise_connection_failure^  sk       ::F+11Foof%%%egw;;<*4995G%dllE7S 	&s   4B	BAB	c                4    | j                   |j                   k(  S r   )rP   r   others     r   __eq__zAsyncConnection.__eq__z  s    yyEJJ&&r   c                    | |k(   S r    rK  s     r   __ne__zAsyncConnection.__ne__}  s    5=  r   c                ,    t        | j                        S r   )hashrP   r   s    r   __hash__zAsyncConnection.__hash__  s    DIIr   c                    dj                  t        | j                        | j                  xr dxs dt	        |             S )NzAsyncConnection({}){} at {}z CLOSED )formatreprrP   rT   rR   r   s    r   __repr__zAsyncConnection.__repr__  s8    ,33OKK%I+tH
 	
r   )
rP   r.   r   PoolrQ   ztuple[str, int]rR   r   rS   r   )r   Optional[float]returnNone)r   zAsyncMongoClient[Any]r   z"Optional[MutableMapping[str, Any]]r[  rZ  r[  r\  )r[  dict[str, Any])r[  Hello[dict[str, Any]])r   zOptional[Any]r   Optional[int]r[  r_  )"r  strr  MutableMapping[str, Any]r  rF   r  CodecOptions[Mapping[str, Any]]r  r   r  z#Optional[Sequence[Union[str, int]]]r  zOptional[ReadConcern]r   zOptional[WriteConcern]r   r   r   zOptional[_CollationIn]r	  Optional[AsyncClientSession]r   Optional[AsyncMongoClient[Any]]r
  r   r   r   r   zOptional[Mapping[str, Any]]r   r   r[  r^  )r  bytesr  r   r[  r\  )r  r`  r[  zUnion[_OpReply, _OpMsg])r   r   r[  r\  )r  rf  r  r   r[  r\  )r  r   r  rf  r  rc  r[  r^  )F)r  r   r[  r\  )r   re  r	  rd  r[  r\  )r-  zOptional[str]r[  r\  r[  r   )r   rb  r	  rd  r   re  r[  r\  )r   rb  r[  r\  )rY   r   r[  r\  )r[  float)r  r  r[  r	   )rL  r   r[  r   r[  r   )r[  ra  )'__name__
__module____qualname____doc__r   r   r   r   r   r   r   r   r   r   r   r6   PRIMARYr   r   r  r   r   r  r  r"  r   r   r.  r9  r   r   r?  rA  rC  r5   rM  rP  rS  rX  rO  r   r   rK   rK   o   sk   9"&9" 9" !	9"
 9" 9"v/+2T	>&#@@-S'S +S 
	Sj 
 (6'='=9N@D.204*/,00426 %#37 %#W8W8 'W8 %	W8
 7W8 W8 >W8 ,W8 .W8 $(W8 *W8 .W8 0W8 W8 W8  1!W8" #W8$ 
%W8 W8r8"	8d	3$):Y	$ D5@\	**8)8 .8 0	8
 
8;
2'98'!
r   rK   c                      e Zd ZdZy)_PoolClosedErrorzZInternal error raised when a thread tries to get a connection from a
    closed pool.
    N)rj  rk  rl  rm  rO  r   r   rp  rp    s    r   rp  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 r   )collectionsdefaultdictr   _generations_generationr   s    r   r   z_PoolGeneration.__init__  s    1<1H1H1Mr   c                <    || j                   S | j                  |   S )z,Get the generation for the given service_id.rw  rv  r   ru   s     r   r   z_PoolGeneration.get  s%    ###  ,,r   c                    | j                   S )z"Get the Pool's overall generation.)rw  r   s    r   rp   z_PoolGeneration.get_overall  s    r   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.r   Nry  rz  s     r   incz_PoolGeneration.inc  s\    A"// 3
!!*-2-3 j)Q.)r   c                *    || j                  |      k7  S )z?Return if the given generation for a given service_id is stale.)r   r   rn   ru   s      r   stalez_PoolGeneration.stale  s    dhhz***r   Nr]  )ru   Optional[ObjectId]r[  r   ri  )ru   r  r[  r\  rn   r   ru   r  r[  r   )rj  rk  rl  r   r   rp   r}  r  rO  r   r   rr  rr    s    - /+r   rr  c                      e Zd ZdZdZdZy)	PoolStater         N)rj  rk  rl  PAUSEDREADYCLOSEDrO  r   r   r  r    s    FEFr   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)'rY  Nc                   |j                   rt        j                  | _        nt        j                  | _        d| _        t        j                         | _        t               | _
        t               | _        t        | j                        | _        d| _        d| _        d| _        t%               | _        t)        j*                         | _        || _        || _        || _        | j2                   xr: | j0                  j4                  duxr  | j0                  j4                  j6                  | _        | j2                   | _        t        | j                        | _        d| _        | j0                  j>                  | _        | j>                  stA        d      | _        t        | j                        | _        | j0                  jB                  | _"        d| _#        || _$        | j6                  r\| j0                  j4                  J | j0                  j4                  jK                  | j.                  | j0                  jL                         | j8                  r~tO        jP                  tR        jT                        r[tW        tN        ftX        jZ                  | jH                  | j.                  d   | j.                  d   d| j0                  jL                   d| _.        t               | _/        d| _0        d| _1        y)z
        :param address: a (hostname, port) tuple
        :param options: a PoolOptions instance
        :param is_sdam: whether to call hello for each new AsyncConnection
        r   r   Ninfr  r  r  r  )2pause_enabledr  r  stater  _check_interval_secondsrt  dequeconnssetactive_contextsr'   lockr&   _max_connecting_condactive_socketsnext_connection_idrY   rr  rn   osgetpidpidrQ   rb   rS   rc   re   rf   	size_condrequestsmax_pool_sizerh  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   rQ   optionsrS   	client_ids        r   r   zPool.__init__  sI      "))DJ"DJ ()$ :E9J9J9L
:=%&(	$;DII$F!"#+/
 #$99;	  <		**$6<		**;; 	
 (,||#3 
 1;!YY44!!!&uD %<DII$F!#yy77#  99--999II&&;;dii;; ##(:(G(G(V"0==<<?<<? ))// %& 7:e
r   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        t        j                   | j"                  | j                  d   | j                  d          d d d       d {    y 7 7 # 1 d {  7  sw Y   y xY ww)Nr   r   r  )r  r  r  r  re   rb   rc   publish_pool_readyrQ   rf   r(   r$  r%  r&  r*   r)   
POOL_READYr}   r   s    r   rr   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    r   rT   zPool.closed  s    zzY----r   c                F	  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 t4        sIt7        j8                  D 
cg c]!  }
|
j;                  t<        j>                        # c}
ddi d {    n.D ])  }
|
j;                  t<        j>                         d {    + | j@                  r|J |jC                  | jD                         | jF                  rktI        jJ                  tL        jN                        rGtQ        tH        tR        j>                  | jT                  | jD                  d   | jD                  d          y y y |t        j                  k7  r| j@                  r"|J |jW                  | jD                  ||       | jF                  rjtI        jJ                  tL        jN                        rGtQ        tH        tR        jX                  | jT                  | jD                  d   | jD                  d   |       t4        sIt7        j8                  D 
cg c]!  }
|
j;                  t<        jZ                        # c}
ddi d {    y D ])  }
|
j;                  t<        jZ                         d {    + y 7 O7 57 y# 1 d {  7  sw Y   xY wc c}
w 7 07 c c}
w 7 c7 8w)Nr   return_exceptionsTr   r  )ru   interrupt_connections)r  r  r  r  	serviceId).r  r  rT   rb   r  r   r  r  rn   r}  r  r  r  r  r  r  rt  r  ru   appendr  r  
notify_allr  r2  rc   r6  asynciogatherr   r-   POOL_CLOSEDre   publish_pool_closedrQ   rf   r(   r$  r%  r&  r*   r)   r}   publish_pool_clearedPOOL_CLEAREDr   )r   r3  pauseru   r  	old_statenewpidsocketsdiscardkeeprP   contextrd   s                r   _resetzPool._reset"  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..	 nnV]^ddoo&<&H&HI^&*  
 $ ND//*@*L*LMMMN$$ ,,,--dll;'',>,K,KGMM,Z&4@@!__#||A#||A -[' I,,,(($00022#-.C 3 
 ++0B0O0OPWP]P]0^* 8 E E!%#'<<?#'<<?", nnPWXdoo&<&B&BCX&*  
 $ HD//*@*F*FGGGHe 	%  	%  	%  	%  	%  	%R _ N@ Y Hs   R!Q.R!Q7R!Q1R!F.Q70R!;Q4<6R!2&R
R!"R#,R!RE9R!	&R/
R!9R:,R!&R'R!1R!4R!7R
=R >R
R!R!R!R!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)rY   r  r  rA  )r   rY   _sockets      r   rA  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)r3  ru   r  r  )r   ru   r  s      r   resetz
Pool.reset  s+      kkJF[  
 	
 	
s   " "c                F   K   | j                  dd       d {    y 7 w)NF)r3  r  r  r   s    r   reset_without_pausezPool.reset_without_pause  s     kkUk333s   !!c                D   K   | j                  d       d {    y 7 w)NT)r3  r  r   s    r   r3  z
Pool.close  s     kkk%%%s     c                :    | j                   j                  ||      S r   )rn   r  r  s      r   stale_generationzPool.stale_generation  s    xx~~c:..r   c           	       K   | j                   4 d{    | j                  t        j                  k7  r	 ddd      d{    yddd      d{    | j                  j
                  Ng }| j                   4 d{    | j                  r| j                  d   j                         | j                  j
                  kD  rj|j                  | j                  j                                | j                  r5| j                  d   j                         | j                  j
                  kD  rjddd      d{    t        sIt        j                  |D cg c]!  }|j                  t        j                        # c}ddi d{    n.|D ])  }|j                  t        j                         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*                  j1                          ddd      d{    | j                   4 d{    | xj(                  dz  c_        | j                   j1                          ddd      d{    y| xj,                  dz  c_        d}ddd      d{    | j3                          d{   }d}| j                   4 d{    | j4                  j7                         |k7  rd}|s@| j                  j9                  |       | j:                  j=                  |j>                         ddd      d{    |r|j                  t        j@                         d{    	 |rT| j*                  4 d{    | xj,                  dz  c_        | j*                  j1                          ddd      d{    | j                   4 d{    | xj(                  dz  c_        | j                   j1                          ddd      d{    y	 |rT| j*                  4 d{    | xj,                  dz  c_        | j*                  j1                          ddd      d{    | j                   4 d{    | xj(                  dz  c_        | j                   j1                          ddd      d{    7 7 o7 a# 1 d{  7  sw Y   rxY w7 L7 # 1 d{  7  sw Y   xY wc c}w 7 e7 ;7 &7 7 7 # 1 d{  7  sw Y   xY w7 7 d7 P7 # 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 K# 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7 7 u# 1 d{  7  sw Y   xY w7 y7 =# 1 d{  7  sw Y   NxY w# |rl| j*                  4 d{  7   | xj,                  dz  c_        | j*                  j1                          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                   j1                          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  Tr   F)!r  r  r  r  rb   max_idle_time_secondsr  rC  r  popr6  r  r  r   r-   IDLEr  lenr  min_pool_sizer  r  r  r  notifyconnectrn   rp   
appendleftr  r  rs   r   )r   reference_generationclose_connsrP   incrementedr   s         r   remove_stale_socketszPool.remove_stale_sockets  sz     99 	 	zzY__,	 	 	 	 	 99**6Kyy 9 9JJ

288:TYY=\=\\&&tzz~~'78 JJ

288:TYY=\=\\9 9 nnOZ[tdoo&<&A&AB[&*  
 ( GD//*@*E*EFFFG ~~ # #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 J J xx++-1EE%)
%

--d3,,44T5H5HIJ J //*@*F*FGGG#88 ; ;*1188:; ;  >> , ,MMQ&MNN))+, , ,  #88 ; ;*1188:; ;  >> , ,MMQ&MNN))+, ,K +	 	 	 	 	 	9 9 9 9 9 \ G# # # # # # #' '.; ; ; ; ;, , , , ,7' ' ' ' ,J J J J J H
; ; ; ; ;, , , , ,	; ; ; ; ;, , , , , #88 ; ;*1188:; ; ; ; ;  >> , ,MMQ&MNN))+, , , , ,sA  _V-_V6_V0_V3-_ W_B*W/_:W;_&W(>
_W-	,_5W06_W3_;W?_W6_$W?_W9_W?'_2W<3_:[< 
X[< Y)[< 4X5[< 9_X_0X!?_
X_X7 _#0X=_X:_$Y;[< Y[< Y+[< 5Y.6[< 9A"Y4[< &Y1'([< Z
[< _'Z(_+0Z_&Z'_;Z)<_?0Z//_:Z,;__[_0[
_[_'[ (_+0[&_&[#'_0_3_6W	<V?=W		__W%WW% _0_3_6_9_<_?XXX_[< [< __!X4'X*(X4/	_:_=YYY_[< Y(YY(#	[< .[< 1[< 4Z:Y=;Z	[< __Z&ZZ&!	_,_/[5Z86[=__
[[[	_#_&[9,[/-[94_<_\
_0]_]_](]]($_;]>
<_ 0_0_;^><___	___c                
  K   | j                   4 d{    | j                  }| xj                  dz  c_        t               }| j                  j	                  |       ddd      d{    | j
                  j                  }| j                  r |J |j                  | j                         | j                  rjt        j                  t        j                        rGt        t        t         j"                  | j$                  | j                  d   | j                  d          	 t'        | j                  | j
                         d{   }tC        || | j                  | jD                        }| j                   4 d{    | j                  j	                  |jF                         | j                  j+                         ddd      d{    jH                  r|jF                  jK                          	 | jD                  s)|jM                          d{    |jN                  | _'        |r|jQ                  |d       |jS                          d{    |r7|jV                  jX                  j[                  |j\                         d{    |S 7 7 5# 1 d{  7  sw Y   FxY w7 m# t(        $ r}| j                   4 d{  7   | j                  j+                         ddd      d{  7   n# 1 d{  7  sw Y   nxY w| j                  r/|J |j-                  | j                  t.        j0                         | j                  rt        j                  t        j                        rnt        t        t         j2                  | j$                  | j                  d   | j                  d   t5        t.        j0                        t.        j0                         t7        |t8        t:        gt<              r-t?        | j
                        }tA        | j                  ||        d}~ww xY w7 7 x# 1 d{  7  sw Y   xY w7 F7 # t(        $ r | j                   4 d{  7   | j                  j+                  |jF                         ddd      d{  7   n# 1 d{  7  sw Y   nxY w|jU                  t.        j0                         d{  7    w xY w7 m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.
        Nr   r   r  r  r  r  r   r,  rE  F)completed_handshake)/r  r  r3   r  addrb   rc   re   publish_connection_createdrQ   rf   r(   r$  r%  r&  r*   r)   CONN_CREATEDr}   r4   r  r  r/  r-   rF  r0  r+   r   rG  rH  r2   r#   r5   rK   rS   rs   	cancelledr2  r   rY   contribute_socketr"  r   r   	_topologyreceive_cluster_timer   )	r   handlerconn_idtmp_contextrd   networking_interfacer  rI  rP   s	            r   r  zPool.connect  s     99 	2 	2--G##q(#.0K  $$[1	2 	2 II..	  (((00wG##(:(G(G(V"0==<<?<<?#*	)GVZV_V_)`#` 6 3T4<<RVR^R^_99 	6 	6  $$T%8%89  ((5	6 	6   &&(	<<jjl""#'#3#3 ))$E)J##%%% ..**??@R@RSSSS	2 	2 	2 	2 	2, $a 	yy : :$$,,[9: : : : :$$ ,,,33LL'+A+G+G '',>,K,KGMM,Z&4@@!__#||A#||A'.;<R<X<XY066	 %'7!?Y!?@.tyy9)$,,wW/	4	6 	6 	6 	6 	6 #
 & 	yy B B$$,,T-@-@AB B B B B//"8">">???		 Ts  TJTAJ!T)J*B<T'#J: 
J7J: 3TQTAQTQ
*T>Q) Q#=Q) Q&Q)  4TTTT!J4'J*(J4/T7J: :
QP?KP?L5P? LP?L	LL	D*P??QT
TQ QQ T#Q) &Q) )S>RS>&R?-S>8R;9S>?S	SS	)S>6S97S>>Tc           	      K   | j                   j                  }t        j                         }| j                  r|J |j                  | j                         | j                  rit        j                  t        j                        rFt        t        t        j                  | j                  | j                  d   | j                  d          | j!                  ||       d{   }t        j                         |z
  }| j                  r+|J |j#                  | j                  |j$                  |       | j                  rut        j                  t        j                        rRt        t        t        j&                  | 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   r   r  r  r  )#rb   rc   rU   rV   re   $publish_connection_check_out_startedrQ   rf   r(   r$  r%  r&  r*   r)   CHECKOUT_STARTEDr}   	_get_connpublish_connection_checked_outrR   CHECKOUT_SUCCEEDEDr  r  r  rs   r  rw   rx   sysexc_infohandlery   r   r  r  r  )
r   r  rd   checkout_started_timerP   r(  pinnedexc_typeexc_val_s
             r   checkoutzPool.checkout0  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$$$ W 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        t$        j&                  | j(                  | j                  d   | j                  d   dt        j                  |       t+        | j                        }t-        | j                  t/        d      |       y y )Nr   r   <An error occurred while trying to establish a new connectionr  r  r  r  r-  r  r!  zconnection pool pausedrE  )r  r  r  rU   rV   re   rb   rc   #publish_connection_check_out_failedrQ   r,   
CONN_ERRORrf   r(   r$  r%  r&  r*   r)   CHECKOUT_FAILEDr}   r#   r5   r   )r   r  
emit_eventr(  rI  s        r   _raise_if_not_readyzPool._raise_if_not_ready  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^+ )r   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        t(        j*                  | 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  s|r|t        j                         z
  nd}tE        | 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  s|r|t        j                         z
  nd}tE        | 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                  |       d{   rsd}^	 | j[                  |
       d{   }| jL                  4 d{    | xjP                  dz  c_(        | jL                  jG                          ddd      d{    |d|_3        |S 7 7 7 # 1 d{  7  sw Y   xY w7 <7 7 G# 1 d{  7  sw Y   XxY w7 D7  # 1 d{  7  sw Y   1xY w7 !7 # tV        $ r | xjP                  dz  c_(        Y ,w xY w7 %# 1 d{  7  sw Y   6xY w7 #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                         d{  7   | 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        t(        j*                  | j,                  | j                  d   | j                  d   dt        jd                  |        w xY ww)z=Get or create a AsyncConnection. Can raise ConnectionFailure.Nr   r   zConnection pool was closedr  z?Attempted to check out a connection from closed connection poolT)r  Fr  r  )4r  r  r  r  rT   rU   rV   re   rb   rc   r  rQ   r,   r  rf   r(   r$  r%  r&  r*   r)   r  r}   rp  r  r  r   get_timeoutget_deadlinewait_queue_timeoutr  r   r  r  r%   r  _raise_wait_queue_timeoutr  r  r  r  r  popleft
IndexError	_perishedr  r  r   r-   rF  r  ry   )	r   r  r  r(  deadliner   rP   r  emitted_events	            r   r  zPool._get_conn  s     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99A(T^^%55t-dnngFFF }}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-QAI(T^^-="=t%5d6O6OQX%YYY  $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111# ?%)\\'\%BB#'#<#< ? ? MMQ.M 55<<>? ?9 ,| o -0	& 	& 	& 	& 	&	 G		 	 	 	$# # # # #+  Z & +*++ + + +$ 2
  C? ? ? ? ?4#<#< ? ? MMQ.M 55<<>? ? ? ? ?  	oo&<&B&BCCC~~ ( ("''1,'%%'	( ( ( ( ( !>>+.CC((9955AAAII..RR&D&O&OQY ++0B0O0OPWP]P]0^* 8 H H!%#'<<?#'<<?]<GG#+	 9	s  5`T(D,`$T+%`(T1>`	T.
B`U`A!U0U
1A4U&U;`U
`Y "U&#Y &U,>Y 	U)
Y !V"Y %A-V0VBV0#V=Y V-	Y #W$Y -W% W	W% Y WY 0WY WY 
`+`.`1U7T:8U?	`
U`U#UU#`&Y )Y ,U?2U53U?:	Y V0V*&V0)V**V0-Y 0W6V97W>	Y 	W% Y Y W"WW"Y %Y6W9
7Y;0X=+Y6X97Y=YYYYY .`Z`Z`A[7%`0[31`7\		=\ >\		D``c                n	  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        t(        j*                  | j,                  | j                  d   | j                  d   |j                         | j.                  t1        j2                         k7  r| j5                          d{    n| j6                  r)|j9                  t:        j<                         d{    n|j6                  r| j                  r9|J |j?                  | j                  |j                  t:        j@                         | j                  rt        j                   t"        j$                        r[t'        t        t(        jB                  | j,                  | j                  d   | j                  d   |j                  tE        t:        j@                        t:        j@                         nd}| j                  4 d{    | jG                  |jH                  |jJ                        rd}ni|jM                          |jO                  tQ        | jR                               | jT                  jW                  |       | jX                  j[                          ddd      d{    |r'|j9                  t:        j\                         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 7 # 1 d{  7  sw Y   xY w7 7 7 G# 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   r   r  r,  T)5rw   rx   ry   r  r  rb   rc   r  r  rs   re   publish_connection_checked_inrQ   rR   rf   r(   r$  r%  r&  r*   r)   	CHECKEDINr}   r  r  r  r  rT   r   r-   r  r/  rF  r0  r+   r  rq   ru   r?  rA  r   rY   r  r  r  r  r   r  r  r  r  r  r  )r   rP   txncursorrd   r   s         r   r   zPool.checkin  s    
 oo##"%%d+II..	99 	> 	>  (()<)<=	> 	>  (((33DLL$''J##(:(G(G(V"0::<<?<<?#'77 88ryy{"**,,,{{oo&<&H&HIII(($00077dgg/E/K/K ++0B0O0OPWP]P]0^* 8 D D!%#'<<?#'<<?+/77?@V@\@\]4::	 #
99 
; 
; ,,T__dooN%)
557//T5E5E0FG

--d31188:
; 
; //*@*F*FGGG>> 	$ 	$

a
"MMQM1$  A% NN!!#	$ 	$ 	$k	> 	> 	> 	> 	> - J*
; 
; 
; 
; 
; H	$ 	$ 	$ 	$ 	$s  A/R51Q2R55&Q"R5&Q'C.R5Q84R5
Q;DR5Q>R5"BR5R5 R(R5)R*R5>R?R5B	R R5RR5R5"Q5(Q+)Q50	R5;R5>R5R5R
RR	R5R5R5 R2&R)'R2.R5c                F  K   |j                         }| j                  j                  A|| j                  j                  kD  r(|j                  t        j
                         d{    y| j                  V| j                  dk(  s|| j                  kD  r8|j                         r(|j                  t        j                         d{    y| j                  |j                  |j                        r(|j                  t        j                         d{    yy7 7 V7 
w)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.
        NTr   F)rC  rb   r  r   r-   r  r  r9  rF  r  rq   ru   r   )r   rP   rC  s      r   r  zPool._perishede  s      !224 II++7!DII$C$CC//"8"="=>>>''3((A-1BTEaEa1a!oo&<&B&BCCC  $//B//"8">">??? ? D @s8   A"D!$D%A!D!DAD!DD!D!D!c           
        | j                   j                  }t        j                         |z
  }| j                  r/|J |j                  | j                  t        j                  |       | j                  rzt        j                  t        j                        rWt        t        t        j                   | 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   r   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: )rb   rc   rU   rV   re   r  rQ   r,   TIMEOUTrf   r(   r$  r%  r&  r*   r)   r  r}   r   r  r  r   r  r  r  r    rV  r  )r   r  rd   r(  r   	other_opss         r   r  zPool._raise_wait_queue_timeout  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
 	
r   c                V    t         r#| j                  D ]  }|j                  d         y y r   )r6  r  r   )r   rP   s     r   __del__zPool.__del__  s+     

 &%& r   )FN)rQ   rG   r  r1   rS   r   r  r  r]  rg  )TNF)
r3  r   r  r   ru   r  r  r   r[  r\  )rY   zOptional[bool]r[  r\  )NF)ru   r  r  r   r[  r\  r  )r  r   r[  r\  r   )r  "Optional[_MongoClientErrorHandler]r[  rK   )r  r  r[  z%AsyncGenerator[AsyncConnection, None])r  rh  r  r   r[  r\  )r  rh  r  r  r[  rK   )rP   rK   r[  r\  )rP   rK   r[  r   )r  rh  r[  r	   )rj  rk  rl  r   rr   propertyrT   r  rA  r  r  r3  r  r  r  
contextlibasynccontextmanagerr  r   r  r   r  r  r  rO  r   r   rY  rY    s_   
 (,TT T 	T
 &Tl" . . )-&+[H[H [H '	[H
  $[H 
[Hz= TY
,
LP
	
4&/C,JQf ##<@L%9L%	.L% $L%\6 [_%*5W	BI$V"H%
N&r   rY  )r
__future__r   r  rt  r  r%  r  r  rU   rM   typingr   r   r   r   r   r	   r
   r   r   bsonr   pymongor   r   #pymongo.asynchronous.client_sessionr   pymongo.asynchronous.helpersr   pymongo.asynchronous.networkr   pymongo.commonr   r   r   r   r   pymongo.errorsr   r   r   r   r   r   r   r   r    pymongo.hellor!   r"   pymongo.helpers_sharedr#   r$   pymongo.lockr%   r&   r'   pymongo.loggerr(   r)   r*   r+   pymongo.monitoringr,   r-   pymongo.network_layerr.   r/   r0   pymongo.pool_optionsr1   pymongo.pool_sharedr2   r3   r4   r5   pymongo.read_preferencesr6   pymongo.server_apir7   pymongo.server_typer8   pymongo.socket_checkerr9   r:   bson.objectidr;   pymongo.asynchronous.authr<   r=   !pymongo.asynchronous.mongo_clientr>   r?   pymongo.compression_supportr@   rA   rB   pymongo.messagerC   rD   pymongo.read_concernrE   rF   pymongo.typingsrG   rH   pymongo.write_concernrI   r6  rK   rp  rr  r  rY  rO  r   r   <module>r7     s   #     	 
  
 
 
 ' ) O 7 0 
 
 
 - O 
  a ` ,  4 . + 0!&6F\ 
 10462 Y
 Y
x| + +> @& @&r   