o
    h                     @  s  U d Z ddlm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mZm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! z
ddl"m#Z# dZ$W n e%yr   dZ$Y nw ddl&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z. ddl/m0Z0m1Z1 e
rddl2m3Z3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z:m;Z;m<Z<m=Z= dZ>dZ?dZ@dZAdZBdZCdZDdZEdZFdZGdZHdZIdZJeAdeBd eCd!iZKd"d#d$d%d&ZLed'd(ZMd)eNd*< dd-d.ZOdd3d4ZPdd8d9ZQdd:d;ZRddAdBZSddCdDdEdFdGZTdHdIdJdKdLdMdNdOdPdQdQdRdSZU			dddddeZVddkdlZWeXdmjYZZdnZ[ddtduZ\eXdvjYZ]ddwdxZ^eXdyjYZ_eXdzjYZ`eXd{jYZad ddZbdddZcdddZde$rae#jeZd	ddddZedddZfdddZgdddZhe$re#jiZh	ddddZjeXdjYZkd	ddZld
ddZmdddZne$re#joZn	ddddZpeAdeBdeCdiZqG dd dZrG dd derZsG dd desZtdddZudZvdddZwdddZxe$re#jxZxdddÄZydddńZze$re#jzZzdddȄZ{G ddʄ derZ|dZ}dddфZ~ddd؄ZdddۄZdddބZdddZdddZdddZe$r=e#jZdddZG dd dZG dd dZejejejejiZdeNd< G dd dZG dd dZG dd deZG dd deZG dd deZdS (  zTools for creating `messages
<https://www.mongodb.com/docs/manual/reference/mongodb-wire-protocol/>`_ to be sent to
MongoDB.

.. note:: This module is for internal use and is generally not needed by
   application developers.
    )annotationsN)BytesIO)	TYPE_CHECKINGAnyCallableIterableMappingMutableMappingNoReturnOptionalUnion)CodecOptions_dict_to_bson_make_c_string)Int64)_RAW_ARRAY_BSON_OPTIONSDEFAULT_RAW_BSON_OPTIONSRawBSONDocument_inflate_bson)HelloCompat)_EventListeners)	_cmessageTF)ConfigurationErrorCursorNotFoundDocumentTooLargeExecutionTimeoutInvalidOperationNotPrimaryErrorOperationFailureProtocolError)ReadPreference_ServerMode)SnappyContextZlibContextZstdContext)ReadConcern)_Address_AgnosticClientSession_AgnosticConnection_AgnosticMongoClient_DocumentOutii   i?                   s            s           s       s   documents     s   updates     s   deletes     	documentsupdatesZdeletesops)insertupdatedelete	bulkWritereplace)Zunicode_decode_error_handlerzCodecOptions[Mapping[str, Any]]_UNICODE_REPLACE_CODEC_OPTIONSreturnintc                   C  s   t ttS )z(Generate a pseudo random 32 bit integer.)randomrandint	MIN_INT32	MAX_INT32 r@   r@   B/var/www/html/venv/lib/python3.10/site-packages/pymongo/message.py_randintt   s   rB   specMutableMapping[str, Any]read_preferencer!   c                 C  sD   |j }|j}|r |tjj kst|dkr d| vrd| i} || d< | S )z-Add $readPreference to spec when appropriate.r+   $query$readPreference)modedocumentr    ZSECONDARY_PREFERREDlen)rC   rE   rH   rI   r@   r@   rA   _maybe_add_read_preferencey   s   rK   	exception	Exceptiondict[str, Any]c                 C  s   t | | jjdS )z<Convert an Exception into a failure document for publishing.)errmsgerrtype)str	__class____name__rL   r@   r@   rA   _convert_exception   s   rU   c                 C  s   t | | j| jjdS )zmConvert an Exception into a failure document for publishing,
    for use in client-level bulk write API.
    )rO   coderP   )rQ   rV   rR   rS   rT   r@   r@   rA   _convert_client_bulk_exception   s   rW   	operationrQ   commandMapping[str, Any]resultc           	      C  s  | dd}d|d}| d| dd}|rB| dr'|d	dd
id|d< nd| dd|d}d|v r;|d |d< |g|d< |S | dkrPt|d |d< |S | dkrd|v rdd|d dg|d< |S | ddu r|dkr|d d }|d  d|d  d}d|dg|d< |S )z6Convert a legacy write result to write command format.nr   r+   )okr\   rO   err Zwtimeout@   T)rO   rV   errInfoZwriteConcernErrorrV      )indexrV   rO   ra   ZwriteErrorsr4   r1   r5   Zupserted)rc   _idZupdatedExistingFr2   urd   q)getrJ   )	rX   rY   r[   ZaffectedresrO   errorr5   rd   r@   r@   rA   _convert_write_result   s.   


	rj   rb             )ZtailableZoplogReplayZnoCursorTimeoutZ	awaitDataZallowPartialResultsfiltersorthintcommentZmaxScan	maxTimeMSmaxminZ	returnKeyZshowRecordIdZsnapshot)rF   z$orderbyz$hintz$commentz$maxScanz
$maxTimeMSz$maxz$minz
$returnKeyz$showRecordIdz$showDiskLocz	$snapshotcoll
projection1Optional[Union[Mapping[str, Any], Iterable[str]]]skiplimit
batch_sizeOptional[int]optionsread_concernr%   	collationOptional[Mapping[str, Any]]session Optional[_AgnosticClientSession]allow_disk_useOptional[bool]c                   s  d| i}d|v r'| dd | D  d|v r|d d|v r&|d n||d< |r1||d< |r7||d	< |rGt||d
< |dk rGd|d< |rU||krQ|d7 }||d< |jrb|	r]|	jsb|j|d< |rh||d< |
durp|
|d<  r|  fddt D  |S )z!Generate a find command document.findrF   c                 S  s,   g | ]\}}|t v rt | |fn||fqS r@   )
_MODIFIERS).0keyvalr@   r@   rA   
<listcomp>   s    z%_gen_find_command.<locals>.<listcomp>$explainrG   rn   rv   rx   ry   r   TZsingleBatchr+   	batchSizeZreadConcernr~   NZallowDiskUsec                   s    g | ]\}} |@ r|d fqS )Tr@   )r   optr   r|   r@   rA   r   
  s     )r5   itemspopabslevelin_transactionrI   _OPTIONS)ru   rC   rv   rx   ry   rz   r|   r}   r~   r   r   cmdr@   r   rA   _gen_find_command   sD   


r   	cursor_idmax_await_time_msOptional[Any]connr(   c                 C  sD   | |d}|r||d< |dur||d< |dur |j dkr ||d< |S )z$Generate a getMore command document.)getMoreZ
collectionr   Nrr   	   rq   )max_wire_version)r   ru   rz   r   rq   r   r   r@   r@   rA   _gen_get_more_command  s   
	r   z<iiiiiiB   databytesctx.Union[SnappyContext, ZlibContext, ZstdContext]tuple[int, bytes]c                 C  s>   | |}t }ttt| |dd| t||j}||| fS )zDTakes message data, compresses it, and adds an OP_COMPRESSED header.r   i  )compressrB   _pack_compression_header_COMPRESSION_HEADER_SIZErJ   Zcompressor_id)rX   r   r   
compressed
request_idheaderr@   r@   rA   	_compress&  s   

	r   z<iiiic                 C  s(   t  }tdt| |d| }||| fS )ztTakes message data and adds a message header based on the operation.

    Returns the resultant message string.
    rk   r   )rB   _pack_headerrJ   )rX   r   ridmessager@   r@   rA   __pack_message<  s   r   z<iz<IBz<Bflags
identifierdocs!Optional[list[Mapping[str, Any]]]optsr   tuple[bytes, int, int]c                   s   t |d }t| d}t|}d}|rR|durRtd}	t|}
 fdd|D }t|
tdd |D  d	 }t|}||7 }td
d |D }|||	||
g|}n||g}d|||fS )zGet a OP_MSG message.

    Note: this method handles multiple documents in a type one payload but
    it does not perform batch splitting and the total message size is
    only checked *after* generating the entire message.
    Fr   Nr+   c                   s   g | ]}t |d  qS F)r   r   docr   r@   rA   r   `  s    z%_op_msg_no_header.<locals>.<listcomp>c                 s      | ]}t |V  qd S NrJ   r   r@   r@   rA   	<genexpr>a      z$_op_msg_no_header.<locals>.<genexpr>   c                 s  r   r   r   r   r@   r@   rA   r   d  r   r-   )	r   _pack_op_msg_flags_typerJ   
_pack_byter   sum	_pack_intrs   join)r   rY   r   r   r   encodedZ
flags_type
total_sizeZmax_doc_sizeZtype_oneZcstringZencoded_docssizeZencoded_sizer   r@   r   rA   _op_msg_no_headerK  s   
r   tuple[int, bytes, int, int]c           
      C  s2   t | ||||\}}}td||\}	}|	|||fS )zInternal OP_MSG message helper.  )r   r   )
r   rY   r   r   r   r   msgr   max_bson_sizer   r@   r@   rA   _op_msg_compressedk  s   	r   c           
      C  s0   t | ||||\}}}td|\}}	||	||fS )z*Internal compressed OP_MSG message helper.r   )r   r   )
r   rY   r   r   r   r   r   r   r   Z
op_messager@   r@   rA   _op_msg_uncompressedy  s   r   dbnameOptional[_ServerMode]4Union[SnappyContext, ZlibContext, ZstdContext, None]c           	   	   C  s   ||d< |durd|vr|j r|j|d< tt|}zt| }||}W n ty2   d}d}Y nw z#|rGt| |||||W |rF|||< S S t| ||||W |rV|||< S S |r]|||< w )zGet a OP_MSG message.$dbNrG   r_   )	rH   rI   nextiter
_FIELD_MAPr   KeyErrorr   r   )	r   rY   r   rE   r   r   namer   r   r@   r@   rA   _op_msg  s.   	



r   collection_namenum_to_skipnum_to_returnqueryfield_selectortuple[bytes, int]c           
      C  s`   t |d|}|rt |d|}nd}tt|t|}	dt| t|t|t|||g|	fS )zGet an OP_QUERY message.Fr-   )r   rs   rJ   r   r   bsonr   )
r|   r   r   r   r   r   r   r   Zefsr   r@   r@   rA   _query_impl  s    

r   tuple[int, bytes, int]c                 C  s2   t | ||||||\}}	td||\}
}|
||	fS )z)Internal compressed query message helper.  )r   r   )r|   r   r   r   r   r   r   r   op_queryr   r   r   r@   r@   rA   _query_compressed  s
   
r   c                 C  s0   t | ||||||\}}td|\}	}
|	|
|fS )zInternal query message helper.r   )r   r   )r|   r   r   r   r   r   r   r   r   r   r   r@   r@   rA   _query_uncompressed  s
   

r   c              	   C  s.   |rt | |||||||S t| ||||||S )zGet a **query** message.)r   r   )r|   r   r   r   r   r   r   r   r@   r@   rA   _query  s   r   z<qc                 C  s    d tt| t|t|gS )zGet an OP_GET_MORE message.r-   )r   _ZERO_32r   r   r   _pack_long_longr   r   r   r@   r@   rA   _get_more_impl  s   r   c                 C  s   t dt| |||S )z+Internal compressed getMore message helper.  )r   r   r   r   r   r   r@   r@   rA   _get_more_compressed  s   r   c                 C  s   t dt| ||S )z Internal getMore message helper.r   )r   r   r   r@   r@   rA   _get_more_uncompressed  s   r   c                 C  s   |r	t | |||S t| ||S )zGet a **getMore** message.)r   r   r   r@   r@   rA   	_get_more(  s   r   s
   documents s   updates s   deletes c                   @  sj   e Zd ZdZdZd(ddZed)ddZed)ddZed)ddZ	ed)ddZ
d*d"d#Zd+d%d&Zd'S ),_BulkWriteContextBasez]Private base class for wrapping around AsyncConnection to use with write splitting functions.)db_namer   op_idr   fieldpublish
start_time	listenersr   r   op_typecodecdatabase_namerQ   cmd_namer   r(   operation_idr;   r   r   r   r   r   r   r   c	           	      C  s`   || _ || _|| _|| _|j| _|| _t| j | _t	j	
 | _|| _t|j| _|| _|| _d S r   )r   r   r   r   Zenabled_for_commandsr   r   r   r   datetimenowr   r   boolcompression_contextr   r   r   	selfr   r   r   r   r   r   r   r   r@   r@   rA   __init__P  s   
z_BulkWriteContextBase.__init__r:   c                 C     | j jS )z#A proxy for SockInfo.max_bson_size.)r   r   r   r@   r@   rA   r   h     z#_BulkWriteContextBase.max_bson_sizec                 C  s   | j r	| jjd S | jjS )z&A proxy for SockInfo.max_message_size.rk   )r   r   max_message_sizer  r@   r@   rA   r  m  s   z&_BulkWriteContextBase.max_message_sizec                 C  r  )z*A proxy for SockInfo.max_write_batch_size.)r   max_write_batch_sizer  r@   r@   rA   r  u  r  z*_BulkWriteContextBase.max_write_batch_sizec                 C     | j S )z:The maximum size of a BSON command before batch splitting.)r   r  r@   r@   rA   max_split_sizez     z$_BulkWriteContextBase.max_split_sizer   replyr*   durationdatetime.timedeltaNonec                 C  4   | j j||| j|| jj| jj| j| jj| jd	 dS )z Publish a CommandSucceededEvent.r   N)	r   Zpublish_command_successr   r   addressserver_connection_idr   
service_idr   )r   r   r
  r  r@   r@   rA   _succeed     
z_BulkWriteContextBase._succeedfailurec                 C  r  )zPublish a CommandFailedEvent.r  N)	r   Zpublish_command_failurer   r   r  r  r   r  r   )r   r   r  r  r@   r@   rA   _fail  r  z_BulkWriteContextBase._failNr   rQ   r   rQ   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  )rS   
__module____qualname____doc__	__slots__r  propertyr   r  r  r  r  r  r@   r@   r@   rA   r   >  s    

r   c                      s:   e Zd ZdZdZd fddZdddZd ddZ  ZS )!_BulkWriteContextz]A wrapper around AsyncConnection/Connection for use with the collection-level bulk write API.r@   r   rQ   r   r   r(   r   r;   r   r   r   r   r   r   r   c	           	   
     s   t  |||||||| d S r   superr  r   rR   r@   rA   r    s   z_BulkWriteContext.__init__r   rD   r   list[Mapping[str, Any]]r:   Atuple[int, Union[bytes, dict[str, Any]], list[Mapping[str, Any]]]c                 C  s<   | j d }t|| j||| j| \}}}|std|||fS )N.$cmdcannot do an empty bulk write)r   _do_batched_op_msgr   r   r   )r   r   r   	namespacer   r   to_sendr@   r@   rA   batch_command  s   


z_BulkWriteContext.batch_commandr   c              	   C  s6   ||| j < | j|| j|| jj| jj| j| jj |S )Publish a CommandStartedEvent.)	r   r   publish_command_startr   r   r  r  r   r  )r   r   r   r   r@   r@   rA   _start  s   
	z_BulkWriteContext._startr  )r   rD   r   r"  r:   r#  )r   rD   r   r;   r   r"  r:   rD   	rS   r  r  r  r  r  r)  r,  __classcell__r@   r@   r!  rA   r    s    
r  c                   @  s(   e Zd ZdZddd	ZedddZdS )_EncryptedBulkWriteContextr@   r   rD   r   r"  r:   3tuple[int, dict[str, Any], list[Mapping[str, Any]]]c                 C  s`   | j d }t|| j||| j| \}}|std|ddd }tt||d  t}d||fS )Nr$  r%  r/   r   r   )	r   _encode_batched_write_commandr   r   r   rc   r   
memoryviewr   )r   r   r   r'  r   r(  Z	cmd_startoutgoingr@   r@   rA   r)    s   

z(_EncryptedBulkWriteContext.batch_commandr;   c                 C  s   t S )z Reduce the batch splitting size.)_MAX_SPLIT_SIZE_ENCr  r@   r@   rA   r       z)_EncryptedBulkWriteContext.max_split_sizeN)r   rD   r   r"  r:   r0  r  )rS   r  r  r  r)  r  r  r@   r@   r@   rA   r/    s
    
r/  doc_sizemax_sizer
   c                 C  s&   | dkrt d||f t | d)z-Internal helper for raising DocumentTooLarge.r4   zfBSON document too large (%d bytes) - the connected server supports BSON document sizes up to %d bytes.z command document too large)r   )rX   r7  r8  r@   r@   rA   _raise_document_too_large  s   	r9  i    r"  ackr   buf_BytesIO#tuple[list[Mapping[str, Any]], int]c                 C  sd  |j }|j}|j}	|rdnd}
||
 |d |t|d| |d | }|d z	|t|   W n tyE   tddw g }d}|D ]O}t|d|}t	|}| | }|dkoe||	k}| ol||k}|sq|rt
t |  }t|t	|| ||	kr n|| || |d	7 }||kr nqL| }|| |t||  ||fS )
zCreate a batched OP_MSG write.r0         r/   F   Unknown commandNr   r+   )r   r  r  writer   tell_OP_MSG_MAPr   r   rJ   listr   keysr9  appendseekr   )rX   rY   r   r:  r   r   r;  r   r  r  r   size_locationr(  idxr   valueZ
doc_lengthnew_message_sizedoc_too_largeZunacked_doc_too_largewrite_oplengthr@   r@   rA   _batched_op_msg_impl  sL   








rO  %tuple[bytes, list[Mapping[str, Any]]]c           	      C  *   t  }t| ||||||\}}| |fS )zOEncode the next batched insert, update, or delete operation
    as OP_MSG.
    )r<  rO  getvalue)	rX   rY   r   r:  r   r   r;  r(  _r@   r@   rA   _encode_batched_op_msgE  s   rT  *tuple[int, bytes, list[Mapping[str, Any]]]c           
      C  sD   t | |||||\}}|jjdusJ td||jj\}}	||	|fS )z]Create the next batched insert, update, or delete operation
    with OP_MSG, compressed.
    Nr   )rT  r   r   r   )
rX   rY   r   r:  r   r   r   r(  r   r   r@   r@   rA   _batched_op_msg_compressedZ  s   
rV  c           
      C  sv   t  }|t |d t| ||||||\}}|d t }	|t|	 |d |t| |	| |fS )z"OP_MSG implementation entry point.         r   r   )r<  rA  _ZERO_64rO  rG  rB   r   rR  )
rX   rY   r   r:  r   r   r;  r(  rN  r   r@   r@   rA   _batched_op_msgl  s   	



rY  r'  c                 C  sb   |  ddd |d< d|v rt|d dd}nd}|jjr(t||||||S t||||||S )zRCreate the next batched insert, update, or delete operation
    using OP_MSG.
    .r+   r   r   writeConcernwT)splitr   rg   r   r   rV  rY  )r'  rX   rY   r   r   r   r:  r@   r@   rA   r&    s   r&  c                      s:   e Zd ZdZdZd" fddZd#ddZd$d d!Z  ZS )%_ClientBulkWriteContextzYA wrapper around AsyncConnection/Connection for use with the client-level bulk write API.r@   r   rQ   r   r   r(   r   r;   r   r   r   r   r   r   c              
     s   t  ||||||d| d S )Nr   r  )r   r   r   r   r   r   r   r   r!  r@   rA   r    s   
z _ClientBulkWriteContext.__init__r   rD   
operations#list[tuple[str, Mapping[str, Any]]]
namespaces	list[str]r:   Ztuple[int, Union[bytes, dict[str, Any]], list[Mapping[str, Any]], list[Mapping[str, Any]]]c                 C  s2   t |||| j| \}}}}|std||||fS )Nr%  )_client_do_batched_op_msgr   r   )r   r   r_  ra  r   r   to_send_ops
to_send_nsr@   r@   rA   r)    s   z%_ClientBulkWriteContext.batch_commandr   op_docsr"  ns_docsc              	   C  s<   ||d< ||d< | j || j|| jj| jj| j| jj |S )r*  r3   ZnsInfo)r   r+  r   r   r  r  r   r  )r   r   r   rg  rh  r@   r@   rA   r,    s   	z_ClientBulkWriteContext._start)r   rQ   r   rQ   r   r(   r   r;   r   r   r   r   r   r   )r   rD   r_  r`  ra  rb  r:   rc  )
r   rD   r   r;   rg  r"  rh  r"  r:   rD   r-  r@   r@   r!  rA   r^    s    
r^  i  command_encodedto_send_ops_encodedlist[bytes]to_send_ns_encodedc                 C  s   |rdnd}| | | d | |  | d | }| d | d |D ]}| | q*| }| }	|| | t|	|  || | d | }| d | d |D ]}
| |
 qb| }	|| | t|	|  |	S )Nr0   r>  r/   r?  s   ops s   nsInfo )rA  rB  rG  r   )ri  rj  rl  r:  r;  r   rH  Z
op_encodedZresume_locationrN  Z
ns_encodedr@   r@   rA   _client_construct_op_msg  s2   











rm  r_  r`  ra  rb  <tuple[list[Mapping[str, Any]], list[Mapping[str, Any]], int]c           %        s`  ddd	}|j }|j}	|j}
t d
|}|s |dt||t  g d} dr.|d  dr8|d  drB|d  fdd|D }tt|d
|}|
t|  }i }g }g }g }g }d}d}d}t	||D ]\\}}}|}|dkr|stt|d d
|}|||| |dkrd}|stt|d d
|}|||| d}d}||vrd|i}t|}|||< || ||< t|d
|} t| }!|rt|d
|}"t|"}|s|||!|t  || |! | }#|#|kr|dkrt
||!|t   n+|| ||  ||!7 }|r|| ||" ||7 }|d7 }||	kr" nqnt|||||}$|||$fS )z:Create a batched OP_MSG write for client-level bulk write.r   rQ   r7  r;   ry   r:   r  c                 S  s   ||krt | || d S d S r   )r9  )r   r7  ry   r@   r@   rA   _check_doc_size_limits  s   z;_client_batched_op_msg_impl.<locals>._check_doc_size_limitsFr7   )r7   Z
errorsOnlyorderedZbypassDocumentValidationrq   Zletc                   s   i | ]}| | qS r@   r@   )r   r   rY   r@   rA   
<dictcomp>6  s    z/_client_batched_op_msg_impl.<locals>.<dictcomp>r   r4   rI   r8   r5   Z
updateModsNnsr+   )r   rQ   r7  r;   ry   r;   r:   r  )r   r  r  r   rJ   _COMMAND_OVERHEADrg   rF  _OP_MSG_OVERHEADzipr9  rm  )%rY   r_  ra  r:  r   r   r;  ro  r   r  r  ri  Zabridged_keysZcommand_abridgedZcommand_len_abridgedZmax_doc_sequences_bytesZns_infore  rf  rj  rl  Ztotal_ops_lengthZtotal_ns_lengthrI  Zreal_op_typeZop_docr'  r   r7  Zns_docZ	ns_lengthZnew_ns_indexZop_doc_encodedZ	op_lengthZns_doc_encodedrK  rN  r@   rq  rA   _client_batched_op_msg_impl  s   













rw  >tuple[bytes, list[Mapping[str, Any]], list[Mapping[str, Any]]]c           
      C  s.   t  }t| ||||||\}}}	| ||fS )zLEncode the next batched client-level bulkWrite
    operation as OP_MSG.
    )r<  rw  rR  )
rY   r_  ra  r:  r   r   r;  re  rf  rS  r@   r@   rA   _client_encode_batched_op_msg  s
   
ry  Ctuple[int, bytes, list[Mapping[str, Any]], list[Mapping[str, Any]]]c                 C  sH   t | |||||\}}}|jjdusJ td||jj\}	}
|	|
||fS )zZCreate the next batched client-level bulkWrite operation
    with OP_MSG, compressed.
    Nr   )ry  r   r   r   )rY   r_  ra  r:  r   r   r   re  rf  r   r   r@   r@   rA   !_client_batched_op_msg_compressed  s   
r{  c                 C  sz   t  }|t |d t| ||||||\}}}	|d t }
|t|
 |d |t|	 |
| ||fS )z=OP_MSG implementation entry point for client-level bulkWrite.rW  r   r   )r<  rA  rX  rw  rG  rB   r   rR  )rY   r_  ra  r:  r   r   r;  re  rf  rN  r   r@   r@   rA   _client_batched_op_msg  s   	




r|  c                 C  sV   d| d< d| v rt | d dd}nd}|jjr"t| |||||S t| |||||S )zOCreate the next batched client-level bulkWrite
    operation using OP_MSG.
    Zadminr   r[  r\  r+   T)r   rg   r   r   r{  r|  )rY   r_  ra  r   r   r:  r@   r@   rA   rd    s   
rd  c           	      C  rQ  )z:Encode the next batched insert, update, or delete command.)r<  _batched_write_command_implrR  )	r'  rX   rY   r   r   r   r;  r(  rS  r@   r@   rA   r2    s   	r2  c                 C  s  |j }|j}|t }	|j}
|t || d |t |t |	 }|t
| |dd |  z	|t|  W n tyO   tddw |	 d }g }d}|D ]`}t|d}t|d|}t||	k}|rtt | }t|t|| |d	ko|	 t| t| |
k}||k}|s|r n|t || |t || || |d	7 }q\|t |	 }|| |t|| d	  || |t||  ||fS )
z(Create a batched OP_QUERY write command.utf8r1  r,   r@  Nr   r   Fr+   )r   r  rt  r  rA  r   encode_ZERO_8_SKIPLIMrB  r   rG  truncate_OP_MAPr   r   rQ   r   rJ   rD  r   rE  r9  _BSONOBJrF  _ZERO_16r   )r'  rX   rY   r   r   r   r;  r   r  Zmax_cmd_sizer  Zcommand_startZ
list_startr(  rI  r   r   rJ  rL  rM  Zenough_dataZenough_documentsrN  r@   r@   rA   r}    sX   




$








r}  c                   @  s   e Zd ZdZdZedjZdZ	d(ddZ
	d)d*ddZdeddfd+ddZd,ddZd-d!d"Zed.d#d$Zed/d&d'ZdS )0_OpReplyz$A MongoDB OP_REPLY response message.)r   r   number_returnedr1   z<iqiir+   r   r;   r   r  r1   r   c                 C  s    || _ t|| _|| _|| _d S r   )r   r   r   r  r1   )r   r   r   r  r1   r@   r@   rA   r  K  s   

z_OpReply.__init__Nr{   user_fieldsr   r:   rk  c                 C  s   | j d@ r|du rtdd|f }d|dd}t|d|| j d@ rdt| j }|d	d |d
 t	j
r@t|d
 ||ddkrVd}t|d
||d|td|d
 |d|| jrk| jgS g S )a  Check the response header from the database, without decoding BSON.

        Check the response for errors and unpack.

        Can raise CursorNotFound, NotPrimaryError, ExecutionTimeout, or
        OperationFailure.

        :param cursor_id: cursor_id we sent to get this response -
            used for raising an informative exception when we get cursor id not
            valid at server response.
        r+   Nz"No cursor id for getMore operationzCursor not found, cursor id: %dr   +   )r]   rO   rV   r,   r]   z$errrV   2   zoperation exceeded time limitzdatabase error: %s)r   r   r   r   ZBSONr1   decode
setdefault
startswithr   ZLEGACY_ERRORr   rg   r   r   )r   r   r  r   ZerrobjZerror_objectZdefault_msgr@   r@   rA   raw_responseQ  s0   


z_OpReply.raw_responseFcodec_optionsr   legacy_responser   list[dict[str, Any]]c                 C  s,   |  | |rt| j|S t| j||S )a  Unpack a response from the database and decode the BSON document(s).

        Check the response for errors and unpack, returning a dictionary
        containing the response data.

        Can raise CursorNotFound, NotPrimaryError, ExecutionTimeout, or
        OperationFailure.

        :param cursor_id: cursor_id we sent to get this response -
            used for raising an informative exception when we get cursor id not
            valid at server response
        :param codec_options: an instance of
            :class:`~bson.codec_options.CodecOptions`
        :param user_fields: Response fields that should be decoded
            using the TypeDecoders from codec_options, passed to
            bson._decode_all_selective.
        )r  r   Z
decode_allr1   _decode_all_selectiver   r   r  r  r  r@   r@   rA   unpack_response}  s   
z_OpReply.unpack_responserN   c                 C  s"   | j |d}| jdksJ |d S )Unpack a command response.r  r+   r   )r  r  )r   r  r   r@   r@   rA   command_response  s   z_OpReply.command_responser
   c                 C  s   t z)Return the bytes of the command response.)NotImplementedErrorr  r@   r@   rA   raw_command_response  r6  z_OpReply.raw_command_responsec                 C  s   dS )+Is the moreToCome bit set on this response?Fr@   r  r@   r@   rA   more_to_come  r6  z_OpReply.more_to_comer   c                 C  s,   |  |\}}}}|dd }| ||||S )z%Construct an _OpReply from raw bytes.   N)UNPACK_FROM)clsr   r   r   rS  r  r1   r@   r@   rA   unpack  s   z_OpReply.unpack)r   r;   r   r;   r  r;   r1   r   )NN)r   r{   r  r   r:   rk  
r   r{   r  r   r  r   r  r   r:   r  r  r   r:   rN   )r:   r
   r:   r   )r   r   r:   r  )rS   r  r  r  r  structStructunpack_fromr  OP_CODEr  r  r9   r  r  r  r  r  classmethodr  r@   r@   r@   rA   r  C  s&    
.

r  c                   @  s   e Zd ZdZdZedjZdZ	dZ
dZdZd)ddZdi fd*ddZdeddfd+ddZd,d d!Zd-d"d#Zed.d$d%Zed/d'd(ZdS )0_OpMsgz"A MongoDB OP_MSG response message.)r   r   r  payload_documentz<IBir   r+   r,   i   r   r;   r  r   c                 C  s   || _ || _d S r   )r   r  )r   r   r  r@   r@   rA   r    s   
z_OpMsg.__init__Nr   r{   r  r   r:   r"  c                 C  s   t t| j|t}|gS )zp
        cursor_id is ignored
        user_fields is used to determine which fields must not be decoded
        )r   Z_decode_selectiver   r  r   )r   r   r  Zinflated_responser@   r@   rA   r    s   	z_OpMsg.raw_responseFr  r   r  r   r  c                 C  s   |rJ t | j||S )a~  Unpack a OP_MSG command response.

        :param cursor_id: Ignored, for compatibility with _OpReply.
        :param codec_options: an instance of
            :class:`~bson.codec_options.CodecOptions`
        :param user_fields: Response fields that should be decoded
            using the TypeDecoders from codec_options, passed to
            bson._decode_all_selective.
        )r   r  r  r  r@   r@   rA   r    s   z_OpMsg.unpack_responserN   c                 C  s   | j |dd S )r  r  r   )r  )r   r  r@   r@   rA   r    s   z_OpMsg.command_responsec                 C  r  r  )r  r  r@   r@   rA   r    s   z_OpMsg.raw_command_responsec                 C  s   t | j| j@ S )r  )r   r   MORE_TO_COMEr  r@   r@   rA   r    s   z_OpMsg.more_to_comer   c                 C  s   |  |\}}}|dkr&|| j@ rtd|d|| jA r&td|d|dkr2td|dt||d kr>td|dd }| ||S )	z#Construct an _OpMsg from raw bytes.r   z+Unsupported OP_MSG flag checksumPresent: 0xxzUnsupported OP_MSG flags: 0xz#Unsupported OP_MSG payload type: 0x   z$Unsupported OP_MSG reply: >1 sectionN)r  CHECKSUM_PRESENTr   r  rJ   )r  r   r   Zfirst_payload_typeZfirst_payload_sizer  r@   r@   rA   r    s   


z_OpMsg.unpack)r   r;   r  r   )r   r{   r  r   r:   r"  r  r  )r:   r   r  )r   r   r:   r  )rS   r  r  r  r  r  r  r  r  r  r  r  EXHAUST_ALLOWEDr  r  r9   r  r  r  r  r  r  r  r@   r@   r@   rA   r    s.    


r  z5dict[int, Callable[[bytes], Union[_OpReply, _OpMsg]]]_UNPACK_REPLYc                   @  sj   e Zd ZdZdZdZdZd8dd Zd9d#d$Zd:d%d&Z	d;d)d*Z
d<d-d.Z	/d=d>d2d3Z	/d=d?d6d7ZdS )@_QueryzA query operation.)r   dbru   ntoskiprC   fieldsr  rE   ry   rz   r   r}   r~   r   clientr   _as_commandexhaustNr   r;   r  rQ   ru   r  rC   rZ   r  r   r  r   rE   r!   ry   rz   r}   r%   r~   r   r   r  r)   r   r   r  r   c                 C  sp   || _ || _|| _|| _|| _|| _|| _|| _|| _|	| _	|
| _
|| _|| _|| _|| _d| _d | _|| _d S )Nr   )r   r  ru   r  rC   r  r  rE   r}   ry   rz   r~   r   r  r   r   r  r  )r   r   r  ru   r  rC   r  r  rE   ry   rz   r}   r~   r   r  r   r  r@   r@   rA   r  *  s$   
z_Query.__init__r:   r  c                 C  
   d | _ d S r   r  r  r@   r@   rA   resetP     
z_Query.resetc                 C     | j  d| j S NrZ  r  ru   r  r@   r@   rA   r'  S     z_Query.namespacer   r(   c                 C  sR   d}| j sd}n|jdkrd}n| jjstd| jj|jf || j| j |S )NFTrb   zDread concern level of %s is not valid with a max wire version of %d.)	r  r   r}   Zok_for_legacyr   r   validate_sessionr  r   )r   r   Zuse_find_cmdr@   r@   rA   use_commandV  s   
z_Query.use_commandr   rN   c                 C     || j f| _d S r   r  r  r   r   r@   r@   rA   update_commandf     z_Query.update_commandFapply_timeouttuple[dict[str, Any], str]c                 C  s   | j dur| j S d| jv }t| j| j| j| j| j| j| j| j	| j
| j| j}|r/d| _d|i}|| | jrN| j|d| j| |sN| jjsN| j|| ||| j| j |ra|j| j|d || jf| _ | j S )z.Return a find command document for this query.Nr   explainFr   )r  rC   r   ru   r  r  ry   rz   r   r}   r~   r   r   r   add_server_api	_apply_torE   r   Z_update_read_concernsend_cluster_timer  r  r  )r   r   r  r  r   r@   r@   rA   
as_commandi  s:   


z_Query.as_commanduse_cmdr   c              
   C  s   || _ |jr| jdB }n| j}|  }| j}|r5| |d }td|| j|| j|j	d\}}}	}
|||	fS | j
dkr<dp>| j
}| jrN|rKt| j|}n| j}|jr]t|tsXJ t||}t||| j|||rhdn| j| j|j	dS )z:Get a query message, possibly setting the secondaryOk bit.r   r   r   r+   r,   N)rE   rH   r   r'  rC   r  r   r  r  r   rz   ry   rt   Z	is_mongos
isinstancer	   rK   r   r  r  )r   rE   r   r  r   rs  rC   r   r   r   rS  	ntoreturnr@   r@   rA   get_message  sF   

z_Query.get_message) r   r;   r  rQ   ru   rQ   r  r;   rC   rZ   r  r   r  r   rE   r!   ry   r;   rz   r;   r}   r%   r~   r   r   r   r  r)   r   r   r  r   r:   r  r:   rQ   r   r(   r:   r   r   rN   r:   r  r   r   r(   r  r   r:   r  )rE   r!   r   r(   r  r   r:   r   )rS   r  r  r  r  conn_mgrr   r  r  r'  r  r  r  r  r@   r@   r@   rA   r    s    

&


(r  c                   @  sf   e Zd ZdZdZdZd4ddZd5ddZd6dd Zd7d#d$Z	d8d'd(Z
	)d9d:d,d-Z	)d9d;d1d2Zd3S )<_GetMorezA getmore operation.)r  ru   r  r   r   r  rE   r   r  r  r  r  rq   r   r  rQ   ru   r  r;   r   r  r   rE   r!   r   r   r  r)   r   r{   r  r   r  r   rq   c                 C  sR   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	d | _
|| _|| _d S r   )r  ru   r  r   r  rE   r   r  r   r  r  r  rq   )r   r  ru   r  r   r  rE   r   r  r   r  r  rq   r@   r@   rA   r    s   
z_GetMore.__init__r:   r  c                 C  r  r   r  r  r@   r@   rA   r    r  z_GetMore.resetc                 C  r  r  r  r  r@   r@   rA   r'    r  z_GetMore.namespacer   r(   c                 C  s2   d}| j sd}n|jdkrd}|| j| j |S )NFTrb   )r  r   r  r  r   )r   r   r  r@   r@   rA   r    s   
z_GetMore.use_commandr   rN   c                 C  r  r   r  r  r@   r@   rA   r    r  z_GetMore.update_commandFr  r  c                 C  s   | j dur| j S t| j| j| j| j| j|}| jr#| j|d| j	| |
| ||| j| j |r;|j| jdd || jf| _ | j S )z1Return a getMore command document for this query.NFr  )r  r   r   ru   r  r   rq   r   r  rE   r  r  r  r  r  )r   r   r  r   r@   r@   rA   r    s$   

z_GetMore.as_commanddummy0r  0Union[tuple[int, bytes, int], tuple[int, bytes]]c                 C  sv   |   }|j}|r2| |d }| jr| jrtj}nd}t||| jd| j	|jd\}}	}
}||	|
fS t
|| j| j|S )zGet a getmore message.r   Nr  )r'  r   r  r  r  r  r  r   r  r  r   r  r   )r   r  r   r  rs  r   rC   r   r   r   r   rS  r@   r@   rA   r  %  s   
z_GetMore.get_messageN)r  rQ   ru   rQ   r  r;   r   r;   r  r   rE   r!   r   r   r  r)   r   r{   r  r   r  r   rq   r   r  r  r  r  r   r  )r  r   r   r(   r  r   r:   r  )rS   r  r  r  r  r   r  r  r'  r  r  r  r  r@   r@   r@   rA   r    s    




r  c                         e Zd Zd fddZ  ZS )_RawBatchQueryr   r(   r:   r   c                   (   t  | |jdkrdS | jsdS dS Nrb   TFr   r  r   r  r   r   r!  r@   rA   r  ;     
z_RawBatchQuery.use_commandr  rS   r  r  r  r.  r@   r@   r!  rA   r  :      r  c                      r  )_RawBatchGetMorer   r(   r:   r   c                   r  r  r  r  r!  r@   rA   r  G  r  z_RawBatchGetMore.use_commandr  r  r@   r@   r!  rA   r  F  r  r  c                   @  sP   e Zd ZU dZded< dd	d
ZedddZdddZdddZ	dddZ
dS )_CursorAddresszEThe server address (host, port) of a cursor, with namespace property.r   _CursorAddress__namespacer  r&   r'  rQ   r:   c                 C  s   t | |}||_|S r   )tuple__new__r  )r  r  r'  r   r@   r@   rA   r  W  s   z_CursorAddress.__new__c                 C  r  )zThe namespace this cursor.)r  r  r@   r@   rA   r'  \  r	  z_CursorAddress.namespacer;   c                 C  s   g | | j R  S r   )r  __hash__r  r@   r@   rA   r  a  s   z_CursorAddress.__hash__otherobjectr   c                 C  s*   t |trt| t|ko| j|jkS tS r   )r  r  r  r'  NotImplementedr   r  r@   r@   rA   __eq__f  s   
z_CursorAddress.__eq__c                 C  s
   | |k S r   r@   r  r@   r@   rA   __ne__k  r  z_CursorAddress.__ne__N)r  r&   r'  rQ   r:   r  r  r  )r  r  r:   r   )rS   r  r  r  __annotations__r  r  r'  r  r  r  r@   r@   r@   rA   r  R  s   
 


r  r  )rC   rD   rE   r!   r:   rD   )rL   rM   r:   rN   )rX   rQ   rY   rZ   r[   rZ   r:   rN   )NNN)ru   rQ   rC   rZ   rv   rw   rx   r;   ry   r;   rz   r{   r|   r{   r}   r%   r~   r   r   r   r   r   r:   rN   )r   r{   ru   rQ   rz   r{   r   r{   rq   r   r   r(   r:   rN   )rX   r;   r   r   r   r   r:   r   )rX   r;   r   r   r:   r   )r   r;   rY   rZ   r   rQ   r   r   r   r   r:   r   )r   r;   rY   rZ   r   rQ   r   r   r   r   r   r   r:   r   )r   r;   rY   rZ   r   rQ   r   r   r   r   r:   r   r   )r   r;   rY   rD   r   rQ   rE   r   r   r   r   r   r:   r   )r|   r;   r   rQ   r   r;   r   r;   r   rZ   r   r   r   r   r:   r   )r|   r;   r   rQ   r   r;   r   r;   r   rZ   r   r   r   r   r   r   r:   r   )r|   r;   r   rQ   r   r;   r   r;   r   rZ   r   r   r   r   r:   r   )r|   r;   r   rQ   r   r;   r   r;   r   rZ   r   r   r   r   r   r   r:   r   )r   rQ   r   r;   r   r;   r:   r   )
r   rQ   r   r;   r   r;   r   r   r:   r   )r   rQ   r   r;   r   r;   r:   r   )
r   rQ   r   r;   r   r;   r   r   r:   r   )rX   rQ   r7  r;   r8  r;   r:   r
   )rX   r;   rY   rZ   r   r"  r:  r   r   r   r   r  r;  r<  r:   r=  )rX   r;   rY   rZ   r   r"  r:  r   r   r   r   r  r:   rP  )rX   r;   rY   rZ   r   r"  r:  r   r   r   r   r  r:   rU  )r'  rQ   rX   r;   rY   rD   r   r"  r   r   r   r  r:   rU  )ri  r   rj  rk  rl  rk  r:  r   r;  r<  r:   r;   )rY   rZ   r_  r`  ra  rb  r:  r   r   r   r   r^  r;  r<  r:   rn  )rY   rZ   r_  r`  ra  rb  r:  r   r   r   r   r^  r:   rx  )rY   rZ   r_  r`  ra  rb  r:  r   r   r   r   r^  r:   rz  )rY   rD   r_  r`  ra  rb  r   r   r   r^  r:   rz  )r'  rQ   rX   r;   rY   rD   r   r"  r   r   r   r  r:   rP  )r'  rQ   rX   r;   rY   rD   r   r"  r   r   r   r  r;  r<  r:   r=  )r  
__future__r   r   r<   r  ior   r<  typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   Z
bson.int64r   Zbson.raw_bsonr   r   r   r   Zpymongo.hellor   Zpymongo.monitoringr   Zpymongor   Z_use_cImportErrorZpymongo.errorsr   r   r   r   r   r   r   r   Zpymongo.read_preferencesr    r!   Zpymongo.compression_supportr"   r#   r$   Zpymongo.read_concernr%   Zpymongo.typingsr&   r'   r(   r)   r*   r?   r>   rt  Z_INSERTZ_UPDATEZ_DELETEZ_EMPTYr  r  r  r   rX  r  r  r   r9   r  rB   rK   rU   rW   rj   r   r   r   r   r  packr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Z_query_messager   r   r   r   r   Z_get_more_messager   rC  r   r  r/  r9  r5  rO  rT  rV  rY  r&  r^  ru  rm  rw  ry  r{  r|  rd  r2  r}  r  r  r  r  r  r  r  r  r  r  r  r@   r@   r@   rA   <module>   s,  ,(
	




%

7


 	 
^7D=0vMqU 8u