o
    {g                    @  s6  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
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,m-Z-m.Z.m/Z/ d dl0m1Z1m2Z2 d d	l3m4Z4m5Z5 d d
l6m7Z7m8Z8m9Z9m:Z: d dl;m<Z<m=Z= d dl>m?Z? d dl@mAZA d dlBmCZC d dlDmEZE d dlFmGZG d dlHmIZI d dlJmKZKmLZL d dlMmNZN d dlOmPZP d dlQmRZRmSZS er?d dlmTZT d dlUmVZV d dlWmXZXmYZYmZZZ d dl[m\Z\m]Z] d dl^m_Z_ d dl`maZa d dlBmbZb d dlcmdZd d dlMmeZe d dlfmgZgmhZh d d limjZjmkZkmlZl d d!lmmnZn zd d"lompZpmqZqmrZrmoZo dld'd(ZsW n etya   dld)d(ZsY nw d*Zud+Zvd,Zwd-Zxe
jyd.krzd dlzZ{W n ety   d dl{Z{Y nw d/d0 Z|z&e{}e{j~d1Ze|ed2d3Ze|ed4d5ZW d   n	1 sw   Y  W n ey   d3Zd5ZY nw d6d7 Zn
dmd=d>Zdnd?d7Z		dodpdIdJZdqdPdQZdrdUdVZdsdXdYZG dZd[ d[ZG d\d] d]Zdtd_d`ZdudbdcZG ddde dee-ZG dfdg dgZG dhdi diZG djdk dkZdS )v    )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ConnectionFailureDocumentTooLargeExecutionTimeoutInvalidOperationNetworkTimeoutNotPrimaryErrorOperationFailurePyMongoErrorWaitQueueTimeoutError_CertificateError)HelloHelloCompat)_create_lock_Lock)_CONNECTION_LOGGER_ConnectionStatusMessage
_debug_log _verbose_connection_error_reason)ConnectionCheckOutFailedReasonConnectionClosedReason)sendall)PoolOptions)ReadPreference)_add_to_command)SERVER_TYPE)SocketChecker)HAS_SNISSLError)_validate_session_write_concern)_handle_reauth)commandreceive_message)CodecOptions)ObjectId)SnappyContextZlibContextZstdContext)_OpMsg_OpReply)_sslConn)ReadConcern)_ServerMode)_AuthContext)ClientSession)MongoClient_MongoClientErrorHandler)ClusterTime_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)rK   rH   rI   rJ   )rL   flags rQ   u/var/www/bot.gig.net.ua/public_html/telegram/P1/HellBot/venv/lib/python3.10/site-packages/pymongo/synchronous/pool.py_set_non_inheritable_non_atomicl   s   
rS   c                 C  s   dS )z6Dummy function for platforms that don't provide fcntl.NrQ   )rL   rQ   rQ   rR   rS   u   s    Tx   
   	   win32c              	   C  s6   zt | |\}}t|W S  ttfy   | Y S w N)winregQueryValueExrM   OSError
ValueError)keynamedefaultvalue_rQ   rQ   rR   _query   s   
rb   z2SYSTEM\CurrentControlSet\Services\Tcpip\ParametersKeepAliveTimei m KeepAliveInterval  c                 C  sH   t ttd }t ttd }|tk s|tk r"| tjd||f d S d S )Nre      )min_WINDOWS_TCP_IDLE_MS_MAX_TCP_KEEPIDLE_WINDOWS_TCP_INTERVAL_MS_MAX_TCP_KEEPINTVLioctlsocketSIO_KEEPALIVE_VALS)sockidle_msinterval_msrQ   rQ   rR   _set_keepalive_times   s
   rr   ro   socket.socket
tcp_optionstr	max_valuec                 C  s`   t t|r.tt|}z| tj|}||kr!| tj|| W d S W d S  ty-   Y d S w d S rX   )hasattrrm   getattr
getsockoptIPPROTO_TCP
setsockoptr[   )ro   rt   rv   sockoptr_   rQ   rQ   rR   _set_tcp_option   s   

r}   c                 C  s(   t | dt t | dt t | dt d S )NTCP_KEEPIDLETCP_KEEPINTVLTCP_KEEPCNT)r}   ri   rk   _MAX_TCP_KEEPCNT)ro   rQ   rQ   rR   rr      s   addressr   error	Exception
msg_prefixOptional[str]timeout_detailsOptional[dict[str, float]]r   c                 C  s   | \}}|durd|||f }n| d| }|r|| }d|vr'|t |7 }t|tjr2t||t|trBdt|v rBt||t||)z9Convert a socket.error to ConnectionFailure and raise it.Nz	%s:%d: %s: zconfigured timeouts	timed out)format_timeout_details
isinstancerm   timeoutr   r1   ru   r   )r   r   r   r   hostportmsgrQ   rQ   rR   _raise_connection_failure   s   


r   	conditionthreading.ConditiondeadlineOptional[float]boolc                 C  s   |r|t   nd }| |S rX   )time	monotonicwait)r   r   r   rQ   rQ   rR   
_cond_wait   s   
r   optionsr+   dict[str, float]c                 C  sP   i }t  }| j}| j}|r|d |d< |r|s|d |d< |r&|d |d< |S )Nre   	timeoutMSsocketTimeoutMSconnectTimeoutMS)r   get_timeoutsocket_timeoutconnect_timeout)r   detailsr   r   r   rQ   rQ   rR   _get_timeout_details   s   r   r   c                 C  sT   d}| r(|d7 }dD ]}|| v r|d| d| |  d7 }q
|d d }|d7 }|S )	N z (configured timeouts:)r   r   r    r   zms,)rQ   )r   resultr   rQ   rQ   rR   r      s   r   c                   @  s.   e Zd ZdddZdddZeddd	Zd
S )_CancellationContextrN   rO   c                 C  s
   d| _ d S NF
_cancelledselfrQ   rQ   rR   __init__      
z_CancellationContext.__init__c                 C  s
   d| _ dS )zCancel this context.TNr   r   rQ   rQ   rR   cancel   s   
z_CancellationContext.cancelr   c                 C     | j S )zWas cancel called?r   r   rQ   rQ   rR   	cancelled   s   z_CancellationContext.cancelledNrN   rO   rN   r   )__name__
__module____qualname__r   r   propertyr   rQ   rQ   rQ   rR   r      s
    

r   c                   @  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/d0d0d0d1d0d0d0d1d/d0d1fddMdNZddRdSZddVdWZddYdZZdd\d]Zdd^d_ZdddadbZddcddZddgdhZddidjZddkdlZddndoZddpdqZddrdsZddudvZ ddxdyZ!dd}d~Z"dddZ#dddZ$dddZ%dddZ&d0S )
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
    connUnion[socket.socket, _sslConn]poolPoolr   tuple[str, int]idrM   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 S )NFg        )7weakrefrefpool_refr   r   r   closedr   r   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_contextr/   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activer   last_timeoutconnect_rtt
_client_idcreation_time)r   r   r   r   r   rQ   rQ   rR   r   	  sP   



zConnection.__init__r   r   rN   rO   c                 C  s$   || j krdS || _ | j| dS )z?Cache last timeout to avoid duplicate calls to conn.settimeout.N)r   r   
settimeout)r   r   rQ   rQ   rR   set_conn_timeout<  s   
zConnection.set_conn_timeoutclientrB   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:r   2   okerrmsgcodere   	maxTimeMS)r   	remainingr   r   r   r   get_rttr   r   r   r   r   rM   )	r   r   r   r   rttmax_time_msr   	formattedr   rQ   rQ   rR   apply_timeoutC  s.   


zConnection.apply_timeoutc                 C     d| _ | jrJ d S NT)r   r   r   rQ   rQ   rR   pin_txnb     zConnection.pin_txnc                 C  r   r   )r   r   r   rQ   rQ   rR   
pin_cursorf  r  zConnection.pin_cursorc                 C  s*   |   }|r||  d S | tj d S rX   )r   checkin
close_connr)   STALE)r   r   rQ   rQ   rR   unpinj  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 )NTrf   helloOk)r   
server_apir   load_balancedr   r!   CMD
LEGACY_CMDr   rQ   rQ   rR   	hello_cmdq  s   
zConnection.hello_cmdr    c                 C  s   |  d d d S rX   )_hellor   rQ   rQ   rR   helloz     zConnection.hellocluster_timeOptional[ClusterTime]topology_versionOptional[Any]heartbeat_frequencyOptional[int]Hello[dict[str, Any]]c                 C  sl  |   }| 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|  |sV|d urV||d	< | jj
}|r|jd
krn|jrn|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r4|j8s(t9d|j8| _8| j:;| j8| _<|S )NFTr   compressionloadBalancedtopologyVersionre   maxAwaitTimeMSz$clusterTime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  r   r   metadatar   compressorsr
  rM   r   r   _credentials	mechanismusernamesourcepymongo.synchronousr   r@   from_credentialsr   speculate_commandr   r   r4   r   r    r   r   r   r   r   logical_session_timeout_minutesis_readabler   r   server_typer.   	RSPrimaryRSSecondary	RSArbiterRSOtherRSGhostis_repl
Standaloneis_standaloneMongosr   get_compression_contextr   r   connection_idr   sasl_supported_mechsr   parse_responsespeculate_succeededr   r   r   r   getr   )r   r  r  r  r   performing_handshaker%  credsr   r   speculative_authenticatestartdocr  ctxrQ   rQ   rR   r  }  s   



zConnection._helloc                 C  s4   |  d }|j| _| }|d }t|| j |S Nr   )r5   r   unpack_responser   _check_command_responser   )r   replyunpacked_docsresponse_docrQ   rQ   rR   _next_reply  s   
zConnection._next_replyTNFdbnameru   specMutableMapping[str, Any]read_preferencer?   codec_optionsr6   checkr   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.)rZ  r[  compression_ctx
use_op_msgunacknowledgedra  r$  rX  )validate_sessionr2   r   r   dictacknowledgedr   add_server_api	_apply_tosend_cluster_timer   r   r   _raise_if_not_writabler4   r   r   r   r   r   r   BaseExceptionr   )r   rN  rO  rQ  rR  rS  rT  rV  rX  rZ  r[  r]  r   r`  r#  ra  r$  r   re  r   rQ   rQ   rR   r4     sZ   )



zConnection.commandmessagebytesmax_doc_sizec              
   C  sj   | j dur|| j krtd|| j f z	t| j| W dS  ty4 } 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.)r   r   r*   r   rm  r   )r   rn  rp  r   rQ   rQ   rR   send_message8  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)r5   r   rm  r   )r   rr  r   rQ   rQ   rR   r5   H  s   zConnection.receive_messagere  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   re  rQ   rQ   rR   rl  R  s   
z!Connection._raise_if_not_writabler   c                 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)rl  rq  )r   r   rp  rQ   rQ   rR   unack_writeZ  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   )rq  r5   command_responser   rI  r   )r   rr  r   rR  rJ  r   rQ   rQ   rR   write_commande  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| jt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  )rw  Trf   clientIdrn  
serverHost
serverPortdriverConnectionId
durationMS)r   r   r   r   r(  r,  r   authenticater   r   r   r   r   publish_connection_readyr   r   r   r$   isEnabledForloggingDEBUGr&   r   r%   
CONN_READY)r   rw  rB  r   durationrQ   rQ   rR   r~  w  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]  rQ   rQ   rR   rf    s
   
zConnection.validate_sessionreasonr   c              
   C  s   | j rdS |   |rA| jr| jdusJ | j| j| j| | jrCt	t
jrEtt| jtj| jd | jd | jt||d dS dS dS dS )z$Close this connection with a reason.Nr   rf   ry  rn  rz  r{  r|  r  r   )r   _close_connr   r   publish_connection_closedr   r   r   r$   r  r  r  r&   r   r%   CONN_CLOSEDr'   )r   r  rQ   rQ   rR   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   r   r   closer   r   rQ   rQ   rR   r    s   
zConnection._close_connc                 C  s   | j | jS )z?Return True if we know socket has been closed, False otherwise.)r   socket_closedr   r   rQ   rQ   rR   conn_closed     zConnection.conn_closedr4   c                 C  s   |r
| || dS dS )zAdd $clusterTime.N)_send_cluster_time)r   r4   r]  r   rQ   rQ   rR   rk    s   zConnection.send_cluster_timec                 C  s   | j jrt|| j j dS dS )zAdd server_api parameters.N)r   r	  r-   )r   r4   rQ   rQ   rR   ri    s   zConnection.add_server_apic                 C  s   t  | _d S rX   r   r   r   r   rQ   rQ   rR   update_last_checkin_time  r  z#Connection.update_last_checkin_timer   c                 C  s
   || _ d S rX   )r   )r   r   rQ   rQ   rR   update_is_writable  r   zConnection.update_is_writablefloatc                 C  s   t  | j S )z9Seconds since this socket was last checked into its pool.r  r   rQ   rQ   rR   idle_time_seconds  r  zConnection.idle_time_secondsr   rm  r   c                 C  sL   | j rd }ntj}| | t|tttfr%t| j	}t
| j||d d S  )Nr   )r   r)   ERRORr  r   IOErrorr[   r1   r   r   r   r   )r   r   r  r   rQ   rQ   rR   r     s   

z$Connection._raise_connection_failureotherr   c                 C  s   | j |j kS rX   )r   r   r  rQ   rQ   rR   __eq__  s   zConnection.__eq__c                 C  s
   | |k S rX   rQ   r  rQ   rQ   rR   __ne__  r   zConnection.__ne__c                 C  s
   t | jS rX   )hashr   r   rQ   rQ   rR   __hash__  r   zConnection.__hash__c                 C  s"   d t| j| jrdpdt| S )NzConnection({}){} at {}z CLOSEDr   )formatreprr   r   r   r   rQ   rQ   rR   __repr__  s
   zConnection.__repr__)r   r   r   r   r   r   r   rM   )r   r   rN   rO   )r   rB   r   r   rN   r   r   )rN   r  )rN   r    )r  r  r  r  r  r  rN   r  )"rN  ru   rO  rP  rQ  r?   rR  r6   rS  r   rT  rU  rV  rW  rX  rY  rZ  r   r[  r\  r]  r^  r   r_  r`  r   r#  r   ra  rb  r$  r   rN   r  )rn  ro  rp  rM   rN   rO   )rr  r  rN   rs  )re  r   rN   rO   )r   ro  rp  rM   rN   rO   )rr  rM   r   ro  rR  r6   rN   r  )F)rw  r   rN   rO   )r   r_  r]  r^  rN   rO   )r  r   rN   rO   r   )r4   rP  r]  r^  r   r_  rN   rO   )r4   rP  rN   rO   )r   r   rN   rO   )rN   r  )r   rm  rN   r   )r  r   rN   r   rN   rM   )rN   ru   )'r   r   r   __doc__r   r   r   r   r  r  r  r  r  rM  r3   r,   PRIMARYr   r4   rq  r5   rl  rt  rv  r~  rf  r  r  r  rk  ri  r  r  r  r   r  r  r  r  rQ   rQ   rQ   rR   r      s`    

3





	

Y
Y





"












r   rE   c                 C  s  | \}}| dr3ttdstdttj}t|  z|| |W S  ty2   |	   w tj
}tjr@|dkr@tj}d}t|||tjD ]}|\}}	}
}}zt||	ttddB |
}W n tys   t||	|
}Y nw t|  z:|tjtjd t }|du r|j}n	|dkrtd	|| |tjtjd
 t| || |W   S  ty } z|}|	  W Y d}~qKd}~ww |dur|td)zGiven (host, port) and PoolOptions, connect and return a socket object.

    Can raise socket.error.

    This is a modified version of create_connection from CPython >= 2.7.
    z.sockAF_UNIXz-UNIX-sockets are not supported on this system	localhostNSOCK_CLOEXECr   rf   r   Tzgetaddrinfo failed)endswithrw   rm   r   r  rS   filenoconnectr[   r  AF_INEThas_ipv6	AF_UNSPECgetaddrinfoSOCK_STREAMrx   r{   rz   TCP_NODELAYr   r   r   r   r   
SOL_SOCKETSO_KEEPALIVErr   )r   r   r   r   ro   familyerrresafsocktypeprotodummysar   erQ   rQ   rR   _create_connection  sZ   






r  r   c           	   
   C  sz  t | |}|j}|du r||j |S | d }zLtrDtr%|j||d}n>t|dr2|j||d}n1t	
 }|dtj|j||d}ntrL||}nt|drW||}nt	
 }|d|j|}W n/ typ   |    ttfy } z|  t|}t| |d|d W Y d}~nd}~ww |jr|js|jsztj| |d W n ty   |   w ||j |S )zGiven (host, port) and PoolOptions, return a configured socket.

    Can raise socket.error, ConnectionFailure, or _CertificateError.

    Sets socket's SSL and timeout options.
    Nr   )server_hostnamea_wrap_socketzSSL handshake failed: r  )hostname)r  _ssl_contextr   r   r0   _IS_SYNCwrap_socketrw   r  asyncioget_running_looprun_in_executor	functoolspartialr   r  r[   r1   r   r   verify_modecheck_hostnametls_allow_invalid_hostnamessslmatch_hostnamegetpeercert)	r   r   ro   ssl_contextr   ssl_sockloopexcr   rQ   rQ   rR   _configured_socketW  s^   


r  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  rQ   rQ   rQ   rR   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 )_PoolGenerationrN   rO   c                 C  s   t t| _d| _d S rG  )collectionsdefaultdictrM   _generations_generationr   rQ   rQ   rR   r     s   
z_PoolGeneration.__init__r   Optional[ObjectId]rM   c                 C  s   |du r| j S | j| S )z,Get the generation for the given service_id.Nr  r  r   r   rQ   rQ   rR   r@    s   
z_PoolGeneration.getc                 C  r   )z"Get the Pool's overall generation.)r  r   rQ   rQ   rR   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.rf   Nr  r  rQ   rQ   rR   inc  s   
z_PoolGeneration.incr   r   c                 C  s   ||  |kS )z?Return if the given generation for a given service_id is stale.)r@  r   r   r   rQ   rQ   rR   stale  r  z_PoolGeneration.staleNr   )r   r  rN   rM   r  )r   r  rN   rO   r   rM   r   r  rN   r   )r   r   r   r   r@  r   r  r  rQ   rQ   rQ   rR   r    s    



	r  c                   @  s   e Zd ZdZdZdZdS )	PoolStaterf         N)r   r   r   PAUSEDREADYCLOSEDrQ   rQ   rQ   rR   r    s    r  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 )Wr   TNr   rE   r   r+   	handshaker   	client_idr  c                 C  st  |j rtj| _ntj| _d| _t | _t	 | _
t }t|| _d| _d| _d| _t | _t | _|| _|| _|| _| joH| jjduoH| jjj| _| j| _t|| _d| _| jj | _ | j sdt!d| _ t|| _"| jj#| _$d| _%|| _&| jr| jjdusJ | jj'| j| jj( | jrt)*t+j,rt-t)f| j&t.j/| jd | jd d| jj( d| _0t	 | _1d| _2d| _3dS )z
        :param address: a (hostname, port) tuple
        :param options: a PoolOptions instance
        :param handshake: whether to call hello for each new Connection
        rf   r   Ninfry  rn  rz  r{  )4pause_enabledr  r  stater  _check_interval_secondsr  dequeconnssetactive_contextsr"   r#   lockactive_socketsnext_connection_idr   r  r   osgetpidpidr   r   r  r   r   r   	threading	Condition	size_condrequestsmax_pool_sizer  _max_connecting_cond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   r   r  r  _lockrQ   rQ   rR   r     sf   








	
zPool.__init__rN   rO   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
| jt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   rf   r  )r  r  r  r  r   r   r   publish_pool_readyr   r   r$   r  r  r  r&   r   r%   
POOL_READYr   rQ   rQ   rR   r     s*   "z
Pool.readyc                 C  s   | j tjkS rX   )r  r  r  r   rQ   rQ   rR   r   .  s   zPool.closedFr  pauser   interrupt_connectionsc                 C  s8  | 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}|r|D ]}
|
tj q| jr|d usJ || j | j rt!"t#j$rt%t!| j&t'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!| j&t'j)| jd | jd |d |D ]	}
|
tj* qd S )Nr   rf   r  )r   r
  )ry  rn  rz  r{  	serviceId)+r  r  r   r   r  r
  r  r  r   r  r  r  r  r  r  r  r  r  r   appendr  r  
notify_allr  r   r   r  r)   POOL_CLOSEDr   publish_pool_closedr   r   r$   r  r  r  r&   r   r%   publish_pool_clearedPOOL_CLEAREDr  )r   r  r	  r   r
  	old_statenewpidsocketsdiscardkeepr   contextr   rQ   rQ   rR   _reset2  s   






"
	zPool._resetr   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)r   r  r  r  )r   r   _socketrQ   rQ   rR   r    s   
"zPool.update_is_writablec                 C  s   | j d||d d S )NF)r  r   r
  r  )r   r   r
  rQ   rQ   rR   reset  s   z
Pool.resetc                 C  s   | j ddd d S )NF)r  r	  r  r   rQ   rQ   rR   reset_without_pause  s   zPool.reset_without_pausec                 C  s   | j dd d S )NT)r  r  r   rQ   rQ   rR   r    s   z
Pool.closer   rM   c                 C  s   | j ||S rX   )r   r  r  rQ   rQ   rR   stale_generation  r  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rb| j / | jrS| jd  | jjkrS| j }|	t
j | jrS| jd  | jjks:W d   n1 s]w   Y  	 | 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}z4| jb | 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 sw   Y  dS |  jd7  _d}W d   n	1 sw   Y  |  }| j q | j |krx|	t
j 	 W d   W |rU| j |  jd8  _| j  W d   n	1 sPw   Y  | j |  jd8  _| j  W d   dS 1 sqw   Y  dS | j| | j|j W d   n	1 sw   Y  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 sw   Y  | j |  jd8  _| j  W d   w 1 sw   Y  w qc)zRemoves stale sockets then adds new ones if pool is too small and
        has not been reset. The `reference_generation` argument specifies the
        `generation` at the point in time this operation was requested on the
        pool.
        Nr   Trf   F)r  r  r  r  r   max_idle_time_secondsr  r  popr  r)   IDLEr  lenr  min_pool_sizer  r  r  r  notifyr  r   r   r  
appendleftr  r  r   )r   r  r   incrementedrQ   rQ   rR   remove_stale_sockets  s   
"	$	 zPool.remove_stale_socketshandler"Optional[_MongoClientErrorHandler]r   c                 C  s  | j  | j}|  jd7  _W d   n1 sw   Y  | jj}| jr1|dus*J || j| | jrLt	t
jrLtt| jtj| jd | jd |d z	t| j| j}W nU ty } zI| jro|dusfJ || j|tj | jrt	t
jrtt| jtj| jd | jd |ttjtjd t|tttfrt| j}t| j||d  d}~ww t|| | j|}| j  | j|j  W d   n1 sw   Y  z| j!r|"  |j#| _#|r|j$|dd |%  W |S  ty   |&tj  w )	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.
        rf   Nr   ry  rn  rz  r{  r|  r  r  F)completed_handshake)'r  r  r   r   r   publish_connection_createdr   r   r$   r  r  r  r&   r   r%   CONN_CREATEDr  rm  r  r)   r  r  r'   r   r  r[   r1   r   r   r   r  addr   r  r  r   contribute_socketr~  r  )r   r)  conn_idr   ro   r   r   r   rQ   rQ   rR   r    st   	



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| jtj| jd | jd d | j||d}t | }| jrQ|dusHJ || j|j| | jrnt	t
jrntt| jt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   rf   r  r)  rx  )#r   r   r   r   r   $publish_connection_check_out_startedr   r   r$   r  r  r  r&   r   r%   CHECKOUT_STARTED	_get_connpublish_connection_checked_outr   CHECKOUT_SUCCEEDEDr  r  r/  r   rm  r   r   sysexc_infohandler   r  r  r  r  )
r   r)  r   checkout_started_timer   r  pinnedexc_typeexc_valra   rQ   rQ   rR   checkout  sp   	


""zPool.checkoutr<  r  
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| jtj| j	d | j	d dt
j|d t| j}t| j	td|d d S d S )Nr   rf   <An error occurred while trying to establish a new connectionry  rn  rz  r{  r  r   r}  zconnection pool pausedr  )r  r  r  r   r   r   r   r   #publish_connection_check_out_failedr   r(   
CONN_ERRORr   r$   r  r  r  r&   r   r%   CHECKOUT_FAILEDr   r   r   )r   r<  rA  r  r   rQ   rQ   rR   _raise_if_not_readye  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| jt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? | j|dd | j | j!k st"| 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&c | j|d	d | j's6| j(| j)k s6t"| j&|s$| j's| j(| j)k r| j&#  d}| $| | j|d	d | j's6| j(| j)k rz| j'* }W n t+yN   |  j(d7  _(Y nw W d   n	1 sZw   Y  |rl| ,|rkd}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.y8   |r|/t0j1 | j |  j d8  _ |r|  j%d8  _%| j#  W d   n	1 sw   Y  |s7t | }| jr| jj	dusJ | jj	
| jtj2| | jr7ttjr7tt| jtj| jd | jd dtj2|d  w d|_3|S )z8Get or create a Connection. Can raise ConnectionFailure.Nr   rf   zConnection pool was closedrC  z?Attempted to check out a connection from closed connection poolT)rA  Fr3  rB  )4r  r  r  r  r   r   r   r   r   r   rD  r   r(   r  r   r$   r  r  r  r&   r   r%   rF  r  r  r  r   r   get_deadlinewait_queue_timeoutr  rG  r  r  r   r%  _raise_wait_queue_timeoutr  r  r  r  r  popleft
IndexError	_perishedr  rm  r  r)   r  rE  r   )r   r<  r)  r  r   r   r'  emitted_eventrQ   rQ   rR   r6    s   








  

zPool._get_connr   c              
   C  sX  |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| jtj| jd | jd |jd | jt krl|   n|| jrv|tj nr|jr| j
r|dusJ || j|jtj  | jrttjrtt| jtj!| jd | jd |jt"tj tj d n9| j. | #|j$|j%r|tj& n|'  |(t)| j* | j+,| | j-.  W d   n1 sw   Y  | j/6 |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   rf   r+  r  )5r   r   r   r  r  r   r   r  r  r   r   publish_connection_checked_inr   r   r   r$   r  r  r  r&   r   r%   	CHECKEDINr  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  r  r  )r   r   txncursorr   rQ   rQ   rR   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)r  r   r   r  r)   r"  r  r  r  r  r   r   r  )r   r   r  rQ   rQ   rR   rM  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
| jt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   rf   zBWait queue timeout elapsed without a connection becoming availablerC  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: )r   r   r   r   r   rD  r   r(   TIMEOUTr   r$   r  r  r  r&   r   r%   rF  r   r   rI  r
  r  r  r  r   r  r  )r   r<  r   r  r   	other_opsrQ   rQ   rR   rJ  i  sL   

zPool._raise_wait_queue_timeoutc                 C  s   | j D ]}|d  qd S rX   )r  r  )r   r   rQ   rQ   rR   __del__  s   
zPool.__del__)TN)r   rE   r   r+   r  r   r  r  r   r   )TNF)
r  r   r	  r   r   r  r
  r   rN   rO   )r   r  rN   rO   r   )r   r  r
  r   rN   rO   r  )r  rM   rN   rO   rX   )r)  r*  rN   r   )r)  r*  rN   r2  )r<  r  rA  r   rN   rO   )r<  r  r)  r*  rN   r   )r   r   rN   rO   )r   r   rN   r   )r<  r  rN   r   )r   r   r   r   r   r   r   r  r  r  r  r  r  r(  r  
contextlibcontextmanagerr@  rG  r6  r  rM  rJ  rU  rQ   rQ   rQ   rR   r     s:    
V
Q




9D
M
~
H
$'r   )rL   rM   rN   rO   )ro   rs   rt   ru   rv   rM   rN   rO   )ro   rs   rN   rO   )NN)
r   r   r   r   r   r   r   r   rN   r   )r   r   r   r   rN   r   )r   r+   rN   r   )r   r   rN   ru   )r   rE   r   r+   rN   rs   )r   rE   r   r+   rN   r   )
__future__r   r  r  rV  r  r  r  rm   r  r9  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   r   r   r   pymongo.hellor    r!   pymongo.lockr"   r#   pymongo.loggerr$   r%   r&   r'   pymongo.monitoringr(   r)   pymongo.network_layerr*   pymongo.pool_optionsr+   pymongo.read_preferencesr,   pymongo.server_apir-   pymongo.server_typer.   pymongo.socket_checkerr/   pymongo.ssl_supportr0   r1   "pymongo.synchronous.client_sessionr2   pymongo.synchronous.helpersr3   pymongo.synchronous.networkr4   r5   r6   bson.objectidr7   pymongo.compression_supportr8   r9   r:   pymongo.messager;   r<   pymongo.pyopenssl_contextr=   pymongo.read_concernr>   r?   pymongo.synchronous.authr@   rA    pymongo.synchronous.mongo_clientrB   rC   pymongo.typingsrD   rE   rF   pymongo.write_concernrG   rK   rH   rI   rJ   rS   ImportErrorr  ri   rk   r   platform_winregrY   rb   OpenKeyHKEY_LOCAL_MACHINEr]   rh   rj   r[   rr   r}   r   r   r   r   r   r   r  r  r  r  r  r   rQ   rQ   rQ   rR   <module>   s   ,8



	


    

GB