o
    sD»i[ð  ã                   @  s²  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r1d 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"ZlG d#d$„ d$ƒZmG d%d&„ d&e-ƒZnG d'd(„ d(ƒZoG d)d*„ d*ƒZpG d+d,„ d,ƒZqdS )-é    )ÚannotationsN)	ÚTYPE_CHECKINGÚAnyÚAsyncGeneratorÚMappingÚMutableMappingÚNoReturnÚOptionalÚSequenceÚUnion)ÚDEFAULT_CODEC_OPTIONS)Ú_csotÚhelpers_shared)Ú_validate_session_write_concern)Ú_handle_reauth)Úcommand)ÚMAX_BSON_SIZEÚMAX_MESSAGE_SIZEÚMAX_WIRE_VERSIONÚMAX_WRITE_BATCH_SIZEÚORDERED_TYPES)	ÚAutoReconnectÚConfigurationErrorÚDocumentTooLargeÚExecutionTimeoutÚInvalidOperationÚNotPrimaryErrorÚOperationFailureÚPyMongoErrorÚWaitQueueTimeoutError)ÚHelloÚHelloCompat)Ú_get_timeout_detailsÚformat_timeout_details)Ú_async_cond_waitÚ_async_create_conditionÚ_async_create_lock)Ú_CONNECTION_LOGGERÚ_ConnectionStatusMessageÚ
_debug_logÚ _verbose_connection_error_reason)ÚConnectionCheckOutFailedReasonÚConnectionClosedReason)ÚAsyncNetworkingInterfaceÚasync_receive_messageÚasync_sendall)ÚPoolOptions)Ú	SSLErrorsÚ_CancellationContextÚ_configured_protocol_interfaceÚ_raise_connection_failure)ÚReadPreference)Ú_add_to_command)ÚSERVER_TYPE)ÚSocketChecker)ÚCodecOptions)ÚObjectId)Ú_AuthContext)ÚAsyncClientSession)ÚAsyncMongoClientÚ_MongoClientErrorHandler)ÚSnappyContextÚZlibContextÚZstdContext)Ú_OpMsgÚ_OpReply)ÚReadConcern)Ú_ServerMode)Ú_AddressÚ_CollationIn)ÚWriteConcernFc                   @  sl  e Zd ZdZd‡dd„Zdˆdd„Zd‰dd„ZdŠdd„ZdŠdd„ZdŠdd„Z	d‹d!d"„Z
dŒd$d%„Zdd*d+„Zd‹d,d-„Zeejed.d/d/d/d0d/d/d/d0d.d/d0fdŽdKdL„ƒZddPdQ„ZddTdU„Zd‘dWdX„Zd’dZd[„Zd“d\d]„Zd”d•d_d`„Zd–dadb„Zd—dedf„ZdŠdgdh„Zd˜didj„Zd™dldm„Zdšdndo„ZdŠdpdq„Zd›dsdt„Z dœdvdw„Z!dd{d|„Z"dždd€„Z#dždd‚„Z$dŸdƒd„„Z%d d…d†„Z&d/S )¡Ú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
    Úconnr-   ÚpoolÚPoolÚaddressútuple[str, int]ÚidÚintÚis_sdamÚboolc                 C  s.  t  |¡| _|| _|| _|| _|| _d| _t 	¡ | _
d| _d| _t| _t| _t| _t| _d| _d| _d| _d| _|jj| _|j| _|j| _|jj| _d | _ t!ƒ | _"d | _#d | _$d | _%|j&| _'| j' (¡ | _)d| _*t+ƒ | _,|j| _d| _-d | _.d | _/d| _0d| _1d| _2| jj3| _4d| _5|j6| _6t 	¡ | _7d | _8d S )NFg        )9ÚweakrefÚrefÚpool_refrJ   rM   rO   rQ   Ú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Úreadyr2   Ú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)ÚselfrJ   rK   rM   rO   rQ   © rƒ   úW/home/alumno/antzosa8961/venv/lib/python3.10/site-packages/pymongo/asynchronous/pool.pyÚ__init__y   sT   





zAsyncConnection.__init__ÚtimeoutúOptional[float]ÚreturnÚNonec                 C  s&   || j krdS || _ | jj |¡ dS )z?Cache last timeout to avoid duplicate calls to conn.settimeout.N)r}   rJ   Úget_connÚ
settimeout)r‚   r†   rƒ   rƒ   r„   Úset_conn_timeout´   s   
z AsyncConnection.set_conn_timeoutÚclientúAsyncMongoClient[Any]Úcmdú"Optional[MutableMapping[str, Any]]c           	      C  s¸   t  ¡ }|d u r| js|  | jj¡ d S t  ¡ }|d u r| j}|| }|dk rIt| jƒ}t	|ƒ}d|d›d|d›d|› }t
|dd|ddœ| jƒ‚|d urUt|d ƒ|d	< |  |¡ |S )
Nr   z5operation would exceed time limit, remaining timeout:z.5fz <= network round trip time:ú é2   ©ÚokÚerrmsgÚcodeéè  Ú	maxTimeMS)r   Ú	remainingrv   rŒ   rd   r|   Úget_rttr~   r"   r#   r   r\   rP   )	r‚   r   r   r†   ÚrttÚmax_time_msÚtimeout_detailsÚ	formattedr•   rƒ   rƒ   r„   Úapply_timeout»   s.   

ü
zAsyncConnection.apply_timeoutc                 C  ó   d| _ | jrJ ‚d S ©NT)ry   rz   ©r‚   rƒ   rƒ   r„   Úpin_txnÚ   ó   zAsyncConnection.pin_txnc                 C  r    r¡   )rz   ry   r¢   rƒ   rƒ   r„   Ú
pin_cursorÞ   r¤   zAsyncConnection.pin_cursorc                 Ã  s8   |   ¡ }|r| | ¡I d H  d S |  tj¡I d H  d S ©N)rU   ÚcheckinÚ
close_connr,   ÚSTALE)r‚   rK   rƒ   rƒ   r„   Úunpinâ   s
   €zAsyncConnection.unpinúdict[str, Any]c                 C  s4   | j js| js| j jrd| _tjdiS tjdddiS )NTé   ÚhelloOk)rd   Ú
server_apira   Úload_balancedrc   r!   ÚCMDÚ
LEGACY_CMDr¢   rƒ   rƒ   r„   Ú	hello_cmdé   s   
zAsyncConnection.hello_cmdúHello[dict[str, Any]]c                 Ã  s   |   d d ¡I d H S r¦   )Ú_hellor¢   rƒ   rƒ   r„   Úhelloò   s   €zAsyncConnection.helloÚtopology_versionúOptional[Any]Úheartbeat_frequencyúOptional[int]c                 Ã  s`  |   ¡ }| j }d}|r(d| _| jj|d< | jr| jj|d< | jjr'd|d< n%|d urM||d< |d us6J ‚t|d ƒ|d< d}| jjrM|  	| jj| ¡ | jj
}|r‚|jd	kre|jre|jd
 |j |d< ddlm} |j || j¡}|r| ¡ }	|	d ur|	|d< nd }|rŠt ¡ }
| jd|d|dI d H }|rŸt ¡ |
 | _t||d}|j| _|j| _|j| _|j| _|j| _|jd uoÀ|j| _ |j| _|j!| _!|j"t#j$t#j%t#j&t#j't#j(fv | _)|j"t#j*k| _+|j"t#j,k| _-|r÷| jr÷| j .|j¡}|| _/d| _0|j1| _2|r|j3| _4|r| 5|¡ | 6¡ r|| _7| jjr.|j8s"t9dƒ‚|j8| _8| j: ;| j8¡| _<|S )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²   rZ   rd   Úmetadatarj   Úcompressorsr¯   rP   Úconnect_timeoutrŒ   Ú_credentialsÚ	mechanismÚusernameÚsourceÚpymongo.asynchronousrÂ   r;   Úfrom_credentialsrM   Úspeculate_commandrW   rX   r   r~   r    r[   r\   r]   r^   r_   Úlogical_session_timeout_minutesÚis_readabler`   ra   Úserver_typer7   Ú	RSPrimaryÚRSSecondaryÚ	RSArbiterÚRSOtherÚRSGhostÚis_replÚ
StandaloneÚis_standaloneÚMongosrb   Úget_compression_contextrk   rc   Úconnection_idrx   Úsasl_supported_mechsrn   Úparse_responseÚspeculate_succeededro   rw   r   rq   Úgetrs   )r‚   r¶   r¸   r   Úperforming_handshakerÇ   ÚcredsrÂ   ro   Úspeculative_authenticateÚstartÚdocrµ   Úctxrƒ   rƒ   r„   r´   õ   s”   €€€ÿû



ÿzAsyncConnection._helloc                 Ã  s<   |   d ¡I d H }|j| _| ¡ }|d }t || j¡ |S ©Nr   )Úreceive_messagerv   Úunpack_responser   Ú_check_command_responser\   )r‚   ÚreplyÚunpacked_docsÚresponse_docrƒ   rƒ   r„   Ú_next_replyJ  s   €zAsyncConnection._next_replyTNFÚdbnameÚstrÚspecúMutableMapping[str, Any]Úread_preferencerE   Úcodec_optionsúCodecOptions[Mapping[str, Any]]ÚcheckÚallowable_errorsú#Optional[Sequence[Union[str, int]]]Úread_concernúOptional[ReadConcern]Úwrite_concernúOptional[WriteConcern]Úparse_write_concern_errorÚ	collationúOptional[_CollationIn]ÚsessionúOptional[AsyncClientSession]úOptional[AsyncMongoClient[Any]]Úretryable_writerÅ   Úuser_fieldsúOptional[Mapping[str, Any]]rÆ   c                 Ã  s2  |   ||¡ t||ƒ}t|tƒst|ƒ}|du s$|js$|
du s$tdƒ‚|  |¡ |r3| |||| ¡ |  	|||¡ |r?| j
nd}t|oG|j ƒ}| jrQ|  |¡ z#t| ||| j||||||| j|| j||	|
| j| j||||dI dH W S  ttfy~   ‚  ty˜ } z|  |¡I dH  W Y d}~dS d}~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.)r   r  Úcompression_ctxÚ
use_op_msgÚunacknowledgedr  rÆ   rþ   )Úvalidate_sessionr   Ú
isinstancer   ÚdictÚacknowledgedr   Úadd_server_apiÚ	_apply_toÚsend_cluster_timerf   rR   rc   Ú_raise_if_not_writabler   rb   rM   r]   rk   r   r   ÚBaseExceptionr4   )r‚   rò   rô   rö   r÷   rù   rú   rü   rþ   r   r  r  r   r  rÅ   r  rÆ   rf   r  Úerrorrƒ   rƒ   r„   r   R  s\   €)



ê€ÿzAsyncConnection.commandÚmessageÚbytesÚmax_doc_sizec              
   Ã  sz   | j dur|| j krtd|| j f ƒ‚zt| jj|ƒI dH  W dS  ty< } z|  |¡I dH  W Y d}~dS d}~ww )z}Send a raw BSON message or raise ConnectionFailure.

        If a network exception is raised, the socket is closed.
        NzfBSON document too large (%d bytes) - the connected server supports BSON document sizes up to %d bytes.)r]   r   r/   rJ   rŠ   r  r4   )r‚   r  r  r  rƒ   rƒ   r„   Úsend_message¬  s   €ÿÿ€ÿzAsyncConnection.send_messageÚ
request_idúUnion[_OpReply, _OpMsg]c              
   Ã  sP   zt | || jƒI dH W S  ty' } z|  |¡I dH  W Y d}~dS d}~ww )zzReceive a raw BSON message or raise ConnectionFailure.

        If any exception is raised, the socket is closed.
        N)r.   r^   r  r4   )r‚   r  r  rƒ   rƒ   r„   rë   ½  s   €€ÿzAsyncConnection.receive_messager  c                 C  s$   |r| j stdddddœƒ‚dS dS )z^Raise NotPrimaryError on unacknowledged write if this socket is not
        writable.
        znot primaryr   i{'  r“   N)r[   r   )r‚   r  rƒ   rƒ   r„   r  È  s   
þz&AsyncConnection._raise_if_not_writableÚmsgc                 Ã  s"   |   d¡ |  ||¡I dH  dS )zÐSend 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‚   r  r  rƒ   rƒ   r„   Úunack_writeÐ  s   €
zAsyncConnection.unack_writec                 Ã  s@   |   |d¡I dH  |  |¡I dH }| |¡}t || j¡ |S )zÐSend "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í   r\   )r‚   r  r  r÷   rî   Úresultrƒ   rƒ   r„   Úwrite_commandÛ  s   €

zAsyncConnection.write_commandÚreauthenticatec              	   Ã  sÒ   |r| j r	d| _d| _| jsc| jj}|r&ddlm} |j|| |dI dH  d| _t 	¡ | j
 }| jrD| jdus:J ‚| j | j| j|¡ | jret tj¡rgtttj| j| jd | jd | j|d dS dS dS dS )	zhAuthenticate to the server if needed.

        Can raise ConnectionFailure or OperationFailure.
        NFr   rÁ   )r!  Tr¬   ©r  ÚclientIdÚ
serverHostÚ
serverPortÚdriverConnectionIdÚ
durationMS)rZ   ro   rt   rd   rË   rÏ   rÂ   ÚauthenticaterW   rX   r€   rg   rf   Úpublish_connection_readyrM   rO   rh   r'   ÚisEnabledForÚloggingÚDEBUGr)   r(   Ú
CONN_READYr   )r‚   r!  rå   rÂ   Údurationrƒ   rƒ   r„   r(  í  s6   €
ùôzAsyncConnection.authenticatec                 C  s   |r|j |urtdƒ‚dS dS )zƒValidate 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  rƒ   rƒ   r„   r    s   
ÿþz AsyncConnection.validate_sessionÚreasonúOptional[str]c              
   Ã  s–   | j rdS |  ¡ I dH  |rE| jr#| jdusJ ‚| j | j| j|¡ | jrGt 	t
j¡rItttj| j| jd | jd | jt|ƒ|d dS dS dS dS )z$Close this connection with a reason.Nr   r¬   ©r  r#  r$  r%  r&  r0  r  )rV   Ú_close_connrg   rf   Úpublish_connection_closedrM   rO   rh   r'   r*  r+  r,  r)   r(   ÚCONN_CLOSEDr   r*   )r‚   r0  rƒ   rƒ   r„   r¨     s*   €
øûzAsyncConnection.close_connc                 Ã  sH   | j rdS d| _ | j ¡  z| j ¡ I dH  W dS  ty#   Y dS w )zClose this connection.NT)rV   ru   ÚcancelrJ   ÚcloseÚ	Exceptionr¢   rƒ   rƒ   r„   r3  1  s   €
ÿzAsyncConnection._close_connc                 C  s   t r
| j | jj¡S | j ¡ S )z?Return True if we know socket has been closed, False otherwise.)Ú_IS_SYNCrl   Úsocket_closedrJ   rŠ   Ú
is_closingr¢   rƒ   rƒ   r„   Úconn_closed>  s   
zAsyncConnection.conn_closedr   c                 C  s   |r
|  ||¡ dS dS )zAdd $clusterTime.N)Ú_send_cluster_time)r‚   r   r  r   rƒ   rƒ   r„   r  E  s   ÿz!AsyncConnection.send_cluster_timec                 C  s   | j jrt|| j jƒ dS dS )zAdd server_api parameters.N)rd   r®   r6   )r‚   r   rƒ   rƒ   r„   r  O  s   ÿzAsyncConnection.add_server_apic                 C  s   t  ¡ | _d S r¦   ©rW   rX   rY   r¢   rƒ   rƒ   r„   Úupdate_last_checkin_timeT  ó   z(AsyncConnection.update_last_checkin_timer[   c                 C  s
   || _ d S r¦   )r[   )r‚   r[   rƒ   rƒ   r„   Úupdate_is_writableW  ó   
z"AsyncConnection.update_is_writableÚfloatc                 C  s   t  ¡ | j S )z9Seconds since this socket was last checked into its pool.r>  r¢   rƒ   rƒ   r„   Úidle_time_secondsZ  ó   z!AsyncConnection.idle_time_secondsr  r  r   c                 Ã  sX   | j rd }ntj}|  |¡I d H  t|ttgt¢R ƒr+t| j	ƒ}t
| j||d d S ‚ )N©r   )rt   r,   ÚERRORr¨   r  ÚIOErrorÚOSErrorr1   r"   rd   r4   rM   )r‚   r  r0  Údetailsrƒ   rƒ   r„   r4   ^  s   €
z)AsyncConnection._raise_connection_failureÚotherr   c                 C  s   | j |j kS r¦   )rJ   ©r‚   rK  rƒ   rƒ   r„   Ú__eq__z  s   zAsyncConnection.__eq__c                 C  s
   | |k S r¦   rƒ   rL  rƒ   rƒ   r„   Ú__ne__}  rB  zAsyncConnection.__ne__c                 C  s
   t | jƒS r¦   )ÚhashrJ   r¢   rƒ   rƒ   r„   Ú__hash__€  rB  zAsyncConnection.__hash__c                 C  s"   d  t| jƒ| jrdpdt| ƒ¡S )NzAsyncConnection({}){} at {}z CLOSEDÚ )ÚformatÚreprrJ   rV   rO   r¢   rƒ   rƒ   r„   Ú__repr__ƒ  s
   ýzAsyncConnection.__repr__)
rJ   r-   rK   rL   rM   rN   rO   rP   rQ   rR   )r†   r‡   rˆ   r‰   )r   rŽ   r   r   rˆ   r‡   ©rˆ   r‰   )rˆ   r«   )rˆ   r³   )r¶   r·   r¸   r¹   rˆ   r³   )"rò   ró   rô   rõ   rö   rE   r÷   rø   rù   rR   rú   rû   rü   rý   rþ   rÿ   r   rR   r  r  r  r  r   r  r  rR   rÅ   rR   r  r  rÆ   rR   rˆ   r«   )r  r  r  rP   rˆ   r‰   )r  r¹   rˆ   r  )r  rR   rˆ   r‰   )r  r  r  rP   rˆ   r‰   )r  rP   r  r  r÷   rø   rˆ   r«   )F)r!  rR   rˆ   r‰   )r   r  r  r  rˆ   r‰   )r0  r1  rˆ   r‰   ©rˆ   rR   )r   rõ   r  r  r   r  rˆ   r‰   )r   rõ   rˆ   r‰   )r[   rR   rˆ   r‰   )rˆ   rC  )r  r  rˆ   r   )rK  r   rˆ   rR   ©rˆ   rP   )rˆ   ró   )'Ú__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¨   r3  r<  r  r  r?  rA  rD  r4   rM  rN  rP  rT  rƒ   rƒ   rƒ   r„   rI   o   s`    
	
;





	

Uï
Y




"












rI   c                   @  s   e Zd ZdZdS )Ú_PoolClosedErrorzZInternal error raised when a thread tries to get a connection from a
    closed pool.
    N)rX  rY  rZ  r[  rƒ   rƒ   rƒ   r„   r]  ‹  s    r]  c                   @  s>   e Zd Zddd„Zddd	„Zdd
d„Zddd„Zddd„ZdS )Ú_PoolGenerationrˆ   r‰   c                 C  s   t  t¡| _d| _d S rê   )ÚcollectionsÚdefaultdictrP   Ú_generationsÚ_generationr¢   rƒ   rƒ   r„   r…   ’  s   
z_PoolGeneration.__init__rw   úOptional[ObjectId]rP   c                 C  s   |du r| j S | j| S )z,Get the generation for the given service_id.N©rb  ra  ©r‚   rw   rƒ   rƒ   r„   rã   ˜  s   
z_PoolGeneration.getc                 C  s   | j S )z"Get the Pool's overall generation.)rb  r¢   rƒ   rƒ   r„   rr   ž  s   z_PoolGeneration.get_overallc                 C  sN   |  j d7  _ |du r| jD ]}| j|  d7  < qdS | j|  d7  < dS )z2Increment the generation for the given service_id.r¬   Nrd  re  rƒ   rƒ   r„   Úinc¢  s   
ÿz_PoolGeneration.incrp   rR   c                 C  s   ||   |¡kS )z?Return if the given generation for a given service_id is stale.)rã   ©r‚   rp   rw   rƒ   rƒ   r„   Ústale«  rE  z_PoolGeneration.staleNrU  )rw   rc  rˆ   rP   rW  )rw   rc  rˆ   r‰   ©rp   rP   rw   rc  rˆ   rR   )rX  rY  rZ  r…   rã   rr   rf  rh  rƒ   rƒ   rƒ   r„   r^  ‘  s    



	r^  c                   @  s   e Zd ZdZdZdZdS )Ú	PoolStater¬   é   é   N)rX  rY  rZ  ÚPAUSEDÚREADYÚCLOSEDrƒ   rƒ   rƒ   r„   rj  °  s    rj  c                   @  sæ   e Zd Z		dDdEdd„ZdFdd„ZedGdd„ƒZ			dHdIdd„ZdJdd„Z	dKdLdd„Z	dFd d!„Z
dFd"d#„ZdMd&d'„ZdNd)d*„ZdOdPd.d/„Zej	dOdQd1d2„ƒZdRd6d7„Z	dOdSd8d9„ZdTd;d<„ZdUd=d>„ZdVd@dA„ZdFdBdC„ZdS )WrL   FNrM   rF   Úoptionsr0   rQ   rR   Ú	client_idrc  c                 C  s|  |j rtj| _ntj| _d| _t ¡ | _t	ƒ | _
tƒ | _t| jƒ| _d| _d| _d| _tƒ | _t ¡ | _|| _|| _|| _| j oK| jjduoK| jjj| _| j | _t| jƒ| _d| _| jj| _| jsht dƒ| _t| jƒ| _| jj!| _"d| _#|| _$| jr| jjdus„J ‚| jj %| j| jj&¡ | jr¯t' (t)j*¡r¯t+t'ft,j-| j$| jd | jd dœ| jj&¤Ž d| _.t	ƒ | _/d| _0d| _1dS )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_enabledrj  rm  Ústatern  Ú_check_interval_secondsr_  ÚdequeÚconnsÚsetÚactive_contextsr&   Úlockr%   Ú_max_connecting_condÚactive_socketsÚnext_connection_idr[   r^  rp   ÚosÚgetpidÚpidrM   rd   rQ   re   rg   rh   Ú	size_condÚrequestsÚmax_pool_sizerC  Ú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‚   rM   rp  rQ   rq  rƒ   rƒ   r„   r…   ·  sf   



ÿý




ÿÿûú	
zPool.__init__rˆ   r‰   c              	   Ã  sò   | j 4 I d H šd | jtjkrKtj| _| jr&| jjd usJ ‚| jj | j¡ | j	rVt
 tj¡ratt
tj| j| jd | jd d W d   ƒI d H  d S W d   ƒI d H  d S W d   ƒI d H  d S W d   ƒI d H  d S 1 I d H srw   Y  d S )Nr   r¬   rs  )r{  ru  rj  rn  rg   rd   re   Úpublish_pool_readyrM   rh   r'   r*  r+  r,  r)   r(   Ú
POOL_READYr   r¢   rƒ   rƒ   r„   rt     s,   €ûùÿú.úz
Pool.readyc                 C  s   | j tjkS r¦   )ru  rj  ro  r¢   rƒ   rƒ   r„   rV     s   zPool.closedTr7  Úpauserw   Úinterrupt_connectionsc              	   Ã  s´  | j }| j4 I d H š‘ | jr	 W d   ƒI d H  d S | jjr-|r-| jjs-| j tj}| _ | j 	|¡ t
 ¡ }| j|krE|| _d| _d| _|d u rS| jt ¡ }| _n#t ¡ }t ¡ }	| jD ]}
|
j|krk| |
¡ q^|	 |
¡ q^|}|	| _|r|tj| _ | j ¡  | j ¡  |r’| jD ]}| ¡  q‹W d   ƒI d H  n1 I d H s¢w   Y  | jj}|rýtsÀtjdd„ |D ƒddiŽI d H  n|D ]}
|
 tj¡I d H  qÂ| j rÝ|d us×J ‚| !| j"¡ | j#rùt$ %t&j'¡rût(t$t)j| j*| j"d | j"d d d S d S d S |tjkr4| j r|d usJ ‚|j+| j"||d | j#r4t$ %t&j'¡r4t(t$t)j,| j*| j"d | j"d |d	 tsItjd
d„ |D ƒddiŽI d H  d S |D ]}
|
 tj-¡I d H  qKd S )Nr   c                 S  ó   g | ]}|  tj¡‘qS rƒ   )r¨   r,   ÚPOOL_CLOSED©Ú.0rJ   rƒ   rƒ   r„   Ú
<listcomp>S  ó    zPool._reset.<locals>.<listcomp>Úreturn_exceptionsTr¬   rs  )rw   r’  )r  r#  r$  r%  Ú	serviceIdc                 S  r“  rƒ   )r¨   r,   r©   r•  rƒ   rƒ   r„   r—  x  r˜  ).ru  r‚  rV   rd   rt  r¯   rj  rm  rp   rf  r  r€  r  r}  r‹  rx  r_  rw  rw   Úappendro  r|  Ú
notify_allrz  r6  re   r9  ÚasyncioÚgatherr¨   r,   r”  rg   Úpublish_pool_closedrM   rh   r'   r*  r+  r,  r)   r(   r   Úpublish_pool_clearedÚPOOL_CLEAREDr©   )r‚   r7  r‘  rw   r’  Ú	old_stateÚnewpidÚsocketsÚdiscardÚkeeprJ   Úcontextrf   rƒ   rƒ   r„   Ú_reset"  s¢   €þ






€(à"ÿþ
ûÿ	ýúÿþÿzPool._resetr[   úOptional[bool]c              	   Ã  s`   || _ | j4 I dH š | jD ]}| | j ¡ qW d  ƒI dH  dS 1 I dH s)w   Y  dS )zXUpdates the is_writable attribute on all sockets currently in the
        Pool.
        N)r[   r{  rx  rA  )r‚   r[   Ú_socketrƒ   rƒ   r„   rA    s   €
ÿ.ÿzPool.update_is_writablec                 Ã  s   | j d||dI d H  d S )NF)r7  rw   r’  ©r¨  )r‚   rw   r’  rƒ   rƒ   r„   Úresetˆ  s   €ÿz
Pool.resetc                 Ã  s   | j dddI d H  d S )NF)r7  r‘  r«  r¢   rƒ   rƒ   r„   Úreset_without_pause  s   €zPool.reset_without_pausec                 Ã  s   | j ddI d H  d S )NT)r7  r«  r¢   rƒ   rƒ   r„   r7  ’  s   €z
Pool.closerp   rP   c                 C  s   | j  ||¡S r¦   )rp   rh  rg  rƒ   rƒ   r„   Ústale_generation•  r@  zPool.stale_generationÚreference_generationc                 Ã  s¶  | j 4 I dH š | jtjkr	 W d  ƒI dH  dS W d  ƒI dH  n1 I dH s+w   Y  | jjduršg }| j 4 I dH š/ | jrd| jd  ¡ | jjkrd| | j 	¡ ¡ | jrd| jd  ¡ | jjksNW d  ƒI dH  n1 I dH stw   Y  t
sŒtjdd„ |D ƒddiŽI dH  n|D ]}| tj¡I dH  qŽ	 | j4 I dH š= t| jƒ| j | jjkr»	 W d  ƒI dH  dS | j| jjkrÎ	 W d  ƒI dH  dS |  jd7  _W d  ƒI dH  n1 I dH såw   Y  d}z”| j4 I dH š€ | j| jkrb	 W d  ƒI dH  W |r5| j4 I dH š |  jd8  _| j ¡  W d  ƒI dH  n1 I dH s0w   Y  | j4 I dH š |  jd8  _| j ¡  W d  ƒI dH  dS 1 I dH s[w   Y  dS |  jd7  _d}W d  ƒI dH  n1 I dH s|w   Y  |  ¡ I dH }d}| j 4 I dH š% | j ¡ |krœd}|s¬| j |¡ | j |j¡ W d  ƒI dH  n1 I dH s½w   Y  |r)| tj ¡I dH  W |rü| j4 I dH š |  jd8  _| j ¡  W d  ƒI dH  n1 I dH s÷w   Y  | j4 I dH š |  jd8  _| j ¡  W d  ƒI dH  dS 1 I dH s"w   Y  dS W |rW| j4 I dH š |  jd8  _| j ¡  W d  ƒI dH  n1 I dH sRw   Y  | j4 I dH š |  jd8  _| j ¡  W d  ƒI dH  n1 I dH s|w   Y  nX|r¯| j4 I dH š |  jd8  _| j ¡  W d  ƒI dH  n1 I dH sªw   Y  | j4 I dH š |  jd8  _| j ¡  W d  ƒI dH  w 1 I dH sÔw   Y  w q›)	zôRemoves 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.
        Néÿÿÿÿc                 S  r“  rƒ   )r¨   r,   ÚIDLEr•  rƒ   rƒ   r„   r—  ­  r˜  z-Pool.remove_stale_sockets.<locals>.<listcomp>r™  Tr¬   F)!r{  ru  rj  rn  rd   Úmax_idle_time_secondsrx  rD  r›  Úpopr9  r  rž  r¨   r,   r±  r‚  Úlenr}  Úmin_pool_sizerƒ  r|  r‡  r†  ÚnotifyÚconnectrp   rr   Ú
appendleftrz  r¥  ru   r©   )r‚   r¯  Úclose_connsrJ   Úincrementedr¨   rƒ   rƒ   r„   Úremove_stale_sockets˜  sÂ   €þ(ÿÿýÿ(ýÿþýû(úü*þ0þê*ú€*ù*þ0þö*þ*þ€ú*þ,þÛzPool.remove_stale_socketsÚhandlerú"Optional[_MongoClientErrorHandler]rI   c           	      Ã  s  | j 4 I dH š | j}|  jd7  _tƒ }| j |¡ W d  ƒI dH  n1 I dH s,w   Y  | jj}| jrE|dus>J ‚| | j	|¡ | j
r`t tj¡r`tttj| j| j	d | j	d |d zt| j	| jƒI dH }W nz tyæ } zn| j 4 I dH š | j |¡ W d  ƒI dH  n1 I dH s’w   Y  | jr©|dus J ‚| | j	|tj¡ | j
rÊt tj¡rÊtttj| j| j	d | j	d |ttjƒtjd t|ttgt¢R ƒrát| jƒ}t | j	||d ‚ d}~ww t!|| | j	|| j"ƒ}| j 4 I dH š | j |j#¡ | j |¡ W d  ƒI dH  n1 I dH sw   Y  |j$r%|j# %¡  z"| j"s5| &¡ I dH  |j'| _'|r?|j(|dd | )¡ I dH  W n7 ty~   | j 4 I dH š | j |j#¡ W d  ƒI dH  n1 I dH sow   Y  | *tj¡I dH  ‚ w |r|j+j, -|j.¡I dH  |S )	zâConnect 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&  r2  rF  F)Úcompleted_handshake)/r{  r~  r2   rz  Úaddrd   re   rg   Úpublish_connection_createdrM   rh   r'   r*  r+  r,  r)   r(   ÚCONN_CREATEDr   r3   r  r¥  r4  r,   rG  r5  r*   r  rH  rI  r1   r"   r4   rI   rQ   ru   Ú	cancelledr6  rµ   r[   Úcontribute_socketr(  r¨   r   Ú	_topologyÚreceive_cluster_timer   )	r‚   r¼  Úconn_idÚtmp_contextrf   Únetworking_interfacer  rJ  rJ   rƒ   rƒ   r„   r·  Ý  s   €(ûú	(ÿ
ÿø

€é*þ
*ÿüzPool.connectú%AsyncGenerator[AsyncConnection, None]c           
   	   C st  | j j}t ¡ }| jr|dusJ ‚| | j¡ | jr2t 	t
j¡r2tttj| j| jd | jd d | j||dI dH }t ¡ | }| jrT|dusKJ ‚| | j|j|¡ | jrqt 	t
j¡rqtttj| j| jd | jd |j|d z)| j4 I dH š | j |j¡ W d  ƒI dH  n1 I dH s‘w   Y  |V  W n- tyÇ   |jp¦|j}|r¹t ¡ \}}}	| ||¡I dH  |sÆ|jrÆ|  |¡I dH  ‚ w |jrø| j4 I dH š | j  |¡ |  j!d7  _!W d  ƒI dH  dS 1 I dH sñw   Y  dS |jr*| j4 I dH š | j  |¡ |  j"d7  _"W d  ƒI dH  dS 1 I dH s#w   Y  dS |jr8|  |¡I dH  dS dS )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¬   rs  ©r¼  r"  )#rd   re   rW   rX   rg   Ú$publish_connection_check_out_startedrM   rh   r'   r*  r+  r,  r)   r(   ÚCHECKOUT_STARTEDr   Ú	_get_connÚpublish_connection_checked_outrO   ÚCHECKOUT_SUCCEEDEDr{  rz  rÀ  ru   r  ry   rz   ÚsysÚexc_infoÚhandler{   r§   rŒ  rŽ  r  )
r‚   r¼  rf   Úcheckout_started_timerJ   r.  ÚpinnedÚexc_typeÚexc_valÚ_rƒ   rƒ   r„   Úcheckout0  sp   €ûù	(ÿ

ó.þ0þÿzPool.checkoutrÔ  rC  Ú
emit_eventc              
   C  sª   | j tjkrS|rBt ¡ | }| jr$| jjd usJ ‚| jj | j	t
j|¡ | jrBt tj¡rBtttj| j| j	d | j	d dt
j|d t| jƒ}t| j	tdƒ|d d S d S )Nr   r¬   ú<An error occurred while trying to establish a new connection©r  r#  r$  r%  r0  r  r'  zconnection pool pausedrF  )ru  rj  rn  rW   rX   rg   rd   re   Ú#publish_connection_check_out_failedrM   r+   Ú
CONN_ERRORrh   r'   r*  r+  r,  r)   r(   ÚCHECKOUT_FAILEDr   r"   r4   r   )r‚   rÔ  rÚ  r.  rJ  rƒ   rƒ   r„   Ú_raise_if_not_ready  s0   
ÿø

ÿëzPool._raise_if_not_readyc           	      Ã  s`  | j t ¡ kr|  ¡ I dH  | jrPt ¡ | }| jr.| jj	dus#J ‚| jj	 
| jtj|¡ | jrLt tj¡rLtttj| j| jd | jd dtj|d tdƒ‚| j4 I dH š |  jd7  _W d  ƒI dH  n1 I dH sow   Y  t ¡ r}t ¡ }n| jjrŠt ¡ | jj }nd}| j4 I dH šO | j|dd | j | j!k sÑ|r©|t ¡  nd}t"| j|ƒI dH sÄ| j | j!k r¿| j #¡  |  $|¡ | j|dd | j | j!k r¡|  j d7  _ W d  ƒI dH  n1 I dH sèw   Y  d}d	}d	}z,| j4 I dH š |  j%d7  _%d}W d  ƒI dH  n1 I dH sw   Y  |du r| j&4 I dH št | j|d	d | j'sy| j(| j)k sy|rD|t ¡  nd}t"| j&|ƒI dH sg| j's[| j(| j)k r`| j& #¡  d}|  $|¡ | j|d	d | j'sy| j(| j)k r;z| j' *¡ }W n t+y‘   |  j(d7  _(Y nw W d  ƒI dH  n1 I dH s£w   Y  |r¹|  ,|¡I dH r¸d}qnaz5| j-|d
I dH }W | j&4 I dH š |  j(d8  _(| j& #¡  W d  ƒI dH  n1 I dH séw   Y  n+| j&4 I dH š |  j(d8  _(| j& #¡  W d  ƒI dH  w 1 I dH sw   Y  w |du s!W nŠ t.yª   |r4| /t0j1¡I dH  | j4 I dH š! |  j d8  _ |rM|  j%d8  _%| j #¡  W d  ƒI dH  n1 I dH scw   Y  |s©t ¡ | }| jr‰| jj	dus~J ‚| jj	 
| jtj2|¡ | jr©t tj¡r©tttj| j| jd | jd dtj2|d ‚ w d|_3|S )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­  rV   rW   rX   rg   rd   re   rÝ  rM   r+   r”  rh   r'   r*  r+  r,  r)   r(   rß  r   r]  r{  r‹  r   Úget_timeoutÚget_deadlineÚwait_queue_timeoutr‚  rà  rƒ  r„  r$   r¶  Ú_raise_wait_queue_timeoutr}  r|  rx  r‡  r†  ÚpopleftÚ
IndexErrorÚ	_perishedr·  r  r¨   r,   rG  rÞ  r{   )	r‚   rÔ  r¼  r.  Údeadliner†   rJ   rº  Úemitted_eventrƒ   rƒ   r„   rÎ  ™  sð   €
ÿø
ÿ(ÿ


ø	(õ*þ


÷ÿ€*ñþ*þ€ ,þ
ä€ *ü
ÿø
äzPool._get_connrJ   c              
   Ã  sº  |j }|j}d|_d|_ d|_| j |¡ | jj}| j4 I dH š | j |j	¡ W d  ƒI dH  n1 I dH s9w   Y  | j
rO|dusGJ ‚| | j|j¡ | jrkt tj¡rktttj| j| jd | jd |jd | jt ¡ krz|  ¡ I dH  n“| jr‡| tj¡I dH  n†|jrÀ| j
r|dus“J ‚| | j|jtj ¡ | jr¿t tj¡r¿tttj!| j| jd | jd |jt"tj ƒtj d nMd}| j4 I dH š- |  #|j$|j%¡rÕd}n| &¡  | 't(| j)ƒ¡ | j* +|¡ | j, -¡  W d  ƒI dH  n1 I dH süw   Y  |r| tj.¡I dH  | j/4 I dH š; |r |  j0d8  _0n
|r*|  j1d8  _1|  j2d8  _2|  j3d8  _3|  j4d8  _4| j/ -¡  W d  ƒI dH  dS 1 I dH sVw   Y  dS )z†Return the connection to the pool, or if it's closed discard it.

        :param conn: The connection to check into the pool.
        FNr   r¬   r¾  r2  T)5ry   rz   r{   rŒ  r¥  rd   re   r{  rz  ru   rg   Úpublish_connection_checked_inrM   rO   rh   r'   r*  r+  r,  r)   r(   Ú	CHECKEDINr   r  r  r€  r­  rV   r¨   r,   r”  r4  rG  r5  r*   r®  rs   rw   r?  rA  rR   r[   rx  r¸  r|  r¶  r©   r‚  rŽ  r  rƒ  r}  r‹  )r‚   rJ   ÚtxnÚcursorrf   r¨   rƒ   rƒ   r„   r§     s†   €(ÿúÿø€
€(ö0øzPool.checkinc                 Ã  sž   |  ¡ }| jjdur|| jjkr| tj¡I dH  dS | jdur:| jdks+|| jkr:| ¡ r:| tj¡I dH  dS |  	|j
|j¡rM| tj¡I dH  dS dS )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)rD  rd   r²  r¨   r,   r±  rv  r<  rG  r®  rs   rw   r©   )r‚   rJ   rD  rƒ   rƒ   r„   rç  e  s   €
zPool._perishedr   c              
   C  sÔ   | j j}t ¡ | }| jr|d usJ ‚| | jtj|¡ | j	r:t
 tj¡r:tt
tj| j| jd | jd dtj|d t ¡ pA| j j}| j jr^| j| j | j }td | j j| j| j||¡ƒ‚td| j j› d|› ƒ‚)Nr   r¬   zBWait queue timeout elapsed without a connection becoming availablerÜ  zÌTimeout 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: )rd   re   rW   rX   rg   rÝ  rM   r+   ÚTIMEOUTrh   r'   r*  r+  r,  r)   r(   rß  r   r   rá  rã  r¯   r}  r  rŽ  r   rR  r„  )r‚   rÔ  rf   r.  r†   Ú	other_opsrƒ   rƒ   r„   rä  ‰  sL   
ÿø
ûüÿÿÿzPool._raise_wait_queue_timeoutc                 C  s"   t r| jD ]	}| d ¡ qd S d S r¦   )r9  rx  r¨   )r‚   rJ   rƒ   rƒ   r„   Ú__del__°  s
   
þzPool.__del__)FN)rM   rF   rp  r0   rQ   rR   rq  rc  rU  rV  )TNF)
r7  rR   r‘  rR   rw   rc  r’  rR   rˆ   r‰   )r[   r©  rˆ   r‰   )NF)rw   rc  r’  rR   rˆ   r‰   ri  )r¯  rP   rˆ   r‰   r¦   )r¼  r½  rˆ   rI   )r¼  r½  rˆ   rÊ  )rÔ  rC  rÚ  rR   rˆ   r‰   )rÔ  rC  r¼  r½  rˆ   rI   )rJ   rI   rˆ   r‰   )rJ   rI   rˆ   rR   )rÔ  rC  rˆ   r   )rX  rY  rZ  r…   rt   ÚpropertyrV   r¨  rA  r¬  r­  r7  r®  r»  r·  Ú
contextlibÚasynccontextmanagerrÙ  rà  rÎ  r§   rç  rä  rð  rƒ   rƒ   rƒ   r„   rL   ¶  s<    û
Vû
]
ÿ



ESÿ
Nÿ 

K
$'rL   )rÚ
__future__r   r  r_  rò  r+  r  rÑ  rW   rS   Ú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.   r/   Úpymongo.pool_optionsr0   Úpymongo.pool_sharedr1   r2   r3   r4   Úpymongo.read_preferencesr5   Úpymongo.server_apir6   Úpymongo.server_typer7   Úpymongo.socket_checkerr8   r9   Úbson.objectidr:   Úpymongo.asynchronous.authr;   r<   Ú!pymongo.asynchronous.mongo_clientr=   r>   Úpymongo.compression_supportr?   r@   rA   Úpymongo.messagerB   rC   Úpymongo.read_concernrD   rE   Úpymongo.typingsrF   rG   Úpymongo.write_concernrH   r9  rI   r]  r^  rj  rL   rƒ   rƒ   rƒ   r„   Ú<module>   sf   ,,     