
    gh 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 d"llmmZmmnZnmoZomlZl d0d#Zpd%Zr G d& d'      Zs G d( d)e-      Zt G d* d+      Zu G d, d-      Zv G d. d/      Zwy# eq$ r d0d$ZpY Aw xY w)1    )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)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/opt/movilizia/ApiFast/venv/lib/python3.12/site-packages/pymongo/asynchronous/pool.py_set_non_inheritable_non_atomicrR   n   s    b'"b'5:-.    c                     y)z6Dummy function for platforms that don't provide fcntl.N )rO   s    rQ   rR   rR   w   s    rS   Fc                     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)selfr\   poolr]   r^   r_   s         rQ   __init__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                |    || j                   k(  ry|| _         | j                  j                  j                  |       y)z?Cache last timeout to avoid duplicate calls to conn.settimeout.N)r   r\   get_conn
settimeout)r   timeouts     rQ   set_conn_timeoutz AsyncConnection.set_conn_timeout   s3    d'''#		%%g.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: 2   okerrmsgcode  	maxTimeMS)r   	remainingr   r   rn   r   get_rttr   r#   r$   r   rf   int)	r   clientcmdr   rttmax_time_mstimeout_details	formattedr   s	            rQ   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&rS   c                .    d| _         | j                  rJ y NT)r   r   r   s    rQ   pin_txnzAsyncConnection.pin_txn   s    %%%%%rS   c                .    d| _         | j                  rJ y r   )r   r   r   s    rQ   
pin_cursorzAsyncConnection.pin_cursor   s    !??""?rS   c                   K   | j                         }|r|j                  |        d {    y | j                  t        j                         d {    y 7 -7 wN)r[   checkin
close_connr-   STALE)r   r   s     rQ   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)rn   
server_apirk   load_balancedrm   r"   CMD
LEGACY_CMDr   s    rQ   	hello_cmdzAsyncConnection.hello_cmd   sO     994==DII4K4K"&DOOQ''**Ay$??rS   c                B   K   | j                  d d        d {   S 7 wr   )_hellor   s    rQ   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   rd   rn   metadatart   compressorsr   r   connect_timeoutr   _credentials	mechanismusernamesourcepymongo.asynchronousr   r<   from_credentialsr]   speculate_commandra   rb   r   r   r!   re   rf   rg   rh   ri   logical_session_timeout_minutesis_readablerj   rk   server_typer8   	RSPrimaryRSSecondary	RSArbiterRSOtherRSGhostis_repl
Standaloneis_standaloneMongosrl   get_compression_contextru   rm   connection_idr   sasl_supported_mechsrx   parse_responsespeculate_succeededry   r   r   r{   getr}   )r   topology_versionheartbeat_frequencyr   performing_handshaker   credsr   ry   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		&&)+,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_messager   unpack_responser   _check_command_responserf   )r   replyunpacked_docsresponse_docs       rQ   _next_replyzAsyncConnection._next_replyY  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_timerp   boolrm   _raise_if_not_writabler   rl   r]   rg   ru   r   r   BaseExceptionr5   )r   dbnamespecread_preferencecodec_optionscheckallowable_errorsread_concernr  r   r   sessionr   retryable_writer   r   r   rp   r   errors                       rQ   r   zAsyncConnection.commanda  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.)rg   r   r0   r\   r   r  r5   )r   messagemax_doc_sizer  s       rQ   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/   rh   r  r5   )r   
request_idr  s      rQ   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)re   r   )r   r   s     rQ   r
  z&AsyncConnection._raise_if_not_writable  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)r
  r  )r   msgr  s      rQ   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   rf   )r   r  r  r  r   results         rQ   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)rd   ry   r~   rn   r   r   r   authenticatera   rb   r   rq   rp   publish_connection_readyr]   r^   rr   r(   isEnabledForloggingDEBUGr*   r)   
CONN_READYr   )r   r%  r   r   durations        rQ   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      rQ   r  z AsyncConnection.validate_session  s-     f,&T  - rS   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  )r`   _close_connrq   rp   publish_connection_closedr]   r^   rr   r(   r.  r/  r0  r*   r)   CONN_CLOSEDr   r+   )r   r7  s     rQ   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)r`   r   cancelr\   close	Exceptionr   s    rQ   r8  zAsyncConnection._close_conn@  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_SYNCrv   socket_closedr\   r   
is_closingr   s    rQ   conn_closedzAsyncConnection.conn_closedM  s9    &&44TYY5G5GHH99''))rS   c                .    |r|j                  ||       yy)zAdd $clusterTime.N)_send_cluster_time)r   r   r  r   s       rQ   r  z!AsyncConnection.send_cluster_timeT  s     %%gw7 rS   c                r    | j                   j                  r!t        || j                   j                         yy)zAdd server_api parameters.N)rn   r   r7   )r   r   s     rQ   r  zAsyncConnection.add_server_api^  s(    99GTYY%9%9:  rS   c                6    t        j                         | _        y r   ra   rb   rc   r   s    rQ   update_last_checkin_timez(AsyncConnection.update_last_checkin_timec  s    !%!1rS   c                    || _         y r   )re   )r   re   s     rQ   update_is_writablez"AsyncConnection.update_is_writablef  s
    &rS   c                D    t        j                         | j                  z
  S )z9Seconds since this socket was last checked into its pool.rH  r   s    rQ   idle_time_secondsz!AsyncConnection.idle_time_secondsi  s    ~~$"8"888rS   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   )r~   r-   ERRORr   r  IOErrorOSErrorr2   r#   rn   r5   r]   )r   r  r7  detailss       rQ   r5   z)AsyncConnection._raise_connection_failurem  sk       ::F+11Foof%%%egw;;<*4995G%dllE7S 	&s   4B	BAB	c                4    | j                   |j                   k(  S r   )r\   r   others     rQ   __eq__zAsyncConnection.__eq__  s    yyEJJ&&rS   c                    | |k(   S r   rU   rU  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 CLOSED )formatreprr\   r`   r^   r   s    rQ   __repr__zAsyncConnection.__repr__  s8    ,33OKK%I+tH
 	
rS   )
r\   r.   r   Poolr]   ztuple[str, int]r^   r   r_   r	  )r   Optional[float]returnNone)r   zAsyncMongoClient[Any]r   z"Optional[MutableMapping[str, Any]]rd  rc  rd  re  )rd  dict[str, Any])rd  Hello[dict[str, Any]])r   zOptional[Any]r   Optional[int]rd  rh  )"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	  rd  rg  )r  bytesr  r   rd  re  )r  ri  rd  zUnion[_OpReply, _OpMsg])r   r	  rd  re  )r  ro  r  r   rd  re  )r  r   r  ro  r  rl  rd  rg  )F)r%  r	  rd  re  )r   rn  r  rm  rd  re  )r7  zOptional[str]rd  re  rd  r	  )r   rk  r  rm  r   rn  rd  re  )r   rk  rd  re  )re   r	  rd  re  )rd  float)r  r  rd  r	   )rV  r   rd  r	  rd  r   )rd  rj  )'__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   r8  rC  r  r  rI  rK  rM  r5   rW  rY  r\  ra  rU   rS   rQ   rW   rW   ~   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'!
rS   rW   c                      e Zd ZdZy)_PoolClosedErrorzZInternal error raised when a thread tries to get a connection from a
    closed pool.
    N)rs  rt  ru  rv  rU   rS   rQ   ry  ry    s    rS   ry  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    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   r   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.r   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.)r   r   rz   r   s      rQ   stalez_PoolGeneration.stale  s    dhhz***rS   Nrf  )r   Optional[ObjectId]rd  r   rr  )r   r  rd  re  rz   r   r   r  rd  r	  )rs  rt  ru  r   r   r|   r  r  rU   rS   rQ   r{  r{    s    - /+rS   r{  c                      e Zd ZdZdZdZy)	PoolStater         N)rs  rt  ru  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)'rb  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_secondsr}  dequeconnssetactive_contextsr'   lockr&   _max_connecting_condactive_socketsnext_connection_idre   r{  rz   osgetpidpidr]   rn   r_   ro   rq   rr   	size_condrequestsmax_pool_sizerq  max_connecting_max_connecting_pendingr   publish_pool_creatednon_default_optionsr(   r.  r/  r0  r*   r)   POOL_CREATEDoperation_count_Pool__pinned_socketsncursorsntxns)r   r]   optionsr_   	client_ids        rQ   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
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        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  rq   rn   ro   publish_pool_readyr]   rr   r(   r.  r/  r0  r*   r)   
POOL_READYr   r   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.closed/  s    zzY----rS   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  )r   interrupt_connections)r  r'  r(  r)  	serviceId).r  r  r`   rn   r  r   r  r  rz   r  r  r  r  r  r  r  r}  r  r   appendr  r  
notify_allr  r<  ro   r@  asynciogatherr   r-   POOL_CLOSEDrq   publish_pool_closedr]   rr   r(   r.  r/  r0  r*   r)   r   publish_pool_clearedPOOL_CLEAREDr   )r   r=  pauser   r  	old_statenewpidsocketsdiscardkeepr\   contextrp   s                rQ   _resetzPool._reset3  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)re   r  r  rK  )r   re   _sockets      rQ   rK  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   r  r  )r   r   r  s      rQ   resetz
Pool.reset  s+      kkJF[  
 	
 	
s   " "c                F   K   | j                  dd       d {    y 7 w)NF)r=  r  r  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=  r  r   s    rQ   r=  z
Pool.close  s     kkk%%%s     c                :    | j                   j                  ||      S r   )rz   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
                  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  rn   max_idle_time_secondsr  rM  r  popr@  r  r  r   r-   IDLEr  lenr  min_pool_sizer  r  r  r  notifyconnectrz   r|   
appendleftr  r  r   r   )r   reference_generationclose_connsr\   incrementedr   s         rQ   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*  r6  rO  F)completed_handshake)/r  r  r3   r  addrn   ro   rq   publish_connection_createdr]   rr   r(   r.  r/  r0  r*   r)   CONN_CREATEDr   r4   r  r  r9  r-   rP  r:  r+   r  rQ  rR  r2   r#   r5   rW   r_   r   	cancelledr<  r   re   contribute_socketr,  r   r   	_topologyreceive_cluster_timer   )	r   handlerconn_idtmp_contextrp   networking_interfacer  rS  r\   s	            rQ   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&  )#rn   ro   ra   rb   rq   $publish_connection_check_out_startedr]   rr   r(   r.  r/  r0  r*   r)   CHECKOUT_STARTEDr   	_get_connpublish_connection_checked_outr^   CHECKOUT_SUCCEEDEDr  r  r  r   r  r   r   sysexc_infohandler   r   r  r  r  )
r   r  rp   checkout_started_timer\   r2  pinnedexc_typeexc_val_s
             rQ   checkoutzPool.checkoutA  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)  r7  r  r+  zconnection pool pausedrO  )r  r  r  ra   rb   rq   rn   ro   #publish_connection_check_out_failedr]   r,   
CONN_ERRORrr   r(   r.  r/  r0  r*   r)   CHECKOUT_FAILEDr   r#   r5   r   )r   r  
emit_eventr2  rS  s        rQ   _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^+ )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        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  r`   ra   rb   rq   rn   ro   r  r]   r,   r  rr   r(   r.  r/  r0  r*   r)   r  r   ry  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-   rP  r  r   )	r   r  r  r2  deadliner   r\   r  emitted_events	            rQ   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  r6  T)5r   r   r   r  r  rn   ro   r  r  r   rq   publish_connection_checked_inr]   r^   rr   r(   r.  r/  r0  r*   r)   	CHECKEDINr   r  r  r  r  r`   r   r-   r  r9  rP  r:  r+   r  r}   r   rI  rK  r	  re   r  r  r  r  r   r  r  r  r  r  r  )r   r\   txncursorrp   r   s         rQ   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)rM  rn   r  r   r-   r  r  rC  rP  r  r}   r   r   )r   r\   rM  s      rQ   r  zPool._perishedv  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: )rn   ro   ra   rb   rq   r  r]   r,   TIMEOUTrr   r(   r.  r/  r0  r*   r)   r  r   r   r  r  r   r  r  r  r    r_  r  )r   r  rp   r2  r   	other_opss         rQ   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
 	
rS   c                V    t         r#| j                  D ]  }|j                  d         y y r   )r@  r  r   )r   r\   s     rQ   __del__zPool.__del__  s+     

 &%& rS   )FN)r]   rG   r  r1   r_   r	  r  r  rf  rp  )TNF)
r=  r	  r  r	  r   r  r  r	  rd  re  )re   zOptional[bool]rd  re  )NF)r   r  r  r	  rd  re  r  )r  r   rd  re  r   )r  "Optional[_MongoClientErrorHandler]rd  rW   )r  r  rd  z%AsyncGenerator[AsyncConnection, None])r  rq  r  r	  rd  re  )r  rq  r  r  rd  rW   )r\   rW   rd  re  )r\   rW   rd  r	  )r  rq  rd  r	   )rs  rt  ru  r   r~   propertyr`   r  rK  r  r  r=  r  r  r  
contextlibasynccontextmanagerr  r	  r  r   r  r  r  rU   rS   rQ   rb  rb    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&rS   rb  )rO   r   rd  re  )x
__future__r   r  r}  r!  r/  r  r  ra   rY   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   rM   rJ   rK   rL   rR   ImportErrorr@  rW   ry  r{  r  rb  rU   rS   rQ   <module>rA     s8   #     	 
  
 
 
 ' ) O 7 0 
 
 
 - O 
  a ` ,  4 . + 0!&6F\ 
 10462E99/ Y
 Y
x| + +> @& @&i  EE	Es   2E8 8	FF