o
    'h                     @  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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*m+Z+ d d	l,m-Z-m.Z.m/Z/ d d
l0m1Z1m2Z2m3Z3m4Z4 d dl5m6Z6m7Z7 d dl8m9Z9m:Z:m;Z; d dl<m=Z= d dl>m?Z?m@Z@mAZAmBZBmCZCmDZD d dlEmFZF d dlGmHZH d dlImJZJ d dlKmLZL d dlMmNZN d dlOmPZP d dlQmRZR er-d dlmSZS d dlTmUZU d dlVmWZWmXZXmYZY d dlZm[Z[m\Z\ d dl]m^Z^ d dlEm_Z_ d dl`maZa d dlMmbZb d dlcmdZdmeZe d dlfmgZgmhZh d d limjZj zd d!lkmlZlmmZmmnZnmkZk d4d&d'ZoW n epyO   d4d(d'ZoY nw d)ZqG d*d+ d+ZrG d,d- d-e'ZsG d.d/ d/ZtG d0d1 d1ZuG d2d3 d3ZvdS )5    )annotationsN)	TYPE_CHECKINGAny	GeneratorMappingMutableMappingNoReturnOptionalSequenceUnion)DEFAULT_CODEC_OPTIONS)_csothelpers_shared)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)
_cond_wait_create_condition_create_lock)_CONNECTION_LOGGER_ConnectionStatusMessage
_debug_log _verbose_connection_error_reason)ConnectionCheckOutFailedReasonConnectionClosedReason)NetworkingInterfacereceive_messagesendall)PoolOptions)	SSLErrors_CancellationContext_configured_socket_interface_get_timeout_details_raise_connection_failureformat_timeout_details)ReadPreference)_add_to_command)SERVER_TYPE)SocketChecker)_validate_session_write_concern)_handle_reauth)command)CodecOptions)ObjectId)SnappyContextZlibContextZstdContext)_OpMsg_OpReply)ReadConcern)_ServerMode)_AuthContext)ClientSession)MongoClient_MongoClientErrorHandler)_Address_CollationIn)WriteConcern)F_GETFDF_SETFD
FD_CLOEXECfcntlfdintreturnNonec                 C  s   t | t}t | t|tB  dS )z8Set the close-on-exec flag on the given file descriptor.N)rL   rI   rJ   rK   )rM   flags rR   T/var/www/html/olx_land/venv/lib/python3.10/site-packages/pymongo/synchronous/pool.py_set_non_inheritable_non_atomico   s   
rT   c                 C  s   dS )z6Dummy function for platforms that don't provide fcntl.NrR   )rM   rR   rR   rS   rT   x   s    Tc                   @  sl  e Zd ZdZdd
dZdddZdddZdddZdddZdddZ	ddd Z
dd"d#Zdd)d*Zdd+d,Zeejed-d.d.d.d/d.d.d.d/d-d.d/fddKdLZddPdQZddTdUZddWdXZddZd[Zdd\d]Zddd_d`ZddadbZddedfZddgdhZddidjZddldmZddndoZddpdqZddsdtZ ddvdwZ!dd{d|Z"dddZ#dddZ$dddZ%dddZ&d.S )
ConnectionzStore 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
    connr(   poolPooladdresstuple[str, int]idrN   c                 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| _/d| _0d| _1| jj2| _3d| _4|j5| _5t | _6d | _7d S )NFg        )8weakrefrefpool_refrV   rY   r[   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_contextr5   socket_checkeroidc_token_gen_idnegotiated_mechsauth_ctxgenpool_genget_overall
generationreadyr-   cancel_contextmore_to_come
service_idserver_connection_id
pinned_txnpinned_cursoractivesocket_timeoutlast_timeoutconnect_rtt
_client_idcreation_time_cluster_time)selfrV   rW   rY   r[   rR   rR   rS   __init__   sR   





zConnection.__init__timeoutOptional[float]rO   rP   c                 C  s&   || j krdS || _ | jj| dS )z?Cache last timeout to avoid duplicate calls to conn.settimeout.N)r   rV   get_conn
settimeout)r   r   rR   rR   rS   set_conn_timeout   s   
zConnection.set_conn_timeoutclientrD   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   	remainingr   r   rm   r   get_rttr   r/   r1   r   re   rN   )	r   r   r   r   rttmax_time_mstimeout_details	formattedr   rR   rR   rS   apply_timeout   s.   


zConnection.apply_timeoutc                 C     d| _ | jrJ d S NT)r   r   r   rR   rR   rS   pin_txn      zConnection.pin_txnc                 C  r   r   )r   r   r   rR   rR   rS   
pin_cursor   r   zConnection.pin_cursorc                 C  s*   |   }|r||  d S | tj d S N)r^   checkin
close_connr'   STALE)r   rW   rR   rR   rS   unpin   s   zConnection.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)rm   
server_apirj   load_balancedrl   r   CMD
LEGACY_CMDr   rR   rR   rS   	hello_cmd   s   
zConnection.hello_cmdr   c                 C  s   |  d d S r   )_hellor   rR   rR   rS   hello      zConnection.hellotopology_versionOptional[Any]heartbeat_frequencyOptional[int]Hello[dict[str, Any]]c                 C  sX  |   }| j }d}|r'd| _| jj|d< | jr| jj|d< | jjr&d|d< n%|d urL||d< |d us5J t|d |d< d}| jjrL| 	| jj|  | jj
}|r|jd	krd|jrd|jd
 |j |d< ddlm} |j|| j}|r| }	|	d ur|	|d< nd }|rt }
| jd|d|d}|rt |
 | _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   rc   rm   metadatars   compressorsr   rN   connect_timeoutr   _credentials	mechanismusernamesourcepymongo.synchronousr   rB   from_credentialsrY   speculate_commandr`   ra   r8   r   r   rd   re   rf   rg   rh   logical_session_timeout_minutesis_readableri   rj   server_typer4   	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   r   r   r   performing_handshaker   credsr   rx   speculative_authenticatestartdocr   ctxrR   rR   rS   r     s   



zConnection._helloc                 C  s4   |  d }|j| _| }|d }t|| j |S Nr   )r)   r   unpack_responser   _check_command_responsere   )r   replyunpacked_docsresponse_docrR   rR   rS   _next_replyW  s   
zConnection._next_replyTNFdbnamestrspecMutableMapping[str, Any]read_preferencerA   codec_optionsr9   checkboolallowable_errors#Optional[Sequence[Union[str, int]]]read_concernOptional[ReadConcern]write_concernOptional[WriteConcern]parse_write_concern_error	collationOptional[_CollationIn]sessionOptional[ClientSession]Optional[MongoClient]retryable_writer   user_fieldsOptional[Mapping[str, Any]]r   c                 C  s$  |  || t||}t|tst|}|du s#|js#|
du s#td| | |r2|||||  | 	||| |r>| j
nd}t|oF|j }| jrP| | z t| ||| j||||||| j|| j||	|
| j| j||||dW S  ttfyz     ty } z| | 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 ClientSession instance.
        :param client: optional MongoClient 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_sessionr6   
isinstancer   dictacknowledgedr   add_server_api	_apply_tosend_cluster_timero   r   rl   _raise_if_not_writabler8   rk   rY   rf   rt   r   r   BaseExceptionr0   )r   r   r   r   r   r   r   r   r  r  r  r  r   r
  r   r  r   ro   r  errorrR   rR   rS   r8   _  sZ   )



zConnection.commandmessagebytesmax_doc_sizec              
   C  sl   | j dur|| j krtd|| j f z
t| jj| W dS  ty5 } z| | 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.)rf   r   r*   rV   r   r  r0   )r   r  r  r  rR   rR   rS   send_message  s   zConnection.send_message
request_idUnion[_OpReply, _OpMsg]c              
   C  sB   zt | || jW S  ty  } z| | 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)   rg   r  r0   )r   r  r  rR   rR   rS   r)     s   zConnection.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)rd   r   )r   r  rR   rR   rS   r    s   
z!Connection._raise_if_not_writablemsgc                 C  s   |  d | || dS )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   r   r  rR   rR   rS   unack_write  s   
zConnection.unack_writec                 C  s2   |  |d | |}||}t|| j |S )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   )r  r)   command_responser   r   re   )r   r  r   r   r   resultrR   rR   rS   write_command  s
   


zConnection.write_commandreauthenticatec              	   C  s   |r| j rd| _d| _| js_| jj}|r"ddlm} |j|| |d d| _t	 | j
 }| jr@| jdus6J | j| j| j| | jrattjrct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)rc   rx   r}   rm   r   r   r   authenticater`   ra   r   rp   ro   publish_connection_readyrY   r[   rq   r"   isEnabledForloggingDEBUGr$   r#   
CONN_READYr   )r   r%  r   r   durationrR   rR   rS   r,    s4   
zConnection.authenticatec                 C  s   |r|j |urtddS dS )zValidate this session before use with client.

        Raises error if the client is not the one that created the session.
        z9Can only use session with the MongoClient that started itN)_clientr   )r   r   r  rR   rR   rS   r    s
   
zConnection.validate_sessionreasonOptional[str]c              
   C  s   | j rdS |   |rA| jr| jdusJ | j| j| j| | jrCt	t
jrEt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*  r4  r  )r_   _close_connrp   ro   publish_connection_closedrY   r[   rq   r"   r.  r/  r0  r$   r#   CONN_CLOSEDr   r%   )r   r4  rR   rR   rS   r   '  s(   
zConnection.close_connc                 C  s@   | j rdS d| _ | j  z| j  W dS  ty   Y dS w )zClose this connection.NT)r_   r~   cancelrV   close	Exceptionr   rR   rR   rS   r7  <  s   
zConnection._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_SYNCru   socket_closedrV   r   
is_closingr   rR   rR   rS   conn_closedI  s   
zConnection.conn_closedr8   c                 C  s   |r
| || dS dS )zAdd $clusterTime.N)_send_cluster_time)r   r8   r  r   rR   rR   rS   r  P  s   zConnection.send_cluster_timec                 C  s   | j jrt|| j j dS dS )zAdd server_api parameters.N)rm   r   r3   )r   r8   rR   rR   rS   r  Z  s   zConnection.add_server_apic                 C  s   t  | _d S r   r`   ra   rb   r   rR   rR   rS   update_last_checkin_time_     z#Connection.update_last_checkin_timerd   c                 C  s
   || _ d S r   )rd   )r   rd   rR   rR   rS   update_is_writableb     
zConnection.update_is_writablefloatc                 C  s   t  | j S )z9Seconds since this socket was last checked into its pool.rB  r   rR   rR   rS   idle_time_secondse     zConnection.idle_time_secondsr  r  r   c                 C  sP   | j rd }ntj}| | t|ttgtR r't| j	}t
| j||d d S  )Nr   )r}   r'   ERRORr   r  IOErrorOSErrorr,   r/   rm   r0   rY   )r   r  r4  detailsrR   rR   rS   r0   i  s   

z$Connection._raise_connection_failureotherr   c                 C  s   | j |j kS r   )rV   r   rO  rR   rR   rS   __eq__  r   zConnection.__eq__c                 C  s
   | |k S r   rR   rP  rR   rR   rS   __ne__  rF  zConnection.__ne__c                 C  s
   t | jS r   )hashrV   r   rR   rR   rS   __hash__  rF  zConnection.__hash__c                 C  s"   d t| j| jrdpdt| S )NzConnection({}){} at {}z CLOSED )formatreprrV   r_   r[   r   rR   rR   rS   __repr__  s
   zConnection.__repr__)rV   r(   rW   rX   rY   rZ   r[   rN   )r   r   rO   rP   )r   rD   r   r   rO   r   rO   rP   )rO   r   )rO   r   )r   r   r   r   rO   r   )"r   r   r   r   r   rA   r   r9   r   r   r   r   r   r  r  r  r  r   r  r  r  r  r   r	  r
  r   r   r   r  r  r   r   rO   r   )r  r  r  rN   rO   rP   )r  r   rO   r  )r  r   rO   rP   )r   r  r  rN   rO   rP   )r  rN   r   r  r   r9   rO   r   )F)r%  r   rO   rP   )r   r	  r  r  rO   rP   )r4  r5  rO   rP   rO   r   )r8   r   r  r  r   r	  rO   rP   )r8   r   rO   rP   )rd   r   rO   rP   )rO   rG  )r  r  rO   r   )rO  r   rO   r   rO   rN   )rO   r   )'__name__
__module____qualname____doc__r   r   r   r   r   r   r   r   r   r   r7   r2   PRIMARYr   r8   r  r)   r  r!  r$  r,  r  r   r7  r@  r  r  rC  rE  rH  r0   rQ  rR  rT  rX  rR   rR   rR   rS   rU      s`    

9





	

U
Y




"












rU   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)r\  r]  r^  r_  rR   rR   rR   rS   ra    s    ra  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 )_PoolGenerationrO   rP   c                 C  s   t t| _d| _d S r   )collectionsdefaultdictrN   _generations_generationr   rR   rR   rS   r     s   
z_PoolGeneration.__init__r   Optional[ObjectId]rN   c                 C  s   |du r| j S | j| S )z,Get the generation for the given service_id.Nrf  re  r   r   rR   rR   rS   r     s   
z_PoolGeneration.getc                 C  s   | j S )z"Get the Pool's overall generation.)rf  r   rR   rR   rS   r{     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   Nrh  ri  rR   rR   rS   inc  s   
z_PoolGeneration.incry   r   c                 C  s   ||  |kS )z?Return if the given generation for a given service_id is stale.)r   r   ry   r   rR   rR   rS   stale  rI  z_PoolGeneration.staleNrY  )r   rg  rO   rN   r[  )r   rg  rO   rP   ry   rN   r   rg  rO   r   )r\  r]  r^  r   r   r{   rj  rl  rR   rR   rR   rS   rb    s    



	rb  c                   @  s   e Zd ZdZdZdZdS )	PoolStater         N)r\  r]  r^  PAUSEDREADYCLOSEDrR   rR   rR   rS   rn    s    rn  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 )WrX   TNrY   rF   optionsr+   	handshaker   	client_idrg  c                 C  sx  |j rtj| _ntj| _d| _t | _t	 | _
t | _t| j| _d| _d| _d| _t | _t | _|| _|| _|| _| joJ| jjduoJ| jjj| _| j| _t| j| _d| _| jj| _| jsft d| _t| j| _| jj!| _"d| _#|| _$| jr| jjdusJ | jj%| j| jj& | jrt'(t)j*rt+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 handshake: whether to call hello for each new Connection
        r   r   Ninfr  r'  r(  r)  )2pause_enabledrn  rq  staterr  _check_interval_secondsrc  dequeconnssetactive_contextsr!   lockr    _max_connecting_condactive_socketsnext_connection_idrd   rb  ry   osgetpidpidrY   rm   ru  rn   rp   rq   	size_condrequestsmax_pool_sizerG  max_connecting_max_connecting_pendingr   publish_pool_creatednon_default_optionsr"   r.  r/  r0  r$   r#   POOL_CREATEDoperation_count_Pool__pinned_socketsncursorsntxns)r   rY   rt  ru  rv  rR   rR   rS   r     sf   







	
zPool.__init__rO   rP   c                 C  s   | j X | jtjkrCtj| _| jr!| jjd usJ | jj| j | j	rKt
tjrStt
tj| j| jd | jd d W d    d S W d    d S W d    d S W d    d S 1 s^w   Y  d S )Nr   r   rx  )r  rz  rn  rr  rp   rm   rn   publish_pool_readyrY   rq   r"   r.  r/  r0  r$   r#   
POOL_READYr   r   rR   rR   rS   r}     s*   "z
Pool.readyc                 C  s   | j tjkS r   )rz  rn  rs  r   rR   rR   rS   r_   +  s   zPool.closedFr;  pauser   interrupt_connectionsc                 C  s~  | j }| j | jr	 W d    d S | jjr%|r%| jjs%| j tj}| _ | j	| t
 }| j|kr=|| _d| _d| _|d u rK| jt }| _n#t }t }	| jD ]}
|
j|krc||
 qV|	|
 qV|}|	| _|rttj| _ | j  | j  |r| jD ]}|  qW d    n1 sw   Y  | jj}|rtstjdd |D ddi n|D ]}
|
tj q| j r|d usJ |!| j" | j#rt$%t&j'rt(t$t)j| j*| j"d | j"d d d S d S d S |tjkr| j r|d usJ |j+| j"||d | j#rt$%t&j'rt(t$t)j,| j*| j"d | j"d |d	 ts1tjd
d |D ddi d S |D ]	}
|
tj- q3d S )Nr   c                 S     g | ]}| tjqS rR   )r   r'   POOL_CLOSED.0rV   rR   rR   rS   
<listcomp>`      zPool._reset.<locals>.<listcomp>return_exceptionsTr   rx  )r   r  )r  r'  r(  r)  	serviceIdc                 S  r  rR   )r   r'   r   r  rR   rR   rS   r    r  ).rz  r  r_   rm   ry  r   rn  rq  ry   rj  r  r  r  r  r  r}  rc  r|  r   appendrs  r  
notify_allr  r:  rn   r=  asynciogatherr   r'   r  rp   publish_pool_closedrY   rq   r"   r.  r/  r0  r$   r#   r   publish_pool_clearedPOOL_CLEAREDr   )r   r;  r  r   r  	old_statenewpidsocketsdiscardkeeprV   contextro   rR   rR   rS   _reset/  s   






"
	
zPool._resetrd   Optional[bool]c                 C  sJ   || _ | j | jD ]}|| j  q
W d   dS 1 sw   Y  dS )zXUpdates the is_writable attribute on all sockets currently in the
        Pool.
        N)rd   r  r}  rE  )r   rd   _socketrR   rR   rS   rE    s   
"zPool.update_is_writablec                 C  s   | j d||d d S )NF)r;  r   r  r  )r   r   r  rR   rR   rS   reset  s   z
Pool.resetc                 C  s   | j ddd d S )NF)r;  r  r  r   rR   rR   rS   reset_without_pause  s   zPool.reset_without_pausec                 C  s   | j dd d S )NT)r;  r  r   rR   rR   rS   r;    s   z
Pool.closery   rN   c                 C  s   | j ||S r   )ry   rl  rk  rR   rR   rS   stale_generation  rD  zPool.stale_generationreference_generationc                 C  s|  | j  | jtjkr	 W d   dS W d   n1 sw   Y  | jjdur|g }| j , | jrR| jd  | jjkrR|| j	  | jrR| jd  | jjks<W d   n1 s\w   Y  t
sqtjdd |D ddi n|D ]}|tj qs	 | j4 t| j| j | jjkr	 W d   dS | j| jjkr	 W d   dS |  jd7  _W d   n1 sw   Y  d}z9| jd | j| jkr	 W d   W |r| j |  jd8  _| j  W d   n1 sw   Y  | j |  jd8  _| j  W d   dS 1 sw   Y  dS |  jd7  _d}W d   n	1 s+w   Y  |  }d}| j " | j |krDd}|sT| j| | j|j W d   n	1 s_w   Y  |r|tj  W |r| j |  jd8  _| j  W d   n	1 sw   Y  | j |  jd8  _| j  W d   dS 1 sw   Y  dS W |r| j |  jd8  _| j  W d   n	1 sw   Y  | j |  jd8  _| j  W d   n	1 sw   Y  nD|r| j |  jd8  _| j  W d   n	1 sw   Y  | j |  jd8  _| j  W d   w 1 s7w   Y  w q})	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.
        Nc                 S  r  rR   )r   r'   IDLEr  rR   rR   rS   r    r  z-Pool.remove_stale_sockets.<locals>.<listcomp>r  Tr   F)!r  rz  rn  rr  rm   max_idle_time_secondsr}  rH  r  popr=  r  r  r   r'   r  r  lenr  min_pool_sizer  r  r  r  notifyconnectry   r{   
appendleftr  r  r~   r   )r   r  close_connsrV   incrementedr   rR   rR   rS   remove_stale_sockets  s   $$ zPool.remove_stale_socketshandler"Optional[_MongoClientErrorHandler]rU   c           	      C  s  | j  | j}|  jd7  _t }| j| W d   n1 s!w   Y  | jj}| jr:|dus3J || j	| | j
rUttjrUtttj| j| j	d | j	d |d z	t| j	| j}W np ty } zd| j  | j| W d   n1 szw   Y  | jr|dusJ || j	|tj | j
rttjrtttj| j| j	d | j	d |ttjtjd t|ttgtR rt| j}t | j	||d  d}~ww t!|| | j	|}| j  | j|j" | j| W d   n1 sw   Y  |j#r|j"$  z| j%r|&  |j'| _'|r|j(|dd |)  W n* tyE   | j  | j|j" W d   n	1 s9w   Y  |*tj  w |rQ|j+j,-|j. |S )	zConnect to Mongo and return a new Connection.

        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.
        r   Nr   r  r'  r(  r)  r*  r6  rJ  F)completed_handshake)/r  r  r-   r  addrm   rn   rp   publish_connection_createdrY   rq   r"   r.  r/  r0  r$   r#   CONN_CREATEDr   r.   r  r  r8  r'   rK  r9  r%   r  rL  rM  r,   r/   r0   rU   r~   	cancelledr:  ru  r   rd   contribute_socketr,  r   r   	_topologyreceive_cluster_timer   )	r   r  conn_idtmp_contextro   networking_interfacer  rN  rV   rR   rR   rS   r    s   	



zPool.connectGenerator[Connection, None]c           
   	   c  s   | 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}t | }| jrQ|dusHJ || j|j| | jrnt	t
jrntttj| j| jd | jd |j|d z| j | j|j W d   n1 sw   Y  |V  W n' ty   |jp|j}|rt \}}}	||| |s|jr| |  w |jr| j | j | |  j!d7  _!W d   dS 1 sw   Y  dS |jr| j | j | |  j"d7  _"W d   dS 1 sw   Y  dS |jr| | dS dS )a  Get a connection from the pool. Use with a "with" statement.

        Returns a :class:`Connection` 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   rx  r  r&  )#rm   rn   r`   ra   rp   $publish_connection_check_out_startedrY   rq   r"   r.  r/  r0  r$   r#   CHECKOUT_STARTEDr   	_get_connpublish_connection_checked_outr[   CHECKOUT_SUCCEEDEDr  r  r  r~   r  r   r   sysexc_infohandler   r   r  r  r  )
r   r  ro   checkout_started_timerV   r2  pinnedexc_typeexc_val_rR   rR   rS   checkout;  sp   	


""zPool.checkoutr  rG  
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)  r4  r  r+  zconnection pool pausedrJ  )rz  rn  rr  r`   ra   rp   rm   rn   #publish_connection_check_out_failedrY   r&   
CONN_ERRORrq   r"   r.  r/  r0  r$   r#   CHECKOUT_FAILEDr   r/   r0   r   )r   r  r  r2  rN  rR   rR   rS   _raise_if_not_ready  s0   


zPool._raise_if_not_readyc           	      C  s  | j t kr|   | jrLt | }| jr*| jj	dusJ | jj	
| jtj| | jrHttjrHtttj| j| jd | jd dtj|d td| j |  jd7  _W d   n1 saw   Y  t rot }n| jjr|t | jj }nd}| jI | j|dd | j | j!k s|r|t  nd}t"| j|s| j | j!k r| j#  | $| | j|dd | j | j!k r|  j d7  _ W d   n1 sw   Y  d}d	}d	}z| j |  j%d7  _%d}W d   n1 sw   Y  |du r| j&n | j|d	d | j'sK| j(| j)k sK|r|t  nd}t"| j&|s9| j's-| j(| j)k r2| j&#  d}| $| | j|d	d | j'sK| j(| j)k rz| j'* }W n t+yc   |  j(d7  _(Y nw W d   n	1 sow   Y  |r| ,|rd}qnJz(| j-|d
}W | j& |  j(d8  _(| j&#  W d   n	1 sw   Y  n!| j& |  j(d8  _(| j&#  W d   w 1 sw   Y  w |du sW n} t.yM   |r|/t0j1 | j |  j d8  _ |r|  j%d8  _%| j#  W d   n	1 sw   Y  |sLt | }| jr,| jj	dus!J | jj	
| jtj2| | jrLttjrLtttj| j| jd | jd dtj2|d  w d|_3|S )z8Get or create a Connection. 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  rY   r&   r  rq   r"   r.  r/  r0  r$   r#   r  r   ra  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'   rK  r  r   )	r   r  r  r2  deadliner   rV   r  emitted_eventrR   rR   rS   r    s   




	


   

zPool._get_connrV   c              
   C  sf  |j }|j}d|_d|_ d|_| j| | jj}| j | j|j	 W d   n1 s.w   Y  | j
rD|dus<J || j|j | jr`ttjr`tttj| j| jd | jd |jd | jt krl|   n| jrv|tj nx|jr| j
r|dusJ || j|jtj  | jrttjrtttj!| j| jd | jd |jt"tj tj d n?d}| j* | #|j$|j%rd}n|&  |'t(| j) | j*+| | j,-  W d   n1 sw   Y  |r|tj. | j/7 |r|  j0d8  _0n
|r|  j1d8  _1|  j2d8  _2|  j3d8  _3|  j4d8  _4| j/-  W d   dS 1 s,w   Y  dS )zReturn the connection to the pool, or if it's closed discard it.

        :param conn: The connection to check into the pool.
        FNr   r   r  r6  T)5r   r   r   r  r  rm   rn   r  r  r~   rp   publish_connection_checked_inrY   r[   rq   r"   r.  r/  r0  r$   r#   	CHECKEDINr   r  r  r  r  r_   r   r'   r  r8  rK  r9  r%   r  r|   r   rC  rE  r   rd   r}  r  r  r  r   r  r  r  r  r  r  )r   rV   txncursorro   r   rR   rR   rS   r   %  s   

$zPool.checkinc                 C  s   |  }| jjdur|| jjkr|tj dS | jdur3| jdks'|| jkr3| r3|tj dS | 	|j
|jrC|tj 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)rH  rm   r  r   r'   r  r{  r@  rK  r  r|   r   r   )r   rV   rH  rR   rR   rS   r  p  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  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  rY   r&   TIMEOUTrq   r"   r.  r/  r0  r$   r#   r  r   r   r  r  r   r  r  r  r   rV  r  )r   r  ro   r2  r   	other_opsrR   rR   rS   r    sL   

zPool._raise_wait_queue_timeoutc                 C  s"   t r| jD ]	}|d  qd S d S r   )r=  r}  r   )r   rV   rR   rR   rS   __del__  s
   
zPool.__del__)TN)rY   rF   rt  r+   ru  r   rv  rg  rY  rZ  )TNF)
r;  r   r  r   r   rg  r  r   rO   rP   )rd   r  rO   rP   )NF)r   rg  r  r   rO   rP   rm  )r  rN   rO   rP   r   )r  r  rO   rU   )r  r  rO   r  )r  rG  r  r   rO   rP   )r  rG  r  r  rO   rU   )rV   rU   rO   rP   )rV   rU   rO   r   )r  rG  rO   r   )r\  r]  r^  r   r}   propertyr_   r  rE  r  r  r;  r  r  r  
contextlibcontextmanagerr  r  r  r   r  r  r  rR   rR   rR   rS   rX     s<    
V
]




ES
N 

K
$'rX   )rM   rN   rO   rP   )w
__future__r   r  rc  r  r/  r  r  r`   r\   typingr   r   r   r   r   r   r	   r
   r   bsonr   pymongor   r   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_sharedr,   r-   r.   r/   r0   r1   pymongo.read_preferencesr2   pymongo.server_apir3   pymongo.server_typer4   pymongo.socket_checkerr5   "pymongo.synchronous.client_sessionr6   pymongo.synchronous.helpersr7   pymongo.synchronous.networkr8   r9   bson.objectidr:   pymongo.compression_supportr;   r<   r=   pymongo.messager>   r?   pymongo.read_concernr@   rA   pymongo.synchronous.authrB   rC    pymongo.synchronous.mongo_clientrD   rE   pymongo.typingsrF   rG   pymongo.write_concernrH   rL   rI   rJ   rK   rT   ImportErrorr=  rU   ra  rb  rn  rX   rR   rR   rR   rS   <module>   sp   ,,     