
    nh=                       d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	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.m/Z/m0Z0 d dl1m2Z2m3Z3m4Z4 d dl5m6Z6m7Z7m8Z8m9Z9 d dl:m;Z;m<Z< d dl=m>Z>m?Z?m@Z@ d dlAmBZB d dlCmDZDmEZEmFZFmGZGmHZH d dlImJZJ d dlKmLZL d dlMmNZN d dlOmPZP d dlQmRZR e
rLd dlmSZS d dlTmUZU d dlVmWZW d dlmXZX d dlYmZZZm[Z[ d dl\m]Z]m^Z^m_Z_ d dl`maZambZb d dlcmdZd d dlImeZe d d lfmgZgmhZh d d!limjZj 	 d d"lkmlZlmmZmmnZnmkZk d0d#Zod%Zq G d& d'      Zr G d( d)e,      Zs G d* d+      Zt G d, d-      Zu G d. d/      Zvy# ep$ r d0d$ZoY 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)_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)_CancellationContext_configured_protocol_interface_get_timeout_details_raise_connection_failureformat_timeout_details)ReadPreference)_add_to_command)SERVER_TYPE)SocketChecker)SSLError)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     /var/www/html/SchoolMeal/SchoolMeal/pds_admin_SchoolMeal/Backend/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)>AsyncConnectionzStore a connection with some metadata.

    :param conn: a raw connection object
    :param pool: a Pool instance
    :param address: the server's (host, port)
    :param id: the id of this socket in it's pool
    c                   t        j                  |      | _        || _        || _        || _        d| _        t        j                         | _	        d| _
        d| _        t        | _        t        | _        t         | _        t$        | _        d| _        d| _        d| _        d| _        |j0                  j2                  | _        |j6                  | _        |j8                  | _        |j0                  j:                  | _        d | _        tA               | _!        d | _"        d | _#        d | _$        |jJ                  | _&        | jL                  jO                         | _(        d| _)        tU               | _+        |j0                  | _        d| _,        d | _-        d | _.        d| _/        d| _0        d| _1        | j0                  jd                  | _3        d| _4        |jj                  | _5        t        j                         | _6        d | _7        y )NFg        )8weakrefrefpool_refconnaddressid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_contextr8   socket_checkeroidc_token_gen_idnegotiated_mechsauth_ctxgenpool_genget_overall
generationreadyr0   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^   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   rm   r   get_rttr   r2   r4   r   re   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)rm   
server_apirj   load_balancedrl   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   rc   rm   metadatars   compressorsr   r   connect_timeoutr   _credentials	mechanismusernamesourcepymongo.asynchronousr   r<   from_credentialsr]   speculate_commandr`   ra   r   r   r!   rd   re   rf   rg   rh   logical_session_timeout_minutesis_readableri   rj   server_typer7   	RSPrimaryRSSecondary	RSArbiterRSOtherRSGhostis_repl
Standaloneis_standaloneMongosrk   get_compression_contextrt   rl   connection_idr   sasl_supported_mechsrw   parse_responsespeculate_succeededrx   r   r   rz   getr|   )r   topology_versionheartbeat_frequencyr   performing_handshaker   credsr   rx   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_responsere   )r   replyunpacked_docsresponse_docs       rQ   _next_replyzAsyncConnection._next_replyV  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_timero   boolrl   _raise_if_not_writabler   rk   r]   rf   rt   r   r   BaseExceptionr3   )r   dbnamespecread_preferencecodec_optionscheckallowable_errorsread_concernr   r   r   sessionr   retryable_writer   r   r   ro   r   errors                       rQ   r   zAsyncConnection.command^  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.)rf   r   r.   r\   r   r
  r3   )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-   rg   r
  r3   )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)rd   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   re   )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)rc   rx   r}   rm   r   r   r   authenticater`   ra   r   rp   ro   publish_connection_readyr]   r^   rq   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_connrp   ro   publish_connection_closedr]   r^   rq   r&   r-  r.  r/  r(   r'   CONN_CLOSEDr   r)   )r   r6  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   r7  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_SYNCru   socket_closedr\   r   
is_closingr   s    rQ   conn_closedzAsyncConnection.conn_closedJ  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_timeQ  s     %%gw7 rS   c                r    | j                   j                  r!t        || j                   j                         yy)zAdd server_api parameters.N)rm   r   r6   )r   r   s     rQ   r  zAsyncConnection.add_server_api[  s(    99GTYY%9%9:  rS   c                6    t        j                         | _        y r   r`   ra   rb   r   s    rQ   update_last_checkin_timez(AsyncConnection.update_last_checkin_time`  s    !%!1rS   c                    || _         y r   )rd   )r   rd   s     rQ   update_is_writablez"AsyncConnection.update_is_writablec  s
    &rS   c                D    t        j                         | j                  z
  S )z9Seconds since this socket was last checked into its pool.rG  r   s    rQ   idle_time_secondsz!AsyncConnection.idle_time_secondsf  s    ~~$"8"888rS   c                  K   | j                   rd }nt        j                  }| j                  |       d {    t	        |t
        t        t        f      r.t        | j                        }t        | j                  ||       y  7 Nw)Nr   )r}   r+   ERRORr   r  IOErrorOSErrorr9   r2   rm   r3   r]   )r   r  r6  detailss       rQ   r3   z)AsyncConnection._raise_connection_failurej  sh       ::F+11Foof%%%egw9:*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   rT  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   Optional[float]returnNone)r   r>   r   z"Optional[MutableMapping[str, Any]]rc  rb  rc  rd  )rc  dict[str, Any])rc  r!   )r   zOptional[Any]r   Optional[int]rc  zHello[dict[str, Any]])"r  strr  MutableMapping[str, Any]r  rF   r  r:   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]r  r  r   r  r   zOptional[Mapping[str, Any]]r   r  rc  rf  )r  bytesr  r   rc  rd  )r  rg  rc  zUnion[_OpReply, _OpMsg])r   r  rc  rd  )r  rl  r  r   rc  rd  )r  r   r  rl  r  r:   rc  rf  )F)r$  r  rc  rd  )r   rk  r  rj  rc  rd  )r6  zOptional[str]rc  rd  rc  r  )r   ri  r  rj  r   rk  rc  rd  )r   ri  rc  rd  )rd   r  rc  rd  )rc  float)r  r
  rc  r	   )rU  r   rc  r  rc  r   )rc  rh  )'__name__
__module____qualname____doc__r   r   r   r   r   r   r   r   r   r   r   r5   PRIMARYr   r   r  r   r	  r  r"  r+  r  r   r7  rB  r  r  rH  rJ  rL  r3   rV  rX  r[  r`  rU   rS   rQ   rW   rW   ~   sa   7"&7" 7" !	7"
 7"r/&-O	>&#@@-S'S +S 
	Sj 
 (6'='=&;@D.204*/,004-1 %#37 %#W8W8 'W8 %	W8
 $W8 W8 >W8 ,W8 .W8 $(W8 *W8 .W8 +W8 W8 W8  1!W8" #W8$ 
%W8 W8r8"	8d	3$):F	$ D0;W	**8)8 .8 +	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)rp  rq  rr  rs  rU   rS   rQ   rv  rv    s    rS   rv  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   ry   r   s      rQ   stalez_PoolGeneration.stale  s    dhhz***rS   Nre  )r   Optional[ObjectId]rc  r   ro  )r   r  rc  rd  ry   r   r   r  rc  r  )rp  rq  rr  r   r   r{   r  r  rU   rS   rQ   rx  rx    s    - /+rS   rx  c                      e Zd ZdZdZdZy)	PoolStater         N)rp  rq  rr  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)'ra  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 handshake: whether to call hello for each new AsyncConnection
        r   r   Ninfr  r&  r'  r(  )2pause_enabledr  r  stater  _check_interval_secondsrz  dequeconnssetactive_contextsr%   lockr$   _max_connecting_condactive_socketsnext_connection_idrd   rx  ry   osgetpidpidr]   rm   	handshakern   rp   rq   	size_condrequestsmax_pool_sizern  max_connecting_max_connecting_pendingr   publish_pool_creatednon_default_optionsr&   r-  r.  r/  r(   r'   POOL_CREATEDoperation_count_Pool__pinned_socketsncursorsntxns)r   r]   optionsr  	client_ids        rQ   r   zPool.__init__  sB      "))DJ"DJ ()$ )4(9(9(;
:=%&(	$;DII$F!"#+/
 #$99;	" NN <		**$6<		**;; 	
 $(>> 
 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  rp   rm   rn   publish_pool_readyr]   rq   r&   r-  r.  r/  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                  K   | j                   }| j                  4 d {    | j                  r	 d d d       d {    y | j                  j                  r:|r8| j                  j
                  s"| j                   t        j                  c}| _         | j                  j                  |       t        j                         }| j                  |k7  r|| _        d| _        d| _        |'| j                  t!        j"                         c}| _        ntt!        j"                         }t!        j"                         }	| j                  D ]4  }
|
j$                  |k(  r|j'                  |
       $|	j'                  |
       6 |}|	| _        |rt        j(                  | _         | j*                  j-                          | j                  j-                          |r!| j.                  D ]  }|j1                           d d d       d {    | j                  j2                  }|rD ])  }
|
j5                  t6        j8                         d {    + | j:                  r|J |j=                  | j>                         | j@                  rktC        jD                  tF        jH                        rGtK        tB        tL        j8                  | jN                  | j>                  d   | j>                  d          y y y |t        j                  k7  r| j:                  r"|J |jQ                  | j>                  ||       | j@                  rjtC        jD                  tF        jH                        rGtK        tB        tL        jR                  | jN                  | j>                  d   | j>                  d   |       D ])  }
|
j5                  t6        jT                         d {    + y 7 7 7 # 1 d {  7  sw Y   xY w7 7 )w)Nr   r   r  )r   interrupt_connections)r  r&  r'  r(  	serviceId)+r  r  r_   rm   r  r   r  r  ry   r  r  r  r  r  r  r  rz  r  r   appendr  r  
notify_allr  r;  rn   r   r+   POOL_CLOSEDrp   publish_pool_closedr]   rq   r&   r-  r.  r/  r(   r'   r   publish_pool_clearedPOOL_CLEAREDr   )r   r<  pauser   r  	old_statenewpidsocketsdiscardkeepr\   contextro   s                rQ   _resetzPool._reset0  sA     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..	  Joo&<&H&HIIIJ$$ ,,,--dll;'',>,K,KGMM,Z&4@@!__#||A#||A -[' I,,,(($00022#-.C 3 
 ++0B0O0OPWP]P]0^* 8 E E!%#'<<?#'<<?",   Doo&<&B&BCCCDM 	%  	%  	%  	%  	%  	%P J> Ds   O3OO3OO3OO3F.O0O3;O<AO3?O. FO3O1O3O3O3O+O!O+&	O31O3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)rd   r  r  rJ  )r   rd   _sockets      rQ   rJ  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   )ry   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
                  g }| 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{    |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$                  j+                          ddd      d{    | j                  4 d{    | xj"                  dz  c_        | j                  j+                          ddd      d{    y| xj&                  dz  c_        d}ddd      d{    | j-                          d{   }d}| j                   4 d{    | j.                  j1                         |k7  rd}|s@| j                  j3                  |       | j4                  j7                  |j8                         ddd      d{    |r|j                  t        j:                         d{    	 |rT| j$                  4 d{    | xj&                  dz  c_        | j$                  j+                          ddd      d{    | j                  4 d{    | xj"                  dz  c_        | j                  j+                          ddd      d{    y	 |rT| j$                  4 d{    | xj&                  dz  c_        | j$                  j+                          ddd      d{    | j                  4 d{    | xj"                  dz  c_        | j                  j+                          ddd      d{    7 J7 7 # 1 d{  7  sw Y   "xY w7 7 F# 1 d{  7  sw Y   WxY w7 37 7 7 7 # 1 d{  7  sw Y   xY w7 7 \7 H7 # 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 C# 1 d{  7  sw Y   TxY w7 37 7 # 1 d{  7  sw Y   xY w7 7 # 1 d{  7  sw Y   yxY w7 7 m# 1 d{  7  sw Y   ~xY w7 q7 5# 1 d{  7  sw Y   FxY w# |rl| j$                  4 d{  7   | xj&                  dz  c_        | j$                  j+                          ddd      d{  7   n# 1 d{  7  sw Y   nxY w| j                  4 d{  7   | xj"                  dz  c_        | j                  j+                          ddd      d{  7   w # 1 d{  7  sw Y   w xY wxY ww)zRemoves stale sockets then adds new ones if pool is too small and
        has not been reset. The `reference_generation` argument specifies the
        `generation` at the point in time this operation was requested on the
        pool.
        NTr   F)r  r  r  r  rm   max_idle_time_secondsr  rL  r  popr   r+   IDLEr  lenr  min_pool_sizer  r  r  r  notifyconnectry   r{   
appendleftr  r  r~   r   )r   reference_generationclose_connsr\   incrementedr   s         rQ   remove_stale_socketszPool.remove_stale_sockets  s.     99 	 	zzY__,	 	 	 	 	 99**6Kyy 9 9JJ

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

288:TYY=\=\\9 9 $ Coo&<&A&ABBBC ~~ # #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 C# # # # # # #' '.; ; ; ; ;, , , , ,7' ' ' ' ,J J J J J H
; ; ; ; ;, , , , ,	; ; ; ; ;, , , , , #88 ; ;*1188:; ; ; ; ;  >> , ,MMQ&MNN))+, , , , ,s#  ^U^U&^U ^U#,^?U< ^B*V.^9U?:+^%V&^=V>^;V'<^V^$V'1^<V!=^V'^"V$#^*Z$ :V=;Z$ >W=Z$ $W %Z$ )^;W<^?0W	/^:W;^W^0W%^W"^W=+Z$ 6W:7Z$ XZ$ %X&Z$ )A"XZ$ X(Z$ ?X2 Z$ ^X5^0X;^X8^+Y,^/0Y^*Y+^1^Y,^0Y27^Y/^Z^0Z^Z^ ^#^&U9,U/-U94	^?^VV	V	^^^!^$^'V:-V0.V:5^=Z$  Z$ ^^	WWW	^"^%W7+W.,W73^:Z$ =XXX	Z$ Z$ Z$ X/"X%#X/*	Z$ 5^8^;YYY		^^Y)Y Y)%^/^2Z8Y;9Z 	^^Z!ZZ!^$]?7Z:
8]?<0[>,]?7[:8]?>\\\]?#\&
$]?(0]*]?#]&$]?*]<0]31]<8]??^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                        }| j                   4 d{    | j                  j	                  |jD                         | j                  j+                         ddd      d{    jF                  r|jD                  jI                          	 | jJ                  r)|jM                          d{    |jN                  | _'        |r|jQ                  |d       |jS                          d{    |r7|jV                  jX                  j[                  |j\                         d{    |S 7 }7 *# 1 d{  7  sw Y   ;xY w7 b# 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:        t<        f      r-t?        | j
                        }tA        | j                  ||        d}~ww xY w7 7 v# 1 d{  7  sw Y   xY w7 D7 	# t(        $ r | j                   4 d{  7   | j                  j+                  |jD                         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 k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)  r5  rN  F)completed_handshake)/r  r  r0   r  addrm   rn   rp   publish_connection_createdr]   rq   r&   r-  r.  r/  r(   r'   CONN_CREATEDr   r1   r
  r  r8  r+   rO  r9  r)   r  rP  rQ  r9   r2   r3   rW   r~   	cancelledr;  r  r   rd   contribute_socketr+  r   r   	_topologyreceive_cluster_timer   )	r   handlerconn_idtmp_contextro   networking_interfacer  rR  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<<Q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	 %'7H!=>.tyy9)$,,wW/	4	6 	6 	6 	6 	6 #
 & 	yy B B$$,,T-@-@AB B B B B//"8">">???		 Ts  S7JS7AJS7)J*B<S7'#J/ 
J,J/ (S77P:8S7;AQ <S7P=*S73Q Q=Q QQ 4S7	S4
S7S7J)JJ)$S7,J/ /
P79P2	K
P2K<*P25K86P2<L	LL	
D(P22P77S7=S7 QQ	QS7Q Q S15Q86S1:&R2 S1+R.,S12S	8R;9S	 )S1)S,*S11S7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%  )#rm   rn   r`   ra   rp   $publish_connection_check_out_startedr]   rq   r&   r-  r.  r/  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  ro   checkout_started_timer\   r1  pinnedexc_typeexc_val_s
             rQ   checkoutzPool.checkout,  s    & II..	 $ 0  (((::4<<H##(:(G(G(V"0AA<<?<<? ^^$97^KK>>#&;;  (((44T\\477HU##(:(G(G(V"0CC<<?<<?#'77#	yy > >$$(()<)<=> >J  ??yy    %%))$/

a
      yy # #%%))$/"# # # [[,,t$$$ 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(  r6  r  r*  zconnection pool pausedrN  )r  r  r  r`   ra   rp   rm   rn   #publish_connection_check_out_failedr]   r*   
CONN_ERRORrq   r&   r-  r.  r/  r(   r'   CHECKOUT_FAILEDr   r2   r3   r   )r   r  
emit_eventr1  rR  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_   r`   ra   rp   rm   rn   r   r]   r*   r  rq   r&   r-  r.  r/  r(   r'   r  r   rv  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+   rO  r  r   )	r   r  r  r1  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  r5  T)5r   r   r   r  r  rm   rn   r  r  r~   rp   publish_connection_checked_inr]   r^   rq   r&   r-  r.  r/  r(   r'   	CHECKEDINr   r  r  r  r  r_   r   r+   r  r8  rO  r9  r)   r  r|   r   rH  rJ  r  rd   r  r  r  r  r   r  r  r  r  r  r  )r   r\   txncursorro   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)rL  rm   r  r   r+   r  r  rB  rO  r  r|   r   r   )r   r\   rL  s      rQ   r  zPool._perisheda  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: )rm   rn   r`   ra   rp   r   r]   r*   TIMEOUTrq   r&   r-  r.  r/  r(   r'   r  r   r   r  r  r   r  r  r  r    r^  r  )r   r  ro   r1  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   )TN)r]   rG   r  r/   r  r  r  r  re  rm  )TNF)
r<  r  r  r  r   r  r  r  rc  rd  )rd   zOptional[bool]rc  rd  )NF)r   r  r  r  rc  rd  r  )r  r   rc  rd  r   )r  "Optional[_MongoClientErrorHandler]rc  rW   )r  r  rc  z%AsyncGenerator[AsyncConnection, None])r  rn  r  r  rc  rd  )r  rn  r  r  rc  rW   )r\   rW   rc  rd  )r\   rW   rc  r  )r  rn  rc  r	   )rp  rq  rr  r   r}   propertyr_   r  rJ  r  r  r<  r  r  r  
contextlibasynccontextmanagerr  r  r  r   r  r	  r  rU   rS   rQ   ra  ra    s^   
 (,TT T 	T
 &Tl" . . )-&+ODOD OD '	OD
  $OD 
ODb= TY
,
LP
	
4&/=,~Qf ##<@L%9L%	.L% $L%\6 [_%*5W	BI$V"H%
N&rS   ra  )rO   r   rc  rd  )w
__future__r   rz  r  r.  r  r  r`   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.lockr#   r$   r%   pymongo.loggerr&   r'   r(   r)   pymongo.monitoringr*   r+   pymongo.network_layerr,   r-   r.   pymongo.pool_optionsr/   pymongo.pool_sharedr0   r1   r2   r3   r4   pymongo.read_preferencesr5   pymongo.server_apir6   pymongo.server_typer7   pymongo.socket_checkerr8   pymongo.ssl_supportr9   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   rv  rx  r  ra  rU   rS   rQ   <module>r<     s5   #    	 
  
 
 
 ' ) O 7 0 
 
 
 - 
  a ` ,  4 . + 0 (!&6F\ 
 10462E99/ V
 V
r| + +> n& n&c  EE	Es   .E4 4	F ?F 