U
    dj(                     @  s:  d Z ddl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 ddlmZ ddlmZmZ ddlmZmZ ddlmZmZmZmZ dd	lmZmZ erdd
lmZ ddlm Z  ddl!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1 ddddiZ2G dd dZ3dS )z2Communicate with one MongoDB server in a topology.    )annotations)datetime)TYPE_CHECKINGAnyCallableContextManagerListOptionalTupleUnion)_decode_all_selective)NotPrimaryErrorOperationFailure)_check_command_response_handle_reauth)_convert_exception_GetMore_OpMsg_Query)PinnedResponseResponse)Queue)ReferenceType)ObjectId)_MongoClientErrorHandler)Monitor)_EventListeners)
ConnectionPool)_ServerMode)ServerDescription)_DocumentOutcursor   )
firstBatch	nextBatchc                	   @  s   e Zd Zd1dddddddd	d
dZddddZd2dddddZddddZddddZedddddddddZ	d3ddd d!d"Z
eddd#d$Zejddd%d&d$Zeddd'd(Zd)d*d+d,d-Zd.dd/d0ZdS )4ServerNr    r   r   zOptional[ObjectId]zOptional[_EventListeners]zOptional[ReferenceType[Queue]]None)server_descriptionpoolmonitortopology_id	listenerseventsreturnc                 C  sF   || _ || _|| _|| _|dk	o$|j| _|| _d| _| jrB| | _dS )zRepresent one MongoDB server.N)_description_pool_monitor_topology_idZenabled_for_server_publish	_listener_events)selfr(   r)   r*   r+   r,   r-    r7   2/tmp/pip-unpacked-wheel-oblwsawz/pymongo/server.py__init__5   s    
zServer.__init__)r.   c                 C  s   | j jjs| j  dS )z[Start monitoring, or restart after a fork.

        Multiple calls have no effect.
        N)r0   optsZload_balancedr1   openr6   r7   r7   r8   r;   I   s    
zServer.open)
service_idr.   c                 C  s   | j | dS )zClear the connection pool.N)r)   reset)r6   r=   r7   r7   r8   r>   Q   s    zServer.resetc                 C  sX   | j r@| jdk	st| jdk	s"t| j| jj| jj| jff | j	
  | j  dS )zXClear the connection pool and stop the monitor.

        Reconnect with open().
        N)r3   r4   AssertionErrorr5   putZpublish_server_closedr/   addressr2   r1   closer0   Zreset_without_pauser<   r7   r7   r8   rB   U   s    
zServer.closec                 C  s   | j   dS )zCheck the server's state soon.N)r1   request_checkr<   r7   r7   r8   rC   f   s    zServer.request_checkr   zUnion[_Query, _GetMore]r   z!Callable[..., List[_DocumentOut]]r   )conn	operationread_preferencer,   
unpack_resr.   c                 C  s  d}|dk	st |j}|r"t }||}	|jo8|jj}
|
rDd}n||||	}| |\}}}|r|	|\}}|dk	st |j
||||j|jd t }z|
r|d}n||| ||}|	rt}d}nd}d}|||j|j||d}|	r|d }|j||j t||j W n tk
r } zb|rt | }t|ttfr^|j}nt|}|dk	stt |j|||j||j|jd  W 5 d}~X Y nX |rLt | }|	r|d }n\|jdkr|r|d ni }n<|j| dd	d
}|jdkr||d d< n||d d< |dk	s0t |j |||j||j|jd |j}|r|j!r|	r|j!"|# }t$||j|}|%|js|j&r|'  t|t(r|j}
nt)|j&o|j}
|jr|j*|
 t+|| j,j||||	||
d}nt-|| j,j|||	|d}|S )a  Run a _Query or _GetMore operation and return a Response object.

        This method is used only to run _Query/_GetMore operations from
        cursors.
        Can raise ConnectionFailure, OperationFailure, etc.

        :Parameters:
          - `conn`: A Connection instance.
          - `operation`: A _Query or _GetMore object.
          - `read_preference`: The read preference to use.
          - `listeners`: Instance of _EventListeners or None.
          - `unpack_res`: A callable that decodes the wire protocol response.
        Nr   )r=   FT)legacy_responseuser_fieldsexplain)idnsr#   )r"   okfindr"   r$   r%   )datarA   rD   duration
request_idfrom_commanddocsmore_to_come)rO   rA   rP   rQ   rR   rS   ).r?   Zenabled_for_commandsr   nowZuse_commandZconn_mgrrT   Zget_message_split_messageZ
as_commandZpublish_command_startrA   r=   Zreceive_messagesend_message_CURSOR_DOC_FIELDSZ	cursor_idZcodec_optionsclientZ_process_responsesessionr   Zmax_wire_version	Exception
isinstancer   r   detailsr   Zpublish_command_failurename	namespaceZpublish_command_successZ
_encrypterZdecryptZraw_command_responser   Z_should_pin_cursorZexhaustZ
pin_cursorr   boolZupdate_exhaustr   r/   r   )r6   rD   rE   rF   r,   rG   rP   publishstartZuse_cmdrT   rQ   messagerO   Zmax_doc_sizecmdZdbnZreplyrI   rH   rS   firstexcZfailureresrY   Z	decryptedresponser7   r7   r8   run_operationj   s    
    


	zServer.run_operationz"Optional[_MongoClientErrorHandler]zContextManager[Connection])handlerr.   c                 C  s   | j |S N)r)   checkout)r6   rj   r7   r7   r8   rl     s    zServer.checkoutc                 C  s   | j S rk   )r/   r<   r7   r7   r8   description  s    zServer.description)r(   r.   c                 C  s   |j | jj kst|| _d S rk   )rA   r/   r?   )r6   r(   r7   r7   r8   rm     s    c                 C  s   | j S rk   )r0   r<   r7   r7   r8   r)     s    zServer.poolz,Union[Tuple[int, Any], Tuple[int, Any, int]]zTuple[int, Any, int])rc   r.   c                 C  s&   t |dkr|S |\}}||dfS dS )zReturn request_id, data, max_doc_size.

        :Parameters:
          - `message`: (request_id, data, max_doc_size) or (request_id, data)
           r   N)len)r6   rc   rQ   rO   r7   r7   r8   rV     s    zServer._split_messagestrc                 C  s   d| j j d| jdS )N< >)	__class____name__r/   r<   r7   r7   r8   __repr__$  s    zServer.__repr__)NNN)N)N)ru   
__module____qualname__r9   r;   r>   rB   rC   r   ri   rl   propertyrm   setterr)   rV   rv   r7   r7   r7   r8   r&   4   s*        r&   N)4__doc__
__future__r   r   typingr   r   r   r   r   r	   r
   r   Zbsonr   Zpymongo.errorsr   r   Zpymongo.helpersr   r   Zpymongo.messager   r   r   r   Zpymongo.responser   r   queuer   weakrefr   Zbson.objectidr   Zpymongo.mongo_clientr   Zpymongo.monitorr   Zpymongo.monitoringr   Zpymongo.poolr   r   Zpymongo.read_preferencesr   Zpymongo.server_descriptionr    Zpymongo.typingsr!   rX   r&   r7   r7   r7   r8   <module>   s*   (