
    FCf4C                      U 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 d dlmZmZmZmZmZmZmZmZmZ d dlZd dlmZ d dlmZmZmZm Z  d dl!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- d d	l.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z: d d
l;m<Z<m=Z= d dl>m?Z? d dl@mAZA d dlBmCZCmDZDmEZEmFZF d dlGmHZHmIZImJZJ d dlKmLZLmMZM d dlNmOZO d dlPmQZQ d dlRmSZS d dlTmUZU d dlVmWZWmXZX erfd dlmYZY d dlZm[Z[ d dl\m]Z]m^Z^ d dl!m_Z_ d dl`maZambZbmcZcmdZd d dlemfZf d dlgmhZhmiZi d dljmkZkmlZl d dlmmnZnmoZo d dlpmqZq d dlNmrZr d d lPmsZs d d!ltmuZumvZvmwZw d d"lxmyZy 	 d d#lzm{Z{m|Z|m}Z}mzZz dld$Z~d&Zd'Zd(Ze
j                  d)k(  rI	 d dlZd* Z	  ej                  ej                  d+      5 Z eed,d-      Z eed.d/      Zddd       d0 Zndmd1Zdnd2Zd3d4ed5iZd6ed7<   e
j                  j!                  d8      r> ej"                         Zee ej&                          ej(                         d9ed:<   ne
j                  d;k(  rO ej"                          ej"                          ej&                          ej*                         d    d9ed:<   nee
j                  d)k(  r ej"                         d<j-                   ej"                          ej(                         f       ej&                         d=j-                   ej.                         d>d?       d9ed:<   ne
j                  j!                  d@      r$ ej0                         dA   \  ZZZeeeed9ed:<   n ej6                   ej"                          ej(                          ej8                               Z ej"                         d<j-                  eddB D  cg c]  } | s| 	 c}        ej&                         edB   d9ed:<    ej<                         j!                  dC      rpd<j-                   ej<                         dDj-                   eee
jB                              dEdDj-                   eee
jD                              z  f      edF<   ne
j                  j!                  d@      rd<j-                   ej<                         dDj-                   eee
jD                              dGd<j-                   ej"                          ej(                         f      z  f      edF<   nId<j-                   ej<                         dDj-                   eee
jD                              f      edF<   dHZdIZdJZdKZdodLZdpdMZdpdNZdpdOZdpdPZdpdQZdqdRZdrdSZdTZdsdUZdVjc                  dW       	 	 dt	 	 	 	 	 	 	 	 	 dudXZdvdYZdwd[Zdxd\Z G d] dZ      Z G d^ d_      Z G d` da      ZdydbZdzdcZ G dd dee8      Z G df dg      Z G dh di      Z G dj dk      Zy# e$ r dld%Z~Y w xY w# e$ r d dlZY w xY w# 1 sw Y   xY w# e$ r d-Zd/ZY w xY wc c} w ){    )annotationsN)Path)	TYPE_CHECKINGAnyIteratorMappingMutableMappingNoReturnOptionalSequenceUnion)DEFAULT_CODEC_OPTIONS)__version___csotauthhelpers)_validate_session_write_concern)
MAX_BSON_SIZEMAX_CONNECTINGMAX_IDLE_TIME_SECMAX_MESSAGE_SIZEMAX_POOL_SIZEMAX_WIRE_VERSIONMAX_WRITE_BATCH_SIZEMIN_POOL_SIZEORDERED_TYPESWAIT_QUEUE_TIMEOUT)AutoReconnectConfigurationErrorConnectionFailureDocumentTooLargeExecutionTimeoutInvalidOperationNetworkTimeoutNotPrimaryErrorOperationFailurePyMongoErrorWaitQueueTimeoutError_CertificateError)HelloHelloCompat)_handle_reauth)_create_lock)_CONNECTION_LOGGER_ConnectionStatusMessage
_debug_log _verbose_connection_error_reason)ConnectionCheckOutFailedReasonConnectionClosedReason_EventListeners)commandreceive_message)ReadPreference)_add_to_command)SERVER_TYPE)SocketChecker)HAS_SNISSLError)CodecOptions)ObjectId)MongoCredential_AuthContext)ClientSession)CompressionSettingsSnappyContextZlibContextZstdContext)
DriverInfo)_OpMsg_OpReply)MongoClient_MongoClientErrorHandler)
SSLContext_sslConn)ReadConcern)_ServerMode)	ServerApi)ClusterTime_Address_CollationIn)WriteConcern)F_GETFDF_SETFD
FD_CLOEXECfcntlc                T    t        | t              }t        | t        |t        z         y)z8Set the close-on-exec flag on the given file descriptor.N)rW   rT   rU   rV   )fdflagss     L/var/www/highfloat_scraper/venv/lib/python3.12/site-packages/pymongo/pool.py_set_non_inheritable_non_atomicr\   u   s    b'"b'5:-.    c                     y)z6Dummy function for platforms that don't provide fcntl.N )rY   s    r[   r\   r\   ~   s    r]   x   
   	   win32c                z    	 t        j                  | |      \  }}t        |      S # t        t        f$ r |cY S w xY wN)winregQueryValueExintOSError
ValueError)keynamedefaultvalue_s        r[   _queryrp      sB    	**35HE1u:$ 	 N	s   #& ::z2SYSTEM\CurrentControlSet\Services\Tcpip\ParametersKeepAliveTimei m KeepAliveInterval  c                    t        t        t        dz        }t        t        t        dz        }|t        k  s	|t        k  r$| j                  t        j                  d||f       y y )Nrs      )min_WINDOWS_TCP_IDLE_MS_MAX_TCP_KEEPIDLE_WINDOWS_TCP_INTERVAL_MS_MAX_TCP_KEEPINTVLioctlsocketSIO_KEEPALIVE_VALS)sockidle_msinterval_mss      r[   _set_keepalive_timesr      sZ    *,=,DE24F4MN))[;S-SJJv001g{2KL .Tr]   c                    t        t        |      rYt        t        |      }	 | j                  t        j                  |      }||kD  r"| j                  t        j                  ||       y y y # t        $ r Y y w xY wre   )hasattrr|   getattr
getsockoptIPPROTO_TCP
setsockoptri   )r~   
tcp_option	max_valuesockoptrm   s        r[   _set_tcp_optionr      sq    6:&fj1G //&*<*<gFY&OOF$6$6K ' '  s   AA+ +	A76A7c                j    t        | dt               t        | dt               t        | dt               y )NTCP_KEEPIDLETCP_KEEPINTVLTCP_KEEPCNT)r   rx   rz   _MAX_TCP_KEEPCNT)r~   s    r[   r   r      s)    n.?@o/ABm-=>r]   driverPyMongo)rl   versiondict[str, Any]	_METADATAlinux)typerl   architecturer   osdarwin -ru      java   PyPy.z(Python %s)platformz(%s)z/.dockerenvKUBERNETES_SERVICE_HOSTdocker
kubernetesc                     i } t        t              j                         r	t        | d<   t	        j
                  t              r	t        | d<   | S )zReturns the runtime and orchestrator of a container.
    If neither value is present, the metadata client.env.container field will be omitted.runtimeorchestrator)r   DOCKER_ENV_PATHexistsRUNTIME_NAME_DOCKERr   getenvENV_VAR_K8SORCHESTRATOR_NAME_K8S)	containers    r[   get_container_env_infor     s@     IO##%2	)	yy$9	.!r]   c                     t        j                  d      ryt        j                  d      } | r| j                  d      S y)NAWS_LAMBDA_RUNTIME_APITAWS_EXECUTION_ENVAWS_Lambda_F)r   r   
startswith)envs    r[   
_is_lambdar     s6    	yy)*
))'
(C
~~m,,r]   c                 >    t        t        j                  d            S )NFUNCTIONS_WORKER_RUNTIMEboolr   r   r_   r]   r[   _is_azure_funcr   %  s    		4566r]   c                 l    t        t        j                  d      xs t        j                  d            S )N	K_SERVICEFUNCTION_NAMEr   r_   r]   r[   _is_gcp_funcr   )  s$    		+&D"))O*DEEr]   c                 >    t        t        j                  d            S )NVERCELr   r_   r]   r[   
_is_vercelr   -  s    		(#$$r]   c                 ^    t               xs" t               xs t               xs
 t               S re   )r   r   r   r   r_   r]   r[   _is_faasr   1  s     <M>+M|~MMr]   c                h    t        j                  |       }|sy	 t        |      S # t        $ r Y yw xY w)zMLike os.getenv but returns an int, or None if the value is missing/malformed.N)r   r   rh   rj   )rk   vals     r[   _getenv_intr   5  s5    
))C.C3x s   
% 	11c                 8   i } t               }|r|| d<   t               t               t               t	               fj                  d      dk7  r| S t               r5d| d<   t        j                  d      }|r|| d<   t        d      }||| d	<   | S t               rd
| d<   | S t               rGd| d<   t        j                  d      }|r|| d<   t        d      }||| d	<   t        d      }||| d<   | S t	               r!d| d<   t        j                  d      }|r|| d<   | S )Nr   Tru   z
aws.lambdarl   
AWS_REGIONregionAWS_LAMBDA_FUNCTION_MEMORY_SIZE	memory_mbz
azure.funczgcp.funcFUNCTION_REGIONFUNCTION_MEMORY_MBFUNCTION_TIMEOUT_SECtimeout_secvercelVERCEL_REGION)	r   r   r   r   r   countr   r   r   )r   r   r   r   r   s        r[   _metadata_envr   @  s@   C&(I$Kn&
EKKDQUVV
|"F<("CM AB	 (C& J% 
	"F" J! 
 F,-"CM 45	 (C!"89"!,C J 
F?+"CMJr]   i   c                ~   t        t        j                  |             t        k  ry| j	                  di       j	                  d      }|rd|i| d<   t        t        j                  |             t        k  ry| j	                  di       j	                  d      }|rd|i| d<   t        t        j                  |             t        k  ry| j                  dd       t        t        j                  |             }|t        k  ry|t        z
  }| j	                  dd      }|r|d|  }|r|| d<   y| j                  dd       y)zPerform metadata truncation.Nr   rl   r   r   r    )lenbsonencode_MAX_METADATA_SIZEgetpop)metadataenv_nameos_typeencoded_sizeoverflowplats         r[   _truncate_metadatar   i  s   
4;;x !%77||E2&**62H!8,
4;;x !%77ll4$((0G '*
4;;x !%77LLt{{8,-L))00H<<
B'DJhY#Z&r]   fooidnac                   | \  }}|	d|||fz  }n| d| }|r||z   }d|vr|t        |      z  }t        |t        j                        rt	        |      |t        |t
              rdt        |      v rt	        |      |t        |      |)z9Convert a socket.error to ConnectionFailure and raise it.z	%s:%d: %s: zconfigured timeouts	timed out)format_timeout_details
isinstancer|   timeoutr$   r<   strr   )addresserror
msg_prefixtimeout_detailshostportmsgs          r[   _raise_connection_failurer     s     JD$T4//b 3C'%o66%(S!u,	E8	$E
)B
 S!u,C e+r]   c                Z    |r|t        j                         z
  nd }| j                  |      S re   )time	monotonicwait)	conditiondeadliner   s      r[   
_cond_waitr     s&    -5h))4G>>'""r]   PoolOptionsc                    i }t        j                         }| j                  }| j                  }|r|dz  |d<   |r
|s|dz  |d<   |r|dz  |d<   |S )Nrs   	timeoutMSsocketTimeoutMSconnectTimeoutMS)r   get_timeoutsocket_timeoutconnect_timeout)optionsdetailsr   r  r  s        r[   _get_timeout_detailsr    si    G!G++N--O&~g%3d%:!"&5&<"#Nr]   c                b    d}| r*|dz  }dD ]  }|| v s|d| d| |    dz  } |d d }|dz  }|S )	Nr   z (configured timeouts:)r  r   r  r   r   zms,r   )r_   )r  resultr   s      r[   r   r     sf    F**K 	?G'!AgYb)9(:#>>	? #Mr]   c                     e Zd ZdZdZeeeddedddddde	ddddf	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ
edd       Zedd       Zedd	       Zedd
       Zedd       Zedd       Zed d       Zed!d       Zed!d       Zed d       Zed"d       Zedd       Zed#d       Zed$d       Zed%d       Zed&d       Zedd       Zed'd       Zed(d       Zy))r   aY  Read only connection pool options for a MongoClient.

    Should not be instantiated directly by application developers. Access
    a client's pool options via
    :attr:`~pymongo.client_options.ClientOptions.pool_options` instead::

      pool_opts = client.options.pool_options
      pool_opts.max_pool_size
      pool_opts.min_pool_size

    )__max_pool_size__min_pool_size__max_idle_time_seconds__connect_timeout__socket_timeout__wait_queue_timeout__ssl_context__tls_allow_invalid_hostnames__event_listeners	__appname__driver
__metadata__compression_settings__max_connecting__pause_enabled__server_api__load_balanced__credentialsNFTc                8   || _         || _        || _        || _        || _        || _        || _        || _        |	| _        |
| _	        || _
        || _        || _        || _        || _        || _        || _        t#        j$                  t&              | _        |
rd|
i| j(                  d<   |r|j*                  r6dj-                  t&        d   d   |j*                        | j(                  d   d<   |j.                  r6dj-                  t&        d   d   |j.                        | j(                  d   d<   |j0                  r0dj-                  t&        d   |j0                        | j(                  d<   t3               }|r|| j(                  d<   t5        | j(                         y )Nrl   applicationz{}|{}r   r   r   r   )_PoolOptions__max_pool_size_PoolOptions__min_pool_size#_PoolOptions__max_idle_time_seconds_PoolOptions__connect_timeout_PoolOptions__socket_timeout _PoolOptions__wait_queue_timeout_PoolOptions__ssl_context)_PoolOptions__tls_allow_invalid_hostnames_PoolOptions__event_listeners_PoolOptions__appname_PoolOptions__driver"_PoolOptions__compression_settings_PoolOptions__max_connecting_PoolOptions__pause_enabled_PoolOptions__server_api_PoolOptions__load_balanced_PoolOptions__credentialscopydeepcopyr   _PoolOptions__metadatarl   formatr   r   r   r   )selfmax_pool_sizemin_pool_sizemax_idle_time_secondsr  r  wait_queue_timeoutssl_contexttls_allow_invalid_hostnamesevent_listenersappnamer   compression_settingsmax_connectingpause_enabled
server_apiload_balancedcredentialsr   s                      r[   __init__zPoolOptions.__init__  sw   (  -,'<$!0 .$6!(-H*!0 &:# .,&,(--	2.4g->DOOM* {{4;NNh'/KK5)&1 ~~7>~~h'	2NN8))4 .5nnYz=RTZTcTc.d
+o%(DOOE"4??+r]   c                    | j                   S )z;A :class:`~pymongo.auth.MongoCredentials` instance or None.)r1  r6  s    r[   _credentialszPoolOptions._credentials3       !!!r]   c                   i }| j                   t        k7  r| j                   |d<   | j                  t        k7  r| j                  |d<   | j                  t
        k7  r | j                  J | j                  dz  |d<   | j                  t        k7  r | j                  J | j                  dz  |d<   | j                  t        k7  r| j                  |d<   |S )zqThe non-default options this pool was created with.

        Added for CMAP's :class:`PoolCreatedEvent`.
        maxPoolSizeminPoolSizers   maxIdleTimeMSwaitQueueTimeoutMSmaxConnecting)
r!  r   r"  r   r#  r   r&  r   r-  r   )r6  optss     r[   non_default_optionszPoolOptions.non_default_options8  s     =0"&"6"6D=0"&"6"6D''+<<//;;;$($@$@4$GD!$$(::,,888)-)B)BT)ID%&  N2$($9$9D!r]   c                    | j                   S )aQ  The maximum allowable number of concurrent connections to each
        connected server. Requests to a server will block if there are
        `maxPoolSize` outstanding connections to the requested server.
        Defaults to 100. Cannot be 0.

        When a server's pool has reached `max_pool_size`, operations for that
        server block waiting for a socket to be returned to the pool. If
        ``waitQueueTimeoutMS`` is set, a blocked operation will raise
        :exc:`~pymongo.errors.ConnectionFailure` after a timeout.
        By default ``waitQueueTimeoutMS`` is not set.
        )r!  rG  s    r[   r7  zPoolOptions.max_pool_sizeM  s     ###r]   c                    | j                   S )zThe minimum required number of concurrent connections that the pool
        will maintain to each connected server. Default is 0.
        )r"  rG  s    r[   r8  zPoolOptions.min_pool_size\  s    
 ###r]   c                    | j                   S )zgThe maximum number of concurrent connection creation attempts per
        pool. Defaults to 2.
        )r-  rG  s    r[   r@  zPoolOptions.max_connectingc  s    
 $$$r]   c                    | j                   S re   )r.  rG  s    r[   rA  zPoolOptions.pause_enabledj  s    ###r]   c                    | j                   S )zThe maximum number of seconds that a connection can remain
        idle in the pool before being removed and replaced. Defaults to
        `None` (no limit).
        )r#  rG  s    r[   r9  z!PoolOptions.max_idle_time_secondsn  s     +++r]   c                    | j                   S )z>How long a connection can take to be opened before timing out.)r$  rG  s    r[   r  zPoolOptions.connect_timeoutv       %%%r]   c                    | j                   S )zBHow long a send or receive on a socket can take before timing out.)r%  rG  s    r[   r  zPoolOptions.socket_timeout{  s     $$$r]   c                    | j                   S )zhHow long a thread will wait for a socket from the pool if the pool
        has no free sockets.
        )r&  rG  s    r[   r:  zPoolOptions.wait_queue_timeout  s    
 (((r]   c                    | j                   S )zAn SSLContext instance or None.)r'  rG  s    r[   _ssl_contextzPoolOptions._ssl_context  rI  r]   c                    | j                   S )z If True skip ssl.match_hostname.)r(  rG  s    r[   r<  z'PoolOptions.tls_allow_invalid_hostnames  s     111r]   c                    | j                   S )z2An instance of pymongo.monitoring._EventListeners.)r)  rG  s    r[   _event_listenerszPoolOptions._event_listeners  rX  r]   c                    | j                   S )zAThe application name, for sending with hello in server handshake.)r*  rG  s    r[   r>  zPoolOptions.appname  s     ~~r]   c                    | j                   S )z=Driver name and version, for sending with hello in handshake.)r+  rG  s    r[   r   zPoolOptions.driver  s     }}r]   c                    | j                   S re   )r,  rG  s    r[   _compression_settingsz!PoolOptions._compression_settings  s    ***r]   c                6    | j                   j                         S )zCA dict of metadata about the application, driver, os, and platform.)r4  r2  rG  s    r[   r   zPoolOptions.metadata  s     ##%%r]   c                    | j                   S )z'A pymongo.server_api.ServerApi or None.)r/  rG  s    r[   rB  zPoolOptions.server_api  s        r]   c                    | j                   S )z6True if this Pool is configured in load balanced mode.)r0  rG  s    r[   rC  zPoolOptions.load_balanced  s     ###r]   )"r7  rh   r8  rh   r9  Optional[int]r  Optional[float]r  rh  r:  rg  r;  Optional[SSLContext]r<  r   r=  Optional[_EventListeners]r>  Optional[str]r   Optional[DriverInfo]r?  Optional[CompressionSettings]r@  rh   rA  r   rB  Optional[ServerApi]rC  Optional[bool]rD  Optional[MongoCredential])returnrp  rq  r   rq  floatrq  rh   rq  r   )rq  rg  )rq  rh  )rq  ri  )rq  rj  )rq  rk  )rq  rl  )rq  rm  )rq  rn  )rq  ro  )__name__
__module____qualname____doc__	__slots__r   r   r   r   r   rE  propertyrH  rQ  r7  r8  r@  rA  r9  r  r  r:  r\  r<  r_  r>  r   rc  r   rB  rC  r_   r]   r[   r   r     s   
I. +*/@+/*.,>,0,159!%'+>B,"*.(,15%C,C, C,  -	C,
 )C, (C, *C, *C, &*C, 3C, C, %C, <C, C, C,  (!C," &#C,$ /%C,J " "  ( $ $ $ $ % % $ $ , , & & % % ) ) " " 2 2 & &     + + & & ! ! $ $r]   c                  .    e Zd ZddZddZedd       Zy)_CancellationContextc                    d| _         y NF
_cancelledrG  s    r[   rE  z_CancellationContext.__init__  s	    r]   c                    d| _         y)zCancel this context.TNr  rG  s    r[   cancelz_CancellationContext.cancel  s	    r]   c                    | j                   S )zWas cancel called?r  rG  s    r[   	cancelledz_CancellationContext.cancelled  s     r]   Nrq  Nonerv  )rw  rx  ry  rE  r  r|  r  r_   r]   r[   r~  r~    s        r]   r~  c                     e Zd ZdZ	 	 	 	 	 	 	 	 d$dZd%dZ	 	 	 	 	 	 d&dZd'dZd'dZd'dZ	d(dZ
d)d	Z	 	 	 	 	 	 	 	 d*d
Zd(dZeej                   eddddddddddddf	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d+d       Zd,dZd-dZd.dZd/dZ	 	 	 	 	 	 	 	 d0dZd1d2dZ	 	 	 	 	 	 d3dZd4dZd'dZd5dZ	 	 	 	 	 	 	 	 d6dZd7dZd'dZd8dZ d9dZ!d:dZ"d;d Z#d;d!Z$d<d"Z%d=d#Z&y)>
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
    c                   t        j                  |      | _        || _        || _        || _        d| _        t        j                         | _	        d| _
        d| _        t        | _        t        | _        t         | _        t$        | _        d| _        d| _        d| _        d| _        |j0                  j2                  | _        |j6                  | _        |j0                  j8                  | _        d | _        t?               | _         d | _!        d | _"        d | _#        |jH                  | _%        | jJ                  jM                         | _'        d| _(        tS               | _*        |j0                  | _        d| _+        d | _,        d | _-        d| _.        d| _/        d| _0        | j0                  jb                  | _2        d| _3        |jh                  | _4        t        j                         | _5        y )NFg        )6weakrefrefpool_refconnr   id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_enabledrP  r_  	listenersenabled_for_cmaprc  r?  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)r6  r  poolr   r  s        r[   rE  zConnection.__init__  s     D)	!%!1#( !& 0* 0$8!!&##33 $ 5 5$(II$C$C!Y] -:_045904 --335
4H4JII	"'.237!  " II44//!^^-r]   c                h    || j                   k(  ry|| _         | j                  j                  |       y)z?Cache last timeout to avoid duplicate calls to conn.settimeout.N)r  r  
settimeout)r6  r   s     r[   set_conn_timeoutzConnection.set_conn_timeout  s-    d'''#		W%r]   c                   t        j                         }|2| j                  s%| j                  | j                  j
                         y t        j                         }|| j                  }||z
  }|dk  rIt        | j                        }t        |      }d|dd|dd| }t        |dd|dd| j                        |t        |dz        |d	<   | j                  |       |S )
Nr   z5operation would exceed time limit, remaining timeout:z.5fz <= network round trip time:r   2   okerrmsgcoders   	maxTimeMS)r   	remainingr  r  rP  r  get_rttr  r  r   r"   r  rh   )	r6  clientcmdr   rttmax_time_msr   	formattedr  s	            r[   apply_timeoutzConnection.apply_timeout  s     //#?$$%%dii&>&>?mmo;""Cm?2499=O.?ILWUXMYuvyz}u~~  AJ  @K  LF"FB7%%	  ?";#56Cg&r]   c                .    d| _         | j                  rJ y NT)r  r  rG  s    r[   pin_txnzConnection.pin_txn#  s    %%%%%r]   c                .    d| _         | j                  rJ y r  )r  r  rG  s    r[   
pin_cursorzConnection.pin_cursor'  s    !??""?r]   c                    | j                         }|r|j                  |        y | j                  t        j                         y re   )r  checkin
close_connr3   STALE)r6  r  s     r[   unpinzConnection.unpin+  s/    }}LLOO2889r]   c                    | j                   j                  s"| j                  s| j                   j                  rd| _        t
        j                  diS t
        j                  dddiS )NTru   helloOk)rP  rB  r  rC  r  r+   CMD
LEGACY_CMDrG  s    r[   	hello_cmdzConnection.hello_cmd2  sO     994==DII4K4K"&DOOQ''**Ay$??r]   c                (    | j                  d d d       S re   )_hellorG  s    r[   hellozConnection.hello;  s    {{4t,,r]   c                   | j                         }| j                   }d}|rad| _        | j                  j                  |d<   | j                  r| j                  j
                  |d<   | j                  j                  rbd|d<   n\|Z||d<   |J t        |dz        |d<   d}| j                  j                  r(| j                  | j                  j                  |z          |s|||d	<   | j                  j                  }|r~|j                  d
k(  r+|j                  r|j                  dz   |j                  z   |d<   t        j                  j!                  || j"                        }|r|j%                         }	|	|	|d<   nd }|rt'        j(                         }
| j+                  d|d|      }|rt'        j(                         
z
  | _        t/        ||      }|j0                  | _        |j2                  | _        |j4                  | _        |j6                  | _        |j8                  | _        |j:                  d uxr |j<                  | _        |j:                  | _        |j@                  | _         |jB                  tD        jF                  tD        jH                  tD        jJ                  tD        jL                  tD        jN                  fv | _(        |jB                  tD        jR                  k(  | _*        |jB                  tD        jV                  k(  | _,        |r8| j                  r,| j                  j[                  |j
                        }|| _.        d| _/        |j`                  | _1        |r|jd                  | _3        |r(|ji                  |       |jk                         r|| _6        | j                  j                  rR|jn                  stq        d      |jn                  | _7        | jr                  ju                  | jn                        | _;        |S )NFTr  compressionloadBalancedtopologyVersionrs   maxAwaitTimeMSz$clusterTimeDEFAULTr   saslSupportedMechs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  rP  r   r?  compressorsrC  rh   r  r  rH  	mechanismusernamesourcer   r@   from_credentialsr   speculate_commandr   r   r5   r  r*   r  r  r  r  r  logical_session_timeout_minutesis_readabler  r  server_typer9   	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  r   r  )r6  cluster_timetopology_versionheartbeat_frequencyr  performing_handshaker  credsr  speculative_authenticatestartdocr  ctxs                 r[   r  zConnection._hello>  s    nn#'#;#;;	'+D$ II..CM((%)%>%>%J%JM"yy&&&*N#)%5C!"&222$'(;d(B$CC !Iyy((%%dii&?&?BU&UV#(@".C		&&)+,1LL3,>,O()((99%NH+3+E+E+G(+75MC12HNN$Ell7CylY#~~/%7DcY/ ,, % 6 6"00 % 6 6$)$>$>!11=S%BSBS 	 ?D>c>c,((!!##!!-
 
 #..+2H2HH**k.@.@@D$=$=++CCEDUDUVC'*D$"$)$7$7!$)$>$>D!##E*++- (99""##(A  $..DO"mm//@DOr]   c                    | j                  d       }|j                  | _        |j                         }|d   }t        j                  || j
                         |S Nr   )r6   r  unpack_responser   _check_command_responser  )r6  replyunpacked_docsresponse_docs       r[   _next_replyzConnection._next_reply  sT    $$T*!..--/$Q'''d6K6KLr]   TNFc                   | j                  ||       t        ||      }t        |t              st	        |      }||j
                  s|
t        d      | j                  |       |r|j                  ||||        | j                  |||       |r| j                  nd}t        |xr |j
                         }| j                  r| j                  |       	 t        | ||| j                  ||||||| j                   || j"                  ||	|
| j$                  | j                  ||||      S # t&        t(        f$ r  t*        $ r}| j-                  |       Y d}~yd}~ww xY 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.)parse_write_concern_error	collationcompression_ctx
use_op_msgunacknowledgeduser_fieldsr  write_concern)validate_sessionr   r   r   dictacknowledgedr   add_server_api	_apply_tosend_cluster_timer  r   r  _raise_if_not_writabler5   r  r   r  r  r&   r%   BaseExceptionr   )r6  dbnamespecread_preferencecodec_optionscheckallowable_errorsread_concernr  r  r  sessionr  retryable_writer  r  r  r  r  r   s                       r[   r5   zConnection.command  si   R 	fg.1'=I $.:D%)C)CyGX$%Z[[D!dO_dKtWf5&4DNN$	mNM4N4N0NO''7	2 ""*C# $ 8 8..-' /+- 0 !/2 	 	2**511	2s   AD* *EEEc                    | j                   )|| j                   kD  rt        d|| j                   fz        	 | j                  j                  |       y# t        $ r}| j                  |       Y d}~yd}~ww xY 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  sendallr  r   )r6  messagemax_doc_sizer   s       r[   send_messagezConnection.send_message  s|    
 )lT=O=O.O"?BNPTPbPbAcd 
	2IIg& 	2**511	2s   A 	A7A22A7c                    	 t        | || j                        S # t        $ r}| j                  |       Y d}~yd}~ww xY w)zzReceive a raw BSON message or raise ConnectionFailure.

        If any exception is raised, the socket is closed.
        N)r6   r  r  r   )r6  
request_idr   s      r[   r6   zConnection.receive_message  s=    
	2"4T5J5JKK 	2**511	2s    	=8=c                B    |r| j                   st        ddddd      yy)z^Raise NotPrimaryError on unacknowledged write if this socket is not
        writable.
        znot primaryr   i{'  r  N)r  r%   )r6  r  s     r[   r  z!Connection._raise_if_not_writable  s+     $"2"2!-]\a1bcc #3>r]   c                J    | j                  d       | j                  ||       y)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*  )r6  r   r)  s      r[   unack_writezConnection.unack_write  s"     	##D)#|,r]   c                    | j                  |d       | j                  |      }|j                  |      }t        j                  || 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*  r6   command_responser   r  r  )r6  r,  r   r   r	  r  s         r[   write_commandzConnection.write_command$  sQ     	#q!$$Z0''6 	''0E0EFr]   c           	        |r| j                   rd| _        d| _        | j                  s| j                  j                  }|rt        j                  || |       d| _        | j                  r| j                  J t        j                         | j                  z
  }| j                  j                  | j                  | j                  |       t        j                   t"        j$                        rSt'        t        | j(                  t*        j,                  | j                  d   | j                  d   | j                  |       yyyy)zhAuthenticate to the server if needed.

        Can raise ConnectionFailure or OperationFailure.
        NF)reauthenticateTr   ru   clientIdr(  
serverHost
serverPortdriverConnectionId
durationMS)r  r  r  rP  rH  r   authenticater  r  r   r   r  publish_connection_readyr   r  r.   isEnabledForloggingDEBUGr0   r  r/   
CONN_READY)r6  r4  r   durations       r[   r;  zConnection.authenticate6  s     '' $DJzzII**E!!%nMDJ$$~~111>>+d.@.@@77dggxX%227==A*!% 8 C C#'<<?#'<<?+/77#+ B	 % r]   c                <    |r|j                   |urt        d      yy)zValidate this session before use with client.

        Raises error if the client is not the one that created the session.
        z9Can only use session with the MongoClient that started itN)_clientr#   )r6  r  r$  s      r[   r  zConnection.validate_sessionV  s)     f,&'bcc - r]   c                   | j                   ry| j                          |r| j                  r| j                  J | j                  j	                  | j
                  | j                  |       t        j                  t        j                        r]t        t        | j                  t        j                  | j
                  d   | j
                  d   | j                  t        |      |       yyyy)z$Close this connection with a reason.Nr   ru   r6  r(  r7  r8  r9  reasonr   )r  _close_connr  r  publish_connection_closedr   r  r.   r=  r>  r?  r0   r  r/   CONN_CLOSEDr1   )r6  rF  s     r[   r  zConnection.close_conna  s    ;;d++>>---NN44T\\477FS!..w}}=&!__4@@#||A#||A'+ww;FC 	 > ,6r]   c                    | j                   ryd| _         | j                  j                          	 | j                  j	                          y# t
        $ r Y yw xY w)zClose this connection.NT)r  r  r  r  close	ExceptionrG  s    r[   rG  zConnection._close_connu  sJ    ;;""$	IIOO 		s   A 	AAc                L    | j                   j                  | j                        S )z?Return True if we know socket has been closed, False otherwise.)r  socket_closedr  rG  s    r[   conn_closedzConnection.conn_closed  s    ""00;;r]   c                .    |r|j                  ||       yy)zAdd $clusterTime.N)_send_cluster_time)r6  r5   r$  r  s       r[   r  zConnection.send_cluster_time  s     %%gw7 r]   c                r    | j                   j                  r!t        || j                   j                         yy)zAdd server_api parameters.N)rP  rB  r8   )r6  r5   s     r[   r  zConnection.add_server_api  s(    99GTYY%9%9:  r]   c                6    t        j                         | _        y re   r   r   r  rG  s    r[   update_last_checkin_timez#Connection.update_last_checkin_time  s    !%!1r]   c                    || _         y re   )r  )r6  r  s     r[   update_is_writablezConnection.update_is_writable  s
    &r]   c                D    t        j                         | j                  z
  S )z9Seconds since this socket was last checked into its pool.rT  rG  s    r[   idle_time_secondszConnection.idle_time_seconds  s    ~~$"8"888r]   c                    | j                   rd }nt        j                  }| j                  |       t	        |t
        t        t        f      r.t        | j                        }t        | j                  ||       y  )Nr   )r  r3   ERRORr  r   IOErrorri   r<   r  rP  r   r   )r6  r   rF  r  s       r[   r   z$Connection._raise_connection_failure  sY      ::F+11Fegw9:*4995G%dllE7Sr]   c                4    | j                   |j                   k(  S re   )r  r6  others     r[   __eq__zConnection.__eq__  s    yyEJJ&&r]   c                    | |k(   S re   r_   r_  s     r[   __ne__zConnection.__ne__  s    5=  r]   c                ,    t        | j                        S re   )hashr  rG  s    r[   __hash__zConnection.__hash__  s    DIIr]   c                    dj                  t        | j                        | j                  xr dxs dt	        |             S )NzConnection({}){} at {}z CLOSEDr   )r5  reprr  r  r  rG  s    r[   __repr__zConnection.__repr__  s8    '..OKK%I+tH
 	
r]   )r  Union[socket.socket, _sslConn]r  Poolr   ztuple[str, int]r  rh   )r   rh  rq  r  )r  rI   r  z"Optional[MutableMapping[str, Any]]rq  rh  r  rr  )rq  Hello[dict[str, Any]])r  zOptional[ClusterTime]r  zOptional[Any]r  rg  rq  rl  )"r  r   r  MutableMapping[str, Any]r  rN   r   r=   r!  r   r"  z#Optional[Sequence[Union[str, int]]]r#  zOptional[ReadConcern]r  zOptional[WriteConcern]r  r   r  zOptional[_CollationIn]r$  Optional[ClientSession]r  Optional[MongoClient]r%  r   r  r   r  zOptional[Mapping[str, Any]]r  r   rq  r   )r(  bytesr)  rh   rq  r  )r,  rg  rq  zUnion[_OpReply, _OpMsg])r  r   rq  r  )r   rp  r)  rh   rq  r  )r,  rh   r   rp  r   r=   rq  r   )F)r4  r   rq  r  )r  ro  r$  rn  rq  r  )rF  rk  rq  r  rv  )r5   rm  r$  rn  r  ro  rq  r  )r5   rm  rq  r  )r  r   rq  r  rs  )r   r  rq  r
   )r`  r   rq  r   ru  )rq  r   )'rw  rx  ry  rz  rE  r  r  r  r  r  r  r  r  r  r,   r7   PRIMARYr   r5   r*  r6   r  r/  r2  r;  r  r  rG  rO  r  r  rU  rW  rY  r   ra  rc  rf  ri  r_   r]   r[   r  r    si   0.20.:>0.IX0.^a0.d&!(J	>&#:@-U+U (U +	U
 
Un 
 (6'='=&;@D.204*/,0+/(, %#37 %#W2W2 'W2 %	W2
 $W2 W2 >W2 ,W2 .W2 $(W2 *W2 )W2 &W2 W2 W2  1!W2" #W2$ 
%W2 W2r2 2d	-$):F	$@	d+	d6M	d		d(<8)8 )8 &	8
 
8;
2'98'!
r]   r  c           
        | \  }}|j                  d      rkt        t        d      st        d      t        j                  t        j                        }t        |j                                	 |j                  |       |S t        j                  }t        j                  r|dk7  rt        j                  }d}t        j                  |||t        j                        D ]  }|\  }}	}
}}	 t        j                  ||	t        t        dd      z  |
      }t        |j                                	 |j!                  t        j"                  t        j$                  d       t'        j(                         }||j*                  }n|dk  rt        j,                  d	      |j/                  |       |j!                  t        j0                  t        j2                  d
       t5        |       |j                  |       |c S  ||t        d      # t        $ r |j                           w xY w# t        $ r t        j                  ||	|
      }Y 7w xY w# t        $ r}|}|j                          Y d}~d}~ww xY w)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   ru   r   Tzgetaddrinfo failed)endswithr   r|   r    rs  r\   filenoconnectri   rK  AF_INEThas_ipv6	AF_UNSPECgetaddrinfoSOCK_STREAMr   r   r   TCP_NODELAYr   r  r  r   r  
SOL_SOCKETSO_KEEPALIVEr   )r   r  r   r   r~   familyerrresafsocktypeprotodummysar   es                  r[   _create_connectionr    s    JD$ }}Wvy)#$STT}}V^^,'6	LLK ^^F4;.!!
C!!$ff6H6HI ),&HeUB	6==XPQ0R%RTYZD 	(6	OOF..0B0BAFoo'G!11Ann[11OOG$OOF--v/B/BDI &LLK3< 	 *++c  	JJL	&  	6 ==Xu5D	6&  	CJJLL	s7   /H ,)H)/C	IH&) II	I6I11I6c                   t        | |      }|j                  }||j                  |j                         |S | d   }	 t        r|j                  ||      }n|j                  |      }|j                  r>|j                  s2|j                  s&	 t        j                   j#                         |       j                  |j                         |S # t        $ r |j                           t        t        f$ r4}|j                          t        |      }t        | |d|       Y d}~d}~ww xY w# t        $ r j                           w xY w)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_hostnamezSSL handshake failed: r[  )hostname)r  r\  r  r  r;   wrap_socketr)   rK  ri   r<   r  r   verify_modecheck_hostnamer<  sslmatch_hostnamegetpeercert)r   r  r~   r;  r   ssl_sockexcr  s           r[   _configured_socketr    s;    gw/D&&K../1:Dc "..tT.JH"..t4H 	**33	x335E
 ../O1  

 	X c

 'w/!'30HZabbc ! 	NN	s#   +C %D/ (D,8*D''D,/E
c                      e Zd ZdZy)_PoolClosedErrorzZInternal error raised when a thread tries to get a connection from a
    closed pool.
    N)rw  rx  ry  rz  r_   r]   r[   r  r  D  s    r]   r  c                  4    e Zd ZddZddZd	dZd
dZddZy)_PoolGenerationc                N    t        j                  t              | _        d| _        y r  )collectionsdefaultdictrh   _generations_generationrG  s    r[   rE  z_PoolGeneration.__init__K  s    1<1H1H1Mr]   c                <    || j                   S | j                  |   S )z,Get the generation for the given service_id.r  r  r6  r  s     r[   r   z_PoolGeneration.getQ  s%    ###  ,,r]   c                    | j                   S )z"Get the Pool's overall generation.)r  rG  s    r[   r  z_PoolGeneration.get_overallW  s    r]   c                    | xj                   dz  c_         |)| j                  D ]  }| j                  |xx   dz  cc<    y| j                  |xx   dz  cc<   y)z2Increment the generation for the given service_id.ru   Nr  r  s     r[   incz_PoolGeneration.inc[  s\    A"// 3
!!*-2-3 j)Q.)r]   c                *    || j                  |      k7  S )z?Return if the given generation for a given service_id is stale.)r   r6  r  r  s      r[   stalez_PoolGeneration.staled  s    dhhz***r]   Nr  )r  Optional[ObjectId]rq  rh   ru  )r  r  rq  r  r  rh   r  r  rq  r   )rw  rx  ry  rE  r   r  r  r  r_   r]   r[   r  r  J  s    - /+r]   r  c                      e Zd ZdZdZdZy)	PoolStateru   r   r   N)rw  rx  ry  PAUSEDREADYCLOSEDr_   r]   r[   r  r  i  s    FEFr]   r  c                     e Zd Z	 	 d	 	 	 	 	 	 	 ddZddZedd       Z	 	 	 d	 	 	 	 	 	 	 	 	 ddZddZ	 d	 	 	 	 	 ddZ	ddZ
dd	Zdd
ZddZdd dZej                   dd!d       Zd"dZ	 d	 	 	 	 	 d#dZd$dZd%dZd&dZddZy)'rk  Nc                   |j                   rt        j                  | _        nt        j                  | _        d| _        t        j                         | _        t               | _
        t               | _        d| _        d| _        d| _        t!               | _        t%        j&                         | _        || _        || _        || _        | j.                  xr: | j,                  j0                  duxr  | j,                  j0                  j2                  | _        t5        j6                  | j                        | _        d| _        | j,                  j<                  | _        | j<                  st?        d      | _        t5        j6                  | j                        | _         | j,                  jB                  | _"        d| _#        || _$        | j2                  r| j,                  j0                  J | j,                  j0                  jK                  | j*                  | j,                  jL                         tO        jP                  tR        jT                        r[tW        tN        f| jH                  tX        jZ                  | j*                  d   | j*                  d   d| j,                  jL                   d| _.        t               | _/        d| _0        d| _1        y)z
        :param address: a (hostname, port) tuple
        :param options: a PoolOptions instance
        :param handshake: whether to call hello for each new Connection
        ru   r   Ninfr6  r(  r7  r8  )2rA  r  r  stater  _check_interval_secondsr  dequeconnssetactive_contextsr-   lockactive_socketsnext_connection_idr  r  r  r   getpidpidr   rP  	handshaker_  r  	threading	Condition	size_condrequestsr7  rt  _max_connecting_condr@  _max_connecting_pendingr  publish_pool_createdrQ  r.   r=  r>  r?  r0   r/   POOL_CREATEDoperation_count_Pool__pinned_socketsncursorsntxns)r6  r   r  r  	client_ids        r[   rE  zPool.__init__r  s%      "))DJ"DJ ()$ )4(9(9(;
:=% N	"#+/
 #$99;	" NN <		**$6<		**;; 	 #,,TYY7!YY44!!!&uD %.$7$7		$B!#yy77#  99--999II&&;;dii;; "..w}}=&!__4AA#||A#||A ii33 %& 25
r]   c           	     "   | j                   5  | j                  t        j                  k7  rt        j                  | _        | j                  r| j
                  j                  J | j
                  j                  j                  | j                         t        j                  t        j                        rFt        t        | j                  t        j                   | j                  d   | j                  d          d d d        y # 1 sw Y   y xY w)Nr   ru   r  )r  r  r  r  r  rP  r_  publish_pool_readyr   r.   r=  r>  r?  r0   r  r/   
POOL_READYrG  s    r[   r  z
Pool.ready  s    YY 	zzY__,&__
((9955AAAII..AA$,,O)66w}}E".%)__$<$G$G'+||A'+||A	 	 	s   C/DDc                <    | j                   t        j                  k(  S re   )r  r  r  rG  s    r[   r  zPool.closed  s    zzY----r]   c                4   | j                   }| j                  5  | j                  r
	 d d d        y | j                  j                  r:|r8| j                  j
                  s"| j                   t        j                  c}| _         | j                  j                  |       t        j                         }| j                  |k7  r|| _        d| _        d| _        |'| j                  t!        j"                         c}| _        ntt!        j"                         }t!        j"                         }	| j                  D ]4  }
|
j$                  |k(  r|j'                  |
       $|	j'                  |
       6 |}|	| _        |rt        j(                  | _         | j*                  j-                          | j                  j-                          |r!| j.                  D ]  }|j1                           d d d        | j                  j2                  }|rD ]!  }
|
j5                  t6        j8                         # | j:                  r|J |j=                  | j>                         tA        jB                  tD        jF                        rGtI        t@        | jJ                  tL        j8                  | j>                  d   | j>                  d          y y y |t        j                  k7  r| j:                  r|J |jO                  | j>                  ||       tA        jB                  tD        jF                        rGtI        t@        | jJ                  tL        jP                  | j>                  d   | j>                  d   |       D ]!  }
|
j5                  t6        jR                         # y # 1 sw Y   xY w)Nr   ru   r  )r  interrupt_connections)r6  r(  r7  r8  	serviceId)*r  r  r  rP  rA  rC  r  r  r  r  r   r  r  r  r  r  r  r  r  appendr  r  
notify_allr  r  r_  r  r3   POOL_CLOSEDr  publish_pool_closedr   r.   r=  r>  r?  r0   r  r/   publish_pool_clearedPOOL_CLEAREDr  )r6  rK  pauser  r  	old_statenewpidsocketsdiscardkeepr  contextr  s                r[   _resetzPool._reset  s    JJ	^^  	%{{ 	%  	% yy&&59P9P(,

I4D4D%	4:HHLL$YY[Fxx6!!&'#'($!&*jj+2C2C2E#-8->->-@*5*;*;*= JJ *D*4t,D)	*
 "!
&--
%%002NN%%'$#33 %GNN$%? 	%D II..	  D 6 B BCD$$ ,,,--dll;%227==A*!% 8 D D#'<<?#'<<? B % I,,,1F1F ,,,..LL)*? / 
 &227==A*!% 8 E E#'<<?#'<<?",   > 6 < <=>K 	%  	%s   NF.NNc                    || _         | j                  5  | j                  D ]  }|j                  | j                           	 ddd       y# 1 sw Y   yxY w)zXUpdates the is_writable attribute on all sockets currently in the
        Pool.
        N)r  r  r  rW  )r6  r  _sockets      r[   rW  zPool.update_is_writable+  sO     'YY 	=:: =**4+;+;<=	= 	= 	=s   -AAc                ,    | j                  d||       y )NF)rK  r  r  r  )r6  r  r  s      r[   resetz
Pool.reset4  s     	%JNcdr]   c                *    | j                  dd       y )NF)rK  r  r  rG  s    r[   reset_without_pausezPool.reset_without_pause9  s    %u-r]   c                (    | j                  d       y )NT)rK  r  rG  s    r[   rK  z
Pool.close<  s    $r]   c                :    | j                   j                  ||      S re   )r  r  r  s      r[   stale_generationzPool.stale_generation?  s    xx~~c:..r]   c                   | j                   5  | j                  t        j                  k7  r
	 ddd       y	 ddd       | j                  j
                  | j                   5  | j                  r| j                  d   j                         | j                  j
                  kD  rz| j                  j                         }|j                  t        j                         | j                  r5| j                  d   j                         | j                  j
                  kD  rzddd       	 | j                  5  t        | j                        | j                  z   | j                  j                  k\  r
	 ddd       y| j                   | j                  j                  k\  r
	 ddd       y| xj                   dz  c_        ddd       d}	 | j"                  5  | j$                  | j&                  k\  r	 ddd       |rD| j"                  5  | xj$                  dz  c_        | j"                  j)                          ddd       | j                  5  | xj                   dz  c_        | j                  j)                          ddd       y| xj$                  dz  c_        d}ddd       | j+                         }| j                   5  | j,                  j/                         |k7  r|j                  t        j0                         	 ddd       |rD| j"                  5  | xj$                  dz  c_        | j"                  j)                          ddd       | j                  5  | xj                   dz  c_        | j                  j)                          ddd       y| j                  j3                  |       | j4                  j7                  |j8                         ddd       |rD| j"                  5  | xj$                  dz  c_        | j"                  j)                          ddd       | j                  5  | xj                   dz  c_        | j                  j)                          ddd       7# 1 sw Y   'xY w# 1 sw Y   OxY w# 1 sw Y   xY w# 1 sw Y   VxY w# 1 sw Y   yxY w# 1 sw Y   xY w# 1 sw Y   pxY w# 1 sw Y   yxY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# |rQ| j"                  5  | xj$                  dz  c_        | j"                  j)                          ddd       n# 1 sw Y   nxY w| j                  5  | xj                   dz  c_        | j                  j)                          ddd       w # 1 sw Y   w xY wxY w)zRemoves stale sockets then adds new ones if pool is too small and
        has not been reset. The `reference_generation` argument specifies the
        `generation` at the point in time this operation was requested on the
        pool.
        Nr   Tru   F)r  r  r  r  rP  r9  r  rY  r   r  r3   IDLEr  r   r  r8  r  r  r  r  notifyrx  r  r  r  
appendleftr  r  r  )r6  reference_generationr  incrementeds       r[   remove_stale_socketszPool.remove_stale_socketsB  si    YY 	zzY__,	 	,	 99**6 AJJ

288:TYY=\=\\::>>+DOO$:$?$?@	 JJ

288:TYY=\=\\A  #tzz?T%8%88DII<S<SS# # ==DII$;$;;# # "#  K,.. ' }}(<(<<	'" 22 ;*1188:; ^^ ,MMQ&MNN))+, ,% MMQ&M"&K' ||~YY F xx++-1EE(>(D(DEF 22 ;*1188:; ^^ ,MMQ&MNN))+, , JJ))$/((001D1DEF 22 ;*1188:; ^^ ,MMQ&MNN))+,C 	 	
A A# #8; ;, ,/' '&; ;, ,F F; ;, , 22 ;*1188:; ; ; ^^ ,MMQ&MNN))+, , ,s   Q B:Q(0;Q54$Q5!Q5S% R(S% >0R0R;R$S% 6>S4S% 
0R(0R5A SS% 0S!0SQ%(Q25Q?RRR% S% (R25R>S
S% SS"%V
40T-$	V
-T62V
0U>5	V
>VV
c                2   | j                   5  | j                  }| xj                  dz  c_        ddd       | j                  j                  }| j                  r|J |j                  | j                         t        j                  t        j                        rGt        t        | j                  t        j                  | j                  d   | j                  d   |       	 t        | j                  | j                        }t9        || | j                        }| j                   5  | j:                  j=                  |j>                         ddd       	 | j@                  r!|jC                          |jD                  | _"        |r|jG                  |d       |jI                          |S # 1 sw Y   ~xY w# t         $ r}| j                  r|J |j#                  | j                  t$        j&                         t        j                  t        j                        rnt        t        | j                  t        j(                  | j                  d   | j                  d   |t+        t$        j&                        t$        j&                         t-        |t.        t0        t2        f      r-t5        | j                        }t7        | j                  ||        d}~ww xY w# 1 sw Y   xY w# t         $ r! |jK                  t$        j&                          w xY 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.
        ru   Nr   r6  r(  r7  r8  r9  rE  r[  F)completed_handshake)&r  r  rP  r_  r  publish_connection_createdr   r.   r=  r>  r?  r0   r  r/   CONN_CREATEDr  r  rH  r3   r\  rI  r1   r   r]  ri   r<   r  r   r  r  addr  r  r  r  contribute_socketr;  r  )r6  handlerconn_idr  r~   r   r  r  s           r[   rx  zPool.connect{  sn    YY 	)--G##q(#	) II..	  (((00wG!..w}}=&!__4AA#||A#||A'.	%dllDII>D0 $dllG<YY 	:  $$T%8%89	:
	~~

#'#3#3 ))$E)J
 u	) 	)(  	$$ ,,,33LL'+A+G+G &227==A*!% 8 D D#'<<?#'<<?+2?@V@\@\]4::	 %'7H!=>.tyy9)$,,wW+	0	: 	:  	OO2889	s=   "F+$ F8 (&KAK, +F58
KDKKK),*Lc           	   #  d  K   | j                   j                  }t        j                         }| j                  r|J |j                  | j                         t        j                  t        j                        rFt        t        | j                  t        j                  | j                  d   | j                  d          | j                  ||      }| j                  r|J t        j                         |z
  }|j!                  | j                  |j"                  |       t        j                  t        j                        rRt        t        | j                  t        j$                  | j                  d   | j                  d   |j"                  |       	 | j&                  5  | j(                  j+                  |j,                         ddd       | |j0                  rF| j&                  5  | j>                  j+                  |       | xj@                  dz  c_         ddd       y|j2                  rF| j&                  5  | j>                  j+                  |       | xjB                  dz  c_!        ddd       y|j:                  r| j=                  |       yy# 1 sw Y   xY w# t.        $ rg |j0                  xs |j2                  }|r*t5        j6                         \  }}}	|j9                  ||       |s|j:                  r| j=                  |        w xY w# 1 sw Y   yxY w# 1 sw Y   yxY ww)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   ru   r  r  r5  )"rP  r_  r   r   r  $publish_connection_check_out_startedr   r.   r=  r>  r?  r0   r  r/   CHECKOUT_STARTED	_get_connpublish_connection_checked_outr  CHECKOUT_SUCCEEDEDr  r  r  r  r  r  r  sysexc_infohandler  r  r  r  r  )
r6  r  r  checkout_started_timer  rA  pinnedexc_typeexc_valro   s
             r[   checkoutzPool.checkout  s    " II..	 $ 0  (((::4<<H!..w}}=&!__4EE#||A#||A ~~3W~E  (((~~'*??H44T\\477HU!..w}}=&!__4GG#||A#||A'+ww'	 >$$(()<)<=>J ??  %%))$/

a
     #%%))$/"# # [[LL 3> >  	
 __:(:(:F (+||~$'1x1dkkT"	   # #sg   FL0J% $&J
J% L0.1L!L0 1L$1(L0J"J% %A0LL0L!L0$L-)L0c           
        | j                   t        j                  k7  r-| j                  r|r| j                  j
                  J t        j                         |z
  }| j                  j
                  j                  | j                  t        j                  |       t        j                  t        j                        rWt!        t        | j"                  t$        j&                  | j                  d   | j                  d   dt        j                  |       t)        | j                        }t+        | j                  t-        d      |       y y )Nr   ru   <An error occurred while trying to establish a new connectionr6  r(  r7  r8  rF  r   r:  zconnection pool pausedr[  )r  r  r  r  rP  r_  r   r   #publish_connection_check_out_failedr   r2   
CONN_ERRORr.   r=  r>  r?  r0   r  r/   CHECKOUT_FAILEDr  r   r   )r6  r  
emit_eventrA  r  s        r[   _raise_if_not_readyzPool._raise_if_not_ready  s    ::($$yy11===>>+.CC		**NNLL"@"K"KX &227==A*!% 8 H H#'<<?#'<<?]<GG#+	 +4995G%m,DEW^) )r]   c                b   | j                   t        j                         k7  r| j                          | j                  r| j
                  r| j                  j                  J t        j                         |z
  }| j                  j                  j                  | j                  t        j                  |       t        j                  t         j"                        rWt%        t        | j&                  t(        j*                  | j                  d   | j                  d   dt        j                  |       t-        d      | j.                  5  | xj0                  dz  c_        ddd       t3        j4                         rt3        j6                         }nD| j                  j8                  r,t        j                         | j                  j8                  z   }nd}| j:                  5  | j=                  |d       | j>                  | j@                  k  stC        | j:                  |      sD| j>                  | j@                  k  r| j:                  jE                          | jG                  |       | j=                  |d       | j>                  | j@                  k  s| xj>                  dz  c_        ddd       d}d	}d	}	 | j.                  5  | xjH                  dz  c_$        d}ddd       |{| jJ                  5  | j=                  |d	       | jL                  s| jN                  | jP                  k  stC        | jJ                  |      sR| jL                  s| jN                  | jP                  k  r| jJ                  jE                          d}| jG                  |       | j=                  |d	       | jL                  s| jN                  | jP                  k  s	 | jL                  jS                         }ddd       |r| jW                  |      r[d}#	 | jY                  |
      }| jJ                  5  | xjN                  dz  c_'        | jJ                  jE                          ddd       |{d|_2        |S # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# tT        $ r | xjN                  dz  c_'        Y w xY w# 1 sw Y   xY w# 1 sw Y   mxY w# | jJ                  5  | xjN                  dz  c_'        | jJ                  jE                          ddd       w # 1 sw Y   w xY wxY w# tZ        $ r |r|j]                  t^        j`                         | j:                  5  | xj>                  dz  c_        |r| xjH                  dz  c_$        | j:                  jE                          ddd       n# 1 sw Y   nxY w| j
                  r|s| j                  j                  J t        j                         |z
  }| j                  j                  j                  | j                  t        jb                  |       t        j                  t         j"                        rWt%        t        | j&                  t(        j*                  | j                  d   | j                  d   dt        jb                  |        w xY w)z8Get or create a Connection. Can raise ConnectionFailure.Nr   ru   zConnection pool was closedr  z?Attempted to check out a connection from closed connection poolT)r  Fr  r  )3r  r   r  r  r  r  rP  r_  r   r   r  r   r2   r  r.   r=  r>  r?  r0   r  r/   r  r  r  r  r   r  get_deadliner:  r  r  r  r7  r   r  _raise_wait_queue_timeoutr  r  r  r  r  popleft
IndexError	_perishedrx  r  r  r3   r\  r  r  )r6  r  r  rA  r   r  r  emitted_events           r[   r  zPool._get_conn$  sX    88ryy{"$$&;;$$yy11===>>+.CC		**NNLL"@"L"Lh &227==A*!% 8 H H#'<<?#'<<?;<HH#+	 #Q  YY 	&  A% 	& ))+HYY))~~'$))*F*FFHH^^ 
	$$%:t$L}}t'9'99!$..(; }}t'9'99--/223HI(()>4(P }}t'9'99 MMQM
	 =	 ###q(#"# , .. +,,-Bu,U#zzT]]T=Q=Q-Q)$*C*CXN  $zzT]]T=Q=Q-Q $ 9 9 @ @ B,0M ::;PQ001FSX0Y  $zzT]]T=Q=Q-Q+#zz113+  ~~d+# ?#||G|<!66 ? MMQ.M 55<<>?7 ,v w	& 	&
	 
	"# #( & +*++ +0? ?T66 ? MMQ.M 55<<>? ? ?  	 6 < <= ("''1,'%%'	( ( ( $$]yy11===>>+.CC		**NNLL"@"K"KX &227==A*!% 8 H H#'<<?#'<<?]<GG#+	 7	s   	Q+ B3Q8Q88T# RT# 3CR6R(T# S T# &0S
T# +Q58RR
T# R30R62R33R66R?;T# ST# T 0T	T TT  T# #7Z.AV*!	Z.*V3	/C?Z.c                2   |j                   }|j                  }d|_        d|_         d|_        | j                  j	                  |       | j
                  j                  }| j                  5  | j                  j	                  |j                         ddd       | j                  r|J |j                  | j                  |j                         t        j                  t         j"                        rQt%        t        | j&                  t(        j*                  | j                  d   | j                  d   |j                         | j,                  t/        j0                         k7  r| j3                          n| j4                  r!|j7                  t8        j:                         n|j4                  r| j                  r|J |j=                  | j                  |j                  t8        j>                         t        j                  t         j"                        r=t%        t        | j&                  t(        j@                  | j                  d   | j                  d   |j                  tC        t8        j>                        t8        j>                         n| j                  5  | jE                  |jF                  |jH                        r |j7                  t8        jJ                         ni|jM                          |jO                  tQ        | jR                               | jT                  jW                  |       | jX                  j[                          ddd       | j\                  5  |r| xj^                  dz  c_/        n|r| xj`                  dz  c_0        | xjb                  dz  c_1        | xjd                  dz  c_2        | xjf                  dz  c_3        | j\                  j[                          ddd       y# 1 sw Y   exY w# 1 sw Y   xY w# 1 sw Y   yxY w)zReturn the connection to the pool, or if it's closed discard it.

        :param conn: The connection to check into the pool.
        FNr   ru   r  rE  )4r  r  r  r  r  rP  r_  r  r  r  r  publish_connection_checked_inr   r  r.   r=  r>  r?  r0   r  r/   	CHECKEDINr  r   r  r  r  r  r3   r  rH  r\  rI  r1   r  r  r  r  rU  rW  r   r  r  r  r  r  r  r  r  r  r  r  )r6  r  txncursorr  s        r[   r  zPool.checkin  s   
 oo##"%%d+II..	YY 	>  (()<)<=	>  (((33DLL$''J!..w}}=&!__4>>#||A#||A'+ww 88ryy{"$$&{{ 6 B BC(($00077dgg/E/K/K *66w}}E".%)__$<$H$H'+||A'+||A/3ww#CDZD`D`#a"8">">	 YY 
; ,,T__dooN(>(D(DE557//T5E5E0FG

--d31188:
; ^^ 	$

a
"MMQM1$  A% NN!!#	$ 	$e	> 	>L
; 
;	$ 	$s&   +&O4B0P"B	P4O>P
Pc                   |j                         }| j                  j                  9|| j                  j                  kD  r |j                  t        j
                         y| j                  N| j                  dk(  s|| j                  kD  r0|j                         r |j                  t        j                         y| j                  |j                  |j                        r |j                  t        j                         yy)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.
        Tr   F)rY  rP  r9  r  r3   r  r  rO  r\  r  r  r  r  )r6  r  rY  s      r[   r  zPool._perished  s     !224 II++7!DII$C$CCOO2778''3((A-1BTEaEa1a! 6 < <=  $//BOO2889r]   c           
     l   | j                   j                  }| j                  r|J t        j                         |z
  }|j                  | j                  t        j                  |       t        j                  t        j                        rWt        t        | j                  t        j                   | j                  d   | j                  d   dt        j                  |       t#        j$                         xs | j                   j&                  }| j                   j(                  rl| j*                  | j,                  z
  | j.                  z
  }t1        dj3                  | j                   j4                  | j,                  | j.                  ||            t1        d| j                   j4                   d|       )Nr   ru   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: )rP  r_  r  r   r   r  r   r2   TIMEOUTr.   r=  r>  r?  r0   r  r/   r  r   r  r:  rC  r  r  r  r(   r5  r7  )r6  r  r  rA  r   	other_opss         r[   r  zPool._raise_wait_queue_timeout  sd   II..	  (((~~'*??H99<DDh "..w}}=&!__4DD#||A#||A_8@@'	 ##%E)E)E99""++dmm;djjHI'7 8>vII++MMJJ8	  $ II334KyJ
 	
r]   c                H    | j                   D ]  }|j                  d         y re   )r  r  )r6  r  s     r[   __del__zPool.__del__4  s#     JJ 	"DOOD!	"r]   )TN)r   rQ   r  r   r  r   r  r  r  rv  )TNF)
rK  r   r  r   r  r  r  r   rq  r  )r  ro  rq  r  r  )r  r  r  r   rq  r  r  )r  rh   rq  r  re   )r  "Optional[_MongoClientErrorHandler]rq  r  )r  r&  rq  zIterator[Connection])r  rt  r  r   rq  r  )r  rt  r  r&  rq  r  )r  r  rq  r  )r  r  rq  r   )r  rt  rq  r
   )rw  rx  ry  rE  r  r|  r  r  rW  r  r  rK  r  r  rx  
contextlibcontextmanagerr  r  r  r  r  r  r%  r_   r]   r[   rk  rk  q  sG   
 (,RR R 	R
 &Rh" . . )-&+N>N> N> '	N>
  $N> 
N>`= TYe,eLPe	e
. /7,rBH I IV4 [_{%*{5W{	{zF$P"H%
N"r]   rk  )rY   rh   rq  r  )r~   socket.socketr   r   r   rh   rq  r  )r~   r)  rq  r  )rq  zdict[str, str]rv  )rk   r   rq  rg  rr  )r   rm  rq  r  )NN)
r   r   r   rL  r   rk  r   Optional[dict[str, float]]rq  r
   )r   zthreading.Conditionr   rh  rq  r   )r  r   rq  zdict[str, float])r  r*  rq  r   )r   rQ   r  r   rq  r)  )r   rQ   r  r   rq  rj  )
__future__r   r  r'  r2  r>  r   r   r|   r  r  r  r   r  pathlibr   typingr   r   r   r   r	   r
   r   r   r   r   r   pymongor   r   r   r   pymongo.client_sessionr   pymongo.commonr   r   r   r   r   r   r   r   r   r   pymongo.errorsr   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   pymongo.hellor*   r+   pymongo.helpersr,   pymongo.lockr-   pymongo.loggerr.   r/   r0   r1   pymongo.monitoringr2   r3   r4   pymongo.networkr5   r6   pymongo.read_preferencesr7   pymongo.server_apir8   pymongo.server_typer9   pymongo.socket_checkerr:   pymongo.ssl_supportr;   r<   r=   bson.objectidr>   pymongo.authr?   r@   rA   pymongo.compression_supportrB   rC   rD   rE   pymongo.driver_inforF   pymongo.messagerG   rH   pymongo.mongo_clientrI   rJ   pymongo.pyopenssl_contextrK   rL   pymongo.read_concernrM   rN   rO   pymongo.typingsrP   rQ   rR   pymongo.write_concernrS   rW   rT   rU   rV   r\   ImportErrorrx   rz   r   _winregrf   rp   OpenKeyHKEY_LOCAL_MACHINErk   rw   ry   ri   r   r   r   __annotations__r   system_namemachinereleasemac_verjoin	win32_verjava_ver_ver_archsystem_aliasr   _aliasedpython_implementationmapr   pypy_version_infoversion_infor   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  rk  )parts   0r[   <module>r]     s   #     	   
 
    
 
 
  & 5 5 B      - * %  
 5 3 . + 0 1!&:4  /0J>04,CC2E99/    <<7 
(V^^%%'\
 	N#)##H '-c3F'M$		NM? &	k'RS	> S<<7#
 HOOE(((*#8##%IdO 	\\X!!(((* $8##%a(IdO 	\\W!/(//+-=X-=-=-?@A(((*88.H..0156IdO 	\\V$***,R0E4 IdO %x$$_X__%68H8H8H8JL\HL\L\L^_H!8BQ<@44$@A(((*A;	IdO "8!!#..v6HH*H**,HHSc3345CHHSc.>.>%?@@	
Ij 	\\V$HH*H**,HHSc../0SXXx02B(2B2B2DEFF	
Ij  HH	'	'	'	)388CS=M=M4N+OPIj  ' $ 
7F%N"J  'H V  !%26	,,, , 0	,
 ,:#
	e$ e$P G
 G
TD,N.b| + +> H" H"o'  EE	E  	N 	N
  (  '#' 	(d AsZ   X! X1 Y ,YY Y
Y
!	X.-X.1	X>=X>YY 	YY