o
    sDi                     @  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]d dwdxZ^eXdyjYZ_eXdzjYZ`eXd{jYZadddZbdddZcdddZde$rbe#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 deedf 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updatesdeletesops)insertupdatedelete	bulkWritereplace)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 rB   rB   M/home/alumno/antzosa8961/venv/lib/python3.10/site-packages/pymongo/message.py_randintt   s   rD   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    SECONDARY_PREFERREDlen)rE   rG   rJ   rK   rB   rB   rC   _maybe_add_read_preferencey   s   rN   	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__rO   rB   rB   rC   _convert_exception   s   rX   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.
    )rR   coderS   )rT   rY   rU   rV   rW   rB   rB   rC   _convert_client_bulk_exception   s   rZ   	operationrT   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_   rR   err wtimeout@   T)rR   rY   errInfowriteConcernErrorrY      )indexrY   rR   re   writeErrorsr5   r1   r6   upserted)rh   _idupdatedExistingFr2   urk   q)getrM   )	r[   r\   r^   affectedresrR   errorr6   rk   rB   rB   rC   _convert_write_result   s.   


	rs   rg             )tailableoplogReplaynoCursorTimeout	awaitDataallowPartialResultsfiltersorthintcommentmaxScan	maxTimeMSmaxmin	returnKeyshowRecordIdsnapshot)rH   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.findrH   c                 S  s,   g | ]\}}|t v rt | |fn||fqS rB   )
_MODIFIERS).0keyvalrB   rB   rC   
<listcomp>   s    z%_gen_find_command.<locals>.<listcomp>$explainrI   r|   r   r   r   r   TsingleBatchr+   	batchSizereadConcernr   NallowDiskUsec                   s    g | ]\}} |@ r|d fqS )TrB   )r   optr   r   rB   rC   r   
  s     )r6   itemspopabslevelin_transactionrK   _OPTIONS)r   rE   r   r   r   r   r   r   r   r   r   cmdrB   r   rC   _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.)getMore
collectionr   Nr   	   r   )max_wire_version)r   r   r   r   r   r   r   rB   rB   rC   _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  )compressrD   _pack_compression_header_COMPRESSION_HEADER_SIZErM   compressor_id)r[   r   r   
compressed
request_idheaderrB   rB   rC   	_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.
    rt   r   )rD   _pack_headerrM   )r[   r   ridmessagerB   rB   rC   __pack_message<  s   r   z<iz<IBz<Bflags
identifierdocs!Optional[list[Mapping[str, Any]]]optsCodecOptions[Any]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   rB   rC   r   `  s    z%_op_msg_no_header.<locals>.<listcomp>c                 s      | ]}t |V  qd S NrM   r   rB   rB   rC   	<genexpr>a      z$_op_msg_no_header.<locals>.<genexpr>   c                 s  r   r   r   r   rB   rB   rC   r   d  r   r-   )	r   _pack_op_msg_flags_typerM   
_pack_byter   sum	_pack_intr   join)r   r\   r   r   r   encoded
flags_type
total_sizemax_doc_sizetype_onecstringencoded_docssizeencoded_sizer   rB   r   rC   _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   r\   r   r   r   r   msgr   max_bson_sizer   rB   rB   rC   _op_msg_compressedk  s   	r   c           
      C  s0   t | ||||\}}}td|\}}	||	||fS )z*Internal compressed OP_MSG message helper.r   )r   r   )
r   r\   r   r   r   r   r   r   r   
op_messagerB   rB   rC   _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.$dbNrI   rb   )	rJ   rK   nextiter
_FIELD_MAPr   KeyErrorr   r   )	r   r\   r   rG   r   r   namer   r   rB   rB   rC   _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   r   rM   r   r   bsonr   )
r   r   r   r   r   r   r   r   efsr   rB   rB   rC   _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   rB   rB   rC   _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   rB   rB   rC   _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   rB   rB   rC   _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   rB   rB   rC   _get_more_impl  s   r	  c                 C  s   t dt| |||S )z+Internal compressed getMore message helper.  )r   r	  r   r   r   r   rB   rB   rC   _get_more_compressed  s   r  c                 C  s   t dt| ||S )z Internal getMore message helper.r
  )r   r	  r  rB   rB   rC   _get_more_uncompressed  s   r  c                 C  s   |r	t | |||S t| ||S )zGet a **getMore** message.)r  r  r  rB   rB   rC   	_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_namerT   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  enabled_for_commandsr  r   r   r  datetimenowr  r   boolcompression_contextr   r  r  	selfr  r  r   r  r  r   r  r  rB   rB   rC   __init__P  s   
z_BulkWriteContextBase.__init__r<   c                 C     | j jS )z#A proxy for SockInfo.max_bson_size.)r   r   r!  rB   rB   rC   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.rt   )r   r   max_message_sizer$  rB   rB   rC   r&  m  s   z&_BulkWriteContextBase.max_message_sizec                 C  r#  )z*A proxy for SockInfo.max_write_batch_size.)r   max_write_batch_sizer$  rB   rB   rC   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$  rB   rB   rC   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  publish_command_successr   r   addressserver_connection_idr  
service_idr  )r!  r   r+  r,  rB   rB   rC   _succeed     
z_BulkWriteContextBase._succeedfailurec                 C  r/  )zPublish a CommandFailedEvent.r0  N)	r  publish_command_failurer   r   r2  r3  r  r4  r  )r!  r   r7  r,  rB   rB   rC   _fail  r6  z_BulkWriteContextBase._failNr  rT   r  rT   r   r(   r  r=   r  r   r   r   r  r=   r  r   r<   r=   )r   r=   r+  r*   r,  r-  r<   r.  )r   r=   r7  r*   r,  r-  r<   r.  )rV   
__module____qualname____doc__	__slots__r"  propertyr   r&  r'  r)  r5  r9  rB   rB   rB   rC   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.rB   r  rT   r  r   r(   r  r=   r  r   r   r   r  r  r   c	           	   
     s   t  |||||||| d S r   superr"  r   rU   rB   rC   r"    s   z_BulkWriteContext.__init__r   rF   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_sendrB   rB   rC   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   r2  r3  r  r4  )r!  r   r   r   rB   rB   rC   _start  s   
	z_BulkWriteContext._startr:  )r   rF   r   rE  r<   rF  )r   rF   r   r=   r   rE  r<   rF   	rV   r<  r=  r>  r?  r"  rL  rO  __classcell__rB   rB   rD  rC   rA    s    
rA  c                   @  s(   e Zd ZdZddd	ZedddZdS )_EncryptedBulkWriteContextrB   r   rF   r   rE  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 )NrG  rH  r/   r   r   )	r  _encode_batched_write_commandr  r  r   rh   r   
memoryviewr   )r!  r   r   rJ  r   rK  	cmd_startoutgoingrB   rB   rC   rL    s   

z(_EncryptedBulkWriteContext.batch_commandr=   c                 C  s   t S )z Reduce the batch splitting size.)_MAX_SPLIT_SIZE_ENCr$  rB   rB   rC   r)       z)_EncryptedBulkWriteContext.max_split_sizeN)r   rF   r   rE  r<   rS  r;  )rV   r<  r=  r?  rL  r@  r)  rB   rB   rB   rC   rR    s
    
rR  doc_sizemax_sizer
   c                 C  s&   | dkrt d||f t | d)z-Internal helper for raising DocumentTooLarge.r5   zfBSON document too large (%d bytes) - the connected server supports BSON document sizes up to %d bytes.z command document too large)r   )r[   r[  r\  rB   rB   rC   _raise_document_too_large  s   	r]  i    rE  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   rM   listr   keysr]  appendseekr   )r[   r\   r   r^  r   r   r_  r   r'  r&  r   size_locationrK  idxr   value
doc_lengthnew_message_sizedoc_too_largeunacked_doc_too_largewrite_oplengthrB   rB   rC   _batched_op_msg_impl  sL   








ru  %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`  ru  getvalue)	r[   r\   r   r^  r   r   r_  rK  _rB   rB   rC   _encode_batched_op_msgE  s   rz  *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   )rz  r   r  r   )
r[   r\   r   r^  r   r   r   rK  r   r   rB   rB   rC   _batched_op_msg_compressedZ  s   
r|  c           
      C  sv   t  }|t |d t| ||||||\}}|d t }	|t|	 |d |t| |	| |fS )z"OP_MSG implementation entry point.         r   r   )r`  re  _ZERO_64ru  rk  rD   r   rx  )
r[   r\   r   r^  r   r   r_  rK  rt  r   rB   rB   rC   _batched_op_msgl  s   	



r  rJ  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  ro   r   r  r|  r  )rJ  r[   r\   r   r   r   r^  rB   rB   rC   rI    s   rI  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.rB   r  rT   r  r   r(   r  r=   r  r   r   r   r  r   c              
     s   t  ||||||d| d S )Nr   rB  )r!  r  r  r   r  r  r   r  rD  rB   rC   r"    s   
z _ClientBulkWriteContext.__init__r   rF   
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 )NrH  )_client_do_batched_op_msgr  r   )r!  r   r  r  r   r   to_send_ops
to_send_nsrB   rB   rC   rL    s   z%_ClientBulkWriteContext.batch_commandr   op_docsrE  ns_docsc              	   C  s<   ||d< ||d< | j || j|| jj| jj| j| jj |S )rM  r4   nsInfo)r  rN  r  r   r2  r3  r  r4  )r!  r   r   r  r  rB   rB   rC   rO    s   	z_ClientBulkWriteContext._start)r  rT   r  rT   r   r(   r  r=   r  r   r   r   r  r   )r   rF   r  r  r  r  r<   r  )
r   rF   r   r=   r  rE  r  rE  r<   rF   rP  rB   rB   rD  rC   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   rb  r/   rc  s   ops s   nsInfo )re  rf  rk  r   )r  r  r  r^  r_  r   rl  
op_encodedresume_locationrt  
ns_encodedrB   rB   rC   _client_construct_op_msg  s2   











r  r  r  r  r  <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  rT   r[  r=   r   r<   r.  c                 S  s   ||krt | || d S d S r   )r]  )r  r[  r   rB   rB   rC   _check_doc_size_limits  s   z;_client_batched_op_msg_impl.<locals>._check_doc_size_limitsFr8   )r8   
errorsOnlyorderedbypassDocumentValidationr   letc                   s   i | ]}| | qS rB   rB   )r   r   r\   rB   rC   
<dictcomp>6  s    z/_client_batched_op_msg_impl.<locals>.<dictcomp>r   r5   rK   r9   r6   
updateModsNnsr+   )r  rT   r[  r=   r   r=   r<   r.  )r   r'  r&  r   rM   _COMMAND_OVERHEADro   rj  _OP_MSG_OVERHEADzipr]  r  )%r\   r  r  r^  r   r   r_  r  r   r'  r&  r  abridged_keyscommand_abridgedcommand_len_abridgedmax_doc_sequences_bytesns_infor  r  r  r  total_ops_lengthtotal_ns_lengthrm  real_op_typeop_docrJ  r  r[  ns_doc	ns_lengthnew_ns_indexop_doc_encoded	op_lengthns_doc_encodedrp  rt  rB   r  rC   _client_batched_op_msg_impl  s   













r  >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`  r  rx  )
r\   r  r  r^  r   r   r_  r  r  ry  rB   rB   rC   _client_encode_batched_op_msg  s
   
r  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   )r  r   r  r   )r\   r  r  r^  r   r   r   r  r  r   r   rB   rB   rC   !_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.r}  r   r   )r`  re  r~  r  rk  rD   r   rx  )r\   r  r  r^  r   r   r_  r  r  rt  r   rB   rB   rC   _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.
    adminr   r  r  r+   T)r  ro   r   r  r  r  )r\   r  r  r   r   r^  rB   rB   rC   r    s   
r  c           	      C  rw  )z:Encode the next batched insert, update, or delete command.)r`  _batched_write_command_implrx  )	rJ  r[   r\   r   r   r   r_  rK  ry  rB   rB   rC   rU    s   	rU  c                 C  s  |j }|j}|t }	|j}
|t || d |t |t |	 }|t
| |dd z	|t|  W n tyK   tddw |	 d }g }d}|D ]`}t|d}t|d|}t||	k}|rtt | }t|t|| |d	ko|	 t| t| |
k}||k}|s|r n|t || |t || || |d	7 }qX|t |	 }|| |t|| d	  || |t||  ||fS )
z(Create a batched OP_QUERY write command.utf8rT  r,   rd  Nr   r   Fr+   )r   r'  r  r)  re  r  encode_ZERO_8_SKIPLIMrf  r   rk  _OP_MAPr   r   rT   r   rM   rh  r   ri  r]  _BSONOBJrj  _ZERO_16r   )rJ  r[   r\   r   r   r   r_  r   r'  max_cmd_sizer)  command_start
list_startrK  rm  r   r   rn  rq  rs  enough_dataenough_documentsrt  rB   rB   rC   r    sV   




$








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   bytes | memoryviewc                 C  s    || _ t|| _|| _|| _d S r   )r   r   r   r  r1   )r!  r   r   r  r1   rB   rB   rC   r"  I  s   

z_OpReply.__init__Nr   user_fieldsr   r<   list[bytes | memoryview]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`   rR   rY   r,   r`   z$errrY   2   zoperation exceeded time limitzdatabase error: %s)r   r   r   r   BSONr1   decode
setdefault
startswithr   LEGACY_ERRORr   ro   r   r   )r!  r   r  r   errobjerror_objectdefault_msgrB   rB   rC   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   
decode_allr1   _decode_all_selectiver!  r   r  r  r  rB   rB   rC   unpack_response}  s   
z_OpReply.unpack_responserQ   c                 C  s"   | j |d}| jdksJ |d S )Unpack a command response.r  r+   r   )r  r  )r!  r  r   rB   rB   rC   command_response  s   z_OpReply.command_responser
   c                 C  s   t z)Return the bytes of the command response.)NotImplementedErrorr$  rB   rB   rC   raw_command_response  rZ  z_OpReply.raw_command_responsec                 C  s   dS )+Is the moreToCome bit set on this response?FrB   r$  rB   rB   rC   more_to_come  rZ  z_OpReply.more_to_comer   c                 C  s,   |  |\}}}}|dd }| ||||S )z%Construct an _OpReply from raw bytes.   N)UNPACK_FROM)clsr   r   r   ry  r  r1   rB   rB   rC   unpack  s   z_OpReply.unpack)r   r=   r   r=   r  r=   r1   r  )NN)r   r   r  r   r<   r  
r   r   r  r   r  r   r  r  r<   r  r  r   r<   rQ   )r<   r
   r<   r  )r   r  r<   r  )rV   r<  r=  r>  r?  structStructunpack_fromr  OP_CODEr"  r  r;   r  r  r  r@  r  classmethodr  rB   rB   rB   rC   r  A  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  rB   rB   rC   r"    s   
z_OpMsg.__init__Nr   r   r  r   r<   rE  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   _decode_selectiver   r  r   )r!  r   r  inflated_responserB   rB   rC   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  rB   rB   rC   r    s   z_OpMsg.unpack_responserQ   c                 C  s   | j |dd S )r  r  r   )r  )r!  r  rB   rB   rC   r    s   z_OpMsg.command_responsec                 C  r(  r  )r  r$  rB   rB   rC   r    s   z_OpMsg.raw_command_responsec                 C  s   t | j| j@ S )r  )r  r   MORE_TO_COMEr$  rB   rB   rC   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  rM   )r  r   r   first_payload_typefirst_payload_sizer  rB   rB   rC   r    s   


z_OpMsg.unpack)r   r=   r  r  )r   r   r  r   r<   rE  r  r  )r<   r  r  )r   r  r<   r  )rV   r<  r=  r>  r?  r  r  r  r  r  r  r  EXHAUST_ALLOWEDr"  r  r;   r  r  r  r@  r  r  r  rB   rB   rB   rC   r    s.    


r  zBdict[int, Callable[[bytes | memoryview], 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   dbr   ntoskiprE   fieldsr  rG   r   r   r   r   r   r   clientr   _as_commandexhaustNr   r=   r   rT   r   r  rE   r]   r  r   r  r   rG   r!   r   r   r   r%   r   r   r   r  r)   r   r   r  r  c                 C  sp   || _ || _|| _|| _|| _|| _|| _|| _|| _|	| _	|
| _
|| _|| _|| _|| _d| _d | _|| _d S )Nr   )r   r   r   r  rE   r  r  rG   r   r   r   r   r   r  r   r   r  r  )r!  r   r   r   r  rE   r  r  rG   r   r   r   r   r   r  r   r  rB   rB   rC   r"  *  s$   
z_Query.__init__r<   r.  c                 C  
   d | _ d S r   r  r$  rB   rB   rC   resetP     
z_Query.resetc                 C     | j  d| j S Nr  r   r   r$  rB   rB   rC   rJ  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 )NFTrg   zDread concern level of %s is not valid with a max wire version of %d.)	r  r   r   ok_for_legacyr   r   validate_sessionr  r   )r!  r   use_find_cmdrB   rB   rC   use_commandV  s   
z_Query.use_commandr   rQ   c                 C     || j f| _d S r   r   r  r!  r   rB   rB   rC   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  rE   r   r   r  r  r   r   r   r   r   r   r   r   add_server_api	_apply_torG   r   _update_read_concernsend_cluster_timer  r  r   )r!  r   r  r  r   rB   rB   rC   
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)rG   rJ   r   rJ  rE   r  r   r   r  r  r   r   r   	is_mongos
isinstancer	   rN   r  r  r  )r!  rG   r   r   r   r  rE   r   r   r   ry  	ntoreturnrB   rB   rC   get_message  sF   

z_Query.get_message) r   r=   r   rT   r   rT   r  r=   rE   r]   r  r   r  r   rG   r!   r   r=   r   r=   r   r%   r   r   r   r   r  r)   r   r   r  r  r<   r.  r<   rT   r   r(   r<   r  r   rQ   r<   r.  r   r   r(   r  r  r<   r  )rG   r!   r   r(   r   r  r<   r   )rV   r<  r=  r>  r?  conn_mgrr   r"  r  rJ  r  r  r  r%  rB   rB   rB   rC   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   r   r$  r   r   r  rG   r   r  r+  r  r  r   r   r   rT   r   r$  r=   r   r  r   rG   r!   r   r   r  r)   r   r   r+  r   r  r  r   c                 C  sR   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	d | _
|| _|| _d S r   )r   r   r$  r   r  rG   r   r  r   r+  r  r  r   )r!  r   r   r$  r   r  rG   r   r  r   r+  r  r   rB   rB   rC   r"    s   
z_GetMore.__init__r<   r.  c                 C  r  r   r  r$  rB   rB   rC   r    r	  z_GetMore.resetc                 C  r
  r  r  r$  rB   rB   rC   rJ    r  z_GetMore.namespacer   r(   c                 C  s2   d}| j sd}n|jdkrd}|| j| j |S )NFTrg   )r  r   r  r  r   )r!  r   r   rB   rB   rC   r    s   
z_GetMore.use_commandr   rQ   c                 C  r  r   r  r  rB   rB   rC   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   r   r$  r   r   r   r  rG   r  r  r  r  r   )r!  r   r  r   rB   rB   rC   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!  )rJ  r  r  r+  r  r  r  r   r   r  r  r$  r   )r!  r-  r   r   r  r   rE   r   r   r   r   ry  rB   rB   rC   r%  %  s   
z_GetMore.get_messageN)r   rT   r   rT   r$  r=   r   r=   r  r   rG   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.  )rV   r<  r=  r>  r?  r   r"  r  rJ  r  r  r  r%  rB   rB   rB   rC   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 Nrg   TFrC  r  r   r  r!  r   rD  rB   rC   r  ;     
z_RawBatchQuery.use_commandr(  rV   r<  r=  r  rQ  rB   rB   rD  rC   r0  :      r0  c                      r/  )_RawBatchGetMorer   r(   r<   r  c                   r1  r2  r3  r4  rD  rB   rC   r  G  r5  z_RawBatchGetMore.use_commandr(  r6  rB   rB   rD  rC   r8  F  r7  r8  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__namespacer2  r&   rJ  rT   r<   c                 C  s   t | |}||_|S r   )tuple__new__r:  )r  r2  rJ  r!  rB   rB   rC   r<  W  s   z_CursorAddress.__new__c                 C  r(  )zThe namespace this cursor.)r:  r$  rB   rB   rC   rJ  \  r*  z_CursorAddress.namespacer=   c                 C  s   g | | j R  S r   )r:  __hash__r$  rB   rB   rC   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#  r9  r;  rJ  NotImplementedr!  r>  rB   rB   rC   __eq__f  s   
z_CursorAddress.__eq__c                 C  s
   | |k S r   rB   rA  rB   rB   rC   __ne__k  r	  z_CursorAddress.__ne__N)r2  r&   rJ  rT   r<   r9  r'  r;  )r>  r?  r<   r  )rV   r<  r=  r>  __annotations__r<  r@  rJ  r=  rB  rC  rB   rB   rB   rC   r9  R  s   
 


r9  .r;  )rE   rF   rG   r!   r<   rF   )rO   rP   r<   rQ   )r[   rT   r\   r]   r^   r]   r<   rQ   )NNN)r   rT   rE   r]   r   r   r   r=   r   r=   r   r   r   r   r   r%   r   r   r   r   r   r   r<   rQ   )r   r   r   rT   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   r=   r\   r]   r   rT   r   r   r   r   r<   r   )r   r=   r\   r]   r   rT   r   r   r   r   r   r   r<   r   )r   r=   r\   r]   r   rT   r   r   r   r   r<   r   r   )r   r=   r\   rF   r   rT   rG   r   r   r   r   r   r<   r   )r   r=   r   rT   r   r=   r   r=   r   r]   r   r   r   r   r<   r   )r   r=   r   rT   r   r=   r   r=   r   r]   r   r   r   r   r   r   r<   r   )r   r=   r   rT   r   r=   r   r=   r   r]   r   r   r   r   r<   r   )r   r=   r   rT   r   r=   r   r=   r   r]   r   r   r   r   r   r   r<   r   )r   rT   r   r=   r   r=   r<   r   )
r   rT   r   r=   r   r=   r   r   r<   r   )r   rT   r   r=   r   r=   r<   r   )
r   rT   r   r=   r   r=   r   r   r<   r   )r[   rT   r[  r=   r\  r=   r<   r
   )r[   r=   r\   r]   r   rE  r^  r  r   r   r   rA  r_  r`  r<   ra  )r[   r=   r\   r]   r   rE  r^  r  r   r   r   rA  r<   rv  )r[   r=   r\   r]   r   rE  r^  r  r   r   r   rA  r<   r{  )rJ  rT   r[   r=   r\   rF   r   rE  r   r   r   rA  r<   r{  )r  r   r  r  r  r  r^  r  r_  r`  r<   r=   )r\   r]   r  r  r  r  r^  r  r   r   r   r  r_  r`  r<   r  )r\   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\   rF   r  r  r  r  r   r   r   r  r<   r  )rJ  rT   r[   r=   r\   rF   r   rE  r   r   r   rA  r<   rv  )rJ  rT   r[   r=   r\   rF   r   rE  r   r   r   rA  r_  r`  r<   ra  )r>  
__future__r   r  r>   r  ior   r`  typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   
bson.int64r   bson.raw_bsonr   r   r   r   pymongo.hellor   pymongo.monitoringr   pymongor   _use_cImportErrorpymongo.errorsr   r   r   r   r   r   r   r   pymongo.read_preferencesr    r!   pymongo.compression_supportr"   r#   r$   pymongo.read_concernr%   pymongo.typingsr&   r'   r(   r)   r*   rA   r@   r  _INSERT_UPDATE_DELETE_EMPTYr  r  r  r  r~  r  r  r   r;   rD  rD   rN   rX   rZ   rs   r   r   r   r   r  packr   r   r   r   r   r   r   r   r   r   r   r   r   r  r  _query_messager  r  r	  r  r  _get_more_messager  rg  r  rA  rR  r]  rY  ru  rz  r|  r  rI  r  r  r  r  r  r  r  r  rU  r  r  r  r  r  r  r  r,  r0  r8  r;  r9  rB   rB   rB   rC   <module>   s,  ,(
	




%

7

 	 
^7D=0vKsU 8u