o
    "`^h3O                     @   s   d Z ddlmZ ddlmZ ddlmZ dZdZdZ	G dd	 d	e
ZG d
d deZG dd deZG dd deZG dd deZG dd deZG dd dZd#ddZG dd dZG dd dZG dd dZG dd dZG d d! d!Zd"S )$zBinary Event Stream Decoding    )crc32)unpack)EventStreamError   i   i   c                   @   s   e Zd ZdZdS )ParserErrorz,Base binary flow encoding parsing exception.N)__name__
__module____qualname____doc__ r   r   R/home/air/shanriGPT/back/venv/lib/python3.10/site-packages/botocore/eventstream.pyr      s    r   c                           e Zd ZdZ fddZ  ZS )DuplicateHeaderz$Duplicate header found in the event.c                    s   d| d}t  | d S )NzDuplicate header present: ""super__init__)selfheadermessage	__class__r   r   r   #   s   zDuplicateHeader.__init__r   r   r	   r
   r   __classcell__r   r   r   r   r           r   c                       r   )InvalidHeadersLengthz*Headers length is longer than the maximum.c                        d| dt  }t | d S )NzHeader length of  exceeded the maximum of )_MAX_HEADERS_LENGTHr   r   r   lengthr   r   r   r   r   +      zInvalidHeadersLength.__init__r   r   r   r   r   r   (   r   r   c                       r   )InvalidPayloadLengthz*Payload length is longer than the maximum.c                    r   )NzPayload length of r   )_MAX_PAYLOAD_LENGTHr   r   r   r   r   r   r   3   r!   zInvalidPayloadLength.__init__r   r   r   r   r   r"   0   r   r"   c                       r   )ChecksumMismatchz8Calculated checksum did not match the expected checksum.c                    s$   d|dd|d}t  | d S )NzChecksum mismatch: expected 0x08xz, calculated 0xr   )r   expected
calculatedr   r   r   r   r   ;   s   zChecksumMismatch.__init__r   r   r   r   r   r$   8   r   r$   c                       r   )NoInitialResponseErrorzAn event of type initial-response was not received.

    This exception is raised when the event stream produced no events or
    the first event in the stream was not of the initial-response type.
    c                    s   d}t  | d S )Nz0First event was not of the initial-response typer   )r   r   r   r   r   r   G   s   zNoInitialResponseError.__init__r   r   r   r   r   r(   @   s    r(   c                   @   s   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zeee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dZed%ddZed d! Zed"d# Zd$S )&DecodeUtilszUnpacking utility functions used in the decoder.

    All methods on this class take raw bytes and return  a tuple containing
    the value parsed from the bytes and the number of bytes consumed to parse
    that value.
    z!Bz!Hz!Iz!bz!hz!iz!qz!III)         c                 C      dS )a  This method consumes none of the provided bytes and returns True.

        :type data: bytes
        :param data: The bytes to parse from. This is ignored in this method.

        :rtype: tuple
        :rtype: (bool, int)
        :returns: The tuple (True, 0)
        )Tr   r   datar   r   r   unpack_trued      zDecodeUtils.unpack_truec                 C   r-   )a  This method consumes none of the provided bytes and returns False.

        :type data: bytes
        :param data: The bytes to parse from. This is ignored in this method.

        :rtype: tuple
        :rtype: (bool, int)
        :returns: The tuple (False, 0)
        )Fr   r   r.   r   r   r   unpack_falseq   r1   zDecodeUtils.unpack_falsec                 C       t tj| dd d }|dfS )zParse an unsigned 8-bit integer from the bytes.

        :type data: bytes
        :param data: The bytes to parse from.

        :rtype: (int, int)
        :returns: A tuple containing the (parsed integer value, bytes consumed)
        Nr*   r   )r   r)   UINT8_BYTE_FORMATr/   valuer   r   r   unpack_uint8~      
zDecodeUtils.unpack_uint8c                 C   r3   )zParse an unsigned 32-bit integer from the bytes.

        :type data: bytes
        :param data: The bytes to parse from.

        :rtype: (int, int)
        :returns: A tuple containing the (parsed integer value, bytes consumed)
        Nr,   r   )r   r)   UINT32_BYTE_FORMATr5   r   r   r   unpack_uint32   r8   zDecodeUtils.unpack_uint32c                 C   r3   )zParse a signed 8-bit integer from the bytes.

        :type data: bytes
        :param data: The bytes to parse from.

        :rtype: (int, int)
        :returns: A tuple containing the (parsed integer value, bytes consumed)
        Nr*   r   )r   r)   INT8_BYTE_FORMATr5   r   r   r   unpack_int8   r8   zDecodeUtils.unpack_int8c                 C   r3   )a  Parse a signed 16-bit integer from the bytes.

        :type data: bytes
        :param data: The bytes to parse from.

        :rtype: tuple
        :rtype: (int, int)
        :returns: A tuple containing the (parsed integer value, bytes consumed)
        Nr+   r   )r   r)   INT16_BYTE_FORMATr5   r   r   r   unpack_int16      zDecodeUtils.unpack_int16c                 C   r3   )a  Parse a signed 32-bit integer from the bytes.

        :type data: bytes
        :param data: The bytes to parse from.

        :rtype: tuple
        :rtype: (int, int)
        :returns: A tuple containing the (parsed integer value, bytes consumed)
        Nr,   r   )r   r)   INT32_BYTE_FORMATr5   r   r   r   unpack_int32   r?   zDecodeUtils.unpack_int32c                 C   r3   )a  Parse a signed 64-bit integer from the bytes.

        :type data: bytes
        :param data: The bytes to parse from.

        :rtype: tuple
        :rtype: (int, int)
        :returns: A tuple containing the (parsed integer value, bytes consumed)
        N   r   )r   r)   INT64_BYTE_FORMATr5   r   r   r   unpack_int64   r?   zDecodeUtils.unpack_int64r+   c                 C   s<   t j| }t|| d| d }|| }| || }||fS )a  Parse a variable length byte array from the bytes.

        The bytes are expected to be in the following format:
            [ length ][0 ... length bytes]
        where length is an unsigned integer represented in the smallest number
        of bytes to hold the maximum length of the array.

        :type data: bytes
        :param data: The bytes to parse from.

        :type length_byte_size: int
        :param length_byte_size: The byte size of the preceding integer that
        represents the length of the array. Supported values are 1, 2, and 4.

        :rtype: (bytes, int)
        :returns: A tuple containing the (parsed byte array, bytes consumed).
        Nr   )r)   UINT_BYTE_FORMATr   )r/   length_byte_sizeuint_byte_formatr    	bytes_endarray_bytesr   r   r   unpack_byte_array   s
   
zDecodeUtils.unpack_byte_arrayc                 C   s   t | |\}}|d|fS )a  Parse a variable length utf-8 string from the bytes.

        The bytes are expected to be in the following format:
            [ length ][0 ... length bytes]
        where length is an unsigned integer represented in the smallest number
        of bytes to hold the maximum length of the array and the following
        bytes are a valid utf-8 string.

        :type data: bytes
        :param bytes: The bytes to parse from.

        :type length_byte_size: int
        :param length_byte_size: The byte size of the preceding integer that
        represents the length of the array. Supported values are 1, 2, and 4.

        :rtype: (str, int)
        :returns: A tuple containing the (utf-8 string, bytes consumed).
        zutf-8)r)   rJ   decode)r/   rF   rI   consumedr   r   r   unpack_utf8_string   s   zDecodeUtils.unpack_utf8_stringc                 C   s   | dd dfS )zParse a 16-byte uuid from the bytes.

        :type data: bytes
        :param data: The bytes to parse from.

        :rtype: (bytes, int)
        :returns: A tuple containing the (uuid bytes, bytes consumed).
        N   r   r.   r   r   r   unpack_uuid  s   
zDecodeUtils.unpack_uuidc                 C   s   t tj| tfS )a  Parse the prelude for an event stream message from the bytes.

        The prelude for an event stream message has the following format:
            [total_length][header_length][prelude_crc]
        where each field is an unsigned 32-bit integer.

        :rtype: ((int, int, int), int)
        :returns: A tuple of ((total_length, headers_length, prelude_crc),
        consumed)
        )r   r)   PRELUDE_BYTE_FORMAT_PRELUDE_LENGTHr.   r   r   r   unpack_prelude  s   zDecodeUtils.unpack_preludeN)r+   )r   r   r	   r
   r4   UINT16_BYTE_FORMATr9   r;   r=   r@   rC   rP   rE   staticmethodr0   r2   r7   r:   r<   r>   rA   rD   rJ   rM   rO   rR   r   r   r   r   r)   L   sL    








r)   c                 C   s$   t | |d@ }||krt||d S )Nl    )r   r$   )r/   checksumcrccomputed_checksumr   r   r   _validate_checksum  s   
rX   c                   @   s<   e Zd ZdZdd Zedd Zedd Zedd	 Zd
S )MessagePreludez2Represents the prelude of an event stream message.c                 C   s   || _ || _|| _d S N)total_lengthheaders_lengthrV   )r   r[   r\   rV   r   r   r   r   '  s   
zMessagePrelude.__init__c                 C   s   | j | j t d S )zCalculates the total payload length.

        The extra minus 4 bytes is for the message CRC.

        :rtype: int
        :returns: The total payload length.
        r,   )r[   r\   rQ   r   r   r   r   payload_length,  s   	zMessagePrelude.payload_lengthc                 C   s
   | j d S )a	  Calculates the byte offset for the end of the message payload.

        The extra minus 4 bytes is for the message CRC.

        :rtype: int
        :returns: The byte offset from the beginning of the event stream
        message to the end of the payload.
        r,   )r[   r]   r   r   r   payload_end7  s   

zMessagePrelude.payload_endc                 C   s
   t | j S )zCalculates the byte offset for the end of the message headers.

        :rtype: int
        :returns: The byte offset from the beginning of the event stream
        message to the end of the headers.
        )rQ   r\   r]   r   r   r   headers_endC  s   
zMessagePrelude.headers_endN)	r   r   r	   r
   r   propertyr^   r_   r`   r   r   r   r   rY   $  s    


rY   c                   @   s"   e Zd ZdZdd ZdddZdS )	EventStreamMessagez#Represents an event stream message.c                 C   s   || _ || _|| _|| _d S rZ   )preludeheaderspayloadrV   )r   rc   rd   re   rV   r   r   r   r   Q  s   
zEventStreamMessage.__init__   c                 C   s0   | j d}|dks|dkrd}|| j | jdS )Nz:message-typeerror	exceptioni  )status_coderd   body)rd   getre   )r   ri   message_typer   r   r   to_response_dictW  s   z#EventStreamMessage.to_response_dictN)rf   )r   r   r	   r
   r   rm   r   r   r   r   rb   N  s    rb   c                   @   s~   e Zd ZdZejejejejej	ej
ejejej
ej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S )EventStreamHeaderParsera  Parses the event headers from an event stream message.

    Expects all of the header data upfront and creates a dictionary of headers
    to return. This object can be reused multiple times to parse the headers
    from multiple event stream messages.
    )
r   r*   r+      r,            rB   	   c                 C   s
   d | _ d S rZ   _datar]   r   r   r   r     s   
z EventStreamHeaderParser.__init__c                 C   s   || _ |  S )a  Parses the event stream headers from an event stream message.

        :type data: bytes
        :param data: The bytes that correspond to the headers section of an
        event stream message.

        :rtype: dict
        :returns: A dictionary of header key, value pairs.
        )ru   _parse_headersr   r/   r   r   r   parse  s   
zEventStreamHeaderParser.parsec                 C   s8   i }| j r|  \}}||v rt||||< | j s|S rZ   )ru   _parse_headerr   )r   rd   namer6   r   r   r   rv     s   z&EventStreamHeaderParser._parse_headersc                 C   s   |   }|  }||fS rZ   )_parse_name_parse_value)r   rz   r6   r   r   r   ry     s   z%EventStreamHeaderParser._parse_headerc                 C   s    t | jd\}}| | |S )Nr*   )r)   rM   ru   _advance_data)r   rz   rL   r   r   r   r{     s   
z#EventStreamHeaderParser._parse_namec                 C   s   t | j\}}| | |S rZ   )r)   r7   ru   r}   )r   typerL   r   r   r   _parse_type  s   
z#EventStreamHeaderParser._parse_typec                 C   s.   |   }| j| }|| j\}}| | |S rZ   )r   _HEADER_TYPE_MAPru   r}   )r   header_typevalue_unpackerr6   rL   r   r   r   r|     s
   

z$EventStreamHeaderParser._parse_valuec                 C   s   | j |d  | _ d S rZ   rt   )r   rL   r   r   r   r}     s   z%EventStreamHeaderParser._advance_dataN)r   r   r	   r
   r)   r0   r2   r<   r>   rA   rD   rJ   rM   rO   r   r   rx   rv   ry   r{   r   r|   r}   r   r   r   r   rn   b  s*    	rn   c                   @   s   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dd Zdd Zdd Zdd ZdS )EventStreamBufferzStreaming based event stream buffer

    A buffer class that wraps bytes from an event stream providing parsed
    messages as they become available via an iterable interface.
    c                 C   s   d| _ d | _t | _d S )N    )ru   _preludern   _header_parserr]   r   r   r   r     s   zEventStreamBuffer.__init__c                 C   s   |  j |7  _ dS )zAdd data to the buffer.

        :type data: bytes
        :param data: The bytes to add to the buffer to be used when parsing
        Nrt   rw   r   r   r   add_data  s   zEventStreamBuffer.add_datac                 C   s,   |j tkr
t|j |jtkrt|jd S rZ   )r\   r   r   r^   r#   r"   )r   rc   r   r   r   _validate_prelude  s
   



z#EventStreamBuffer._validate_preludec                 C   sJ   | j d t }t|\}}t| }t|d td  |j | | |S Nr,   )ru   rQ   r)   rR   rY   rX   rV   r   )r   prelude_bytesraw_prelude_rc   r   r   r   _parse_prelude  s   
z EventStreamBuffer._parse_preludec                 C   s   | j t| jj }| j|S rZ   )ru   rQ   r   r`   r   rx   )r   header_bytesr   r   r   rv     s   z EventStreamBuffer._parse_headersc                 C   s   | j }| j|j|j }|S rZ   )r   ru   r`   r_   )r   rc   payload_bytesr   r   r   _parse_payload  s   z EventStreamBuffer._parse_payloadc                 C   s*   | j }| j|j|j }t|\}}|S rZ   )r   ru   r_   r[   r)   r:   )r   rc   	crc_bytesmessage_crcr   r   r   r   _parse_message_crc  s   z$EventStreamBuffer._parse_message_crcc                 C   s   | j td | jj }|S r   )ru   rQ   r   r_   )r   message_bytesr   r   r   _parse_message_bytes  s   z&EventStreamBuffer._parse_message_bytesc                 C   s&   |   }|  }t||| jjd |S )N)rV   )r   r   rX   r   rV   )r   r   r   r   r   r   _validate_message_crc  s   z'EventStreamBuffer._validate_message_crcc                 C   s4   |   }|  }|  }t| j|||}|   |S rZ   )r   rv   r   rb   r   _prepare_for_next_message)r   rV   rd   re   r   r   r   r   _parse_message  s   z EventStreamBuffer._parse_messagec                 C   s   | j | jjd  | _ d | _d S rZ   )ru   r   r[   r]   r   r   r   r     s   
z+EventStreamBuffer._prepare_for_next_messagec                 C   sH   t | jtk r
t | jdu r|  | _t | j| jjk r t |  S )zProvides the next available message parsed from the stream

        :rtype: EventStreamMessage
        :returns: The next event stream message
        N)lenru   rQ   StopIterationr   r   r[   r   r]   r   r   r   next  s   

zEventStreamBuffer.nextc                 C   s   |   S rZ   )r   r]   r   r   r   __next__  s   zEventStreamBuffer.__next__c                 C   s   | S rZ   r   r]   r   r   r   __iter__  s   zEventStreamBuffer.__iter__N)r   r   r	   r
   r   r   r   r   rv   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s     	r   c                   @   s@   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S )EventStreama  Wrapper class for an event stream body.

    This wraps the underlying streaming body, parsing it for individual events
    and yielding them as they come available through the iterator interface.

    The following example uses the S3 select API to get structured data out of
    an object stored in S3 using an event stream.

    **Example:**
    ::
        from botocore.session import Session

        s3 = Session().create_client('s3')
        response = s3.select_object_content(
            Bucket='bucketname',
            Key='keyname',
            ExpressionType='SQL',
            RequestProgress={'Enabled': True},
            Expression="SELECT * FROM S3Object s",
            InputSerialization={'CSV': {}},
            OutputSerialization={'CSV': {}},
        )
        # This is the event stream in the response
        event_stream = response['Payload']
        end_event_received = False
        with open('output', 'wb') as f:
            # Iterate over events in the event stream as they come
            for event in event_stream:
                # If we received a records event, write the data to a file
                if 'Records' in event:
                    data = event['Records']['Payload']
                    f.write(data)
                # If we received a progress event, print the details
                elif 'Progress' in event:
                    print(event['Progress']['Details'])
                # End event indicates that the request finished successfully
                elif 'End' in event:
                    print('Result is complete')
                    end_event_received = True
        if not end_event_received:
            raise Exception("End event not received, request incomplete.")
    c                 C   s&   || _ || _|| _|| _|  | _d S rZ   )_raw_stream_output_shape_operation_name_parser_create_raw_event_generator_event_generator)r   
raw_streamoutput_shapeparseroperation_namer   r   r   r   G  s
   zEventStream.__init__c                 c   s&    | j D ]}| |}|r|V  qd S rZ   )r   _parse_event)r   eventparsed_eventr   r   r   r   N  s   

zEventStream.__iter__c                 c   s0    t  }| j D ]}|| |E d H  q	d S rZ   )r   r   streamr   )r   event_stream_bufferchunkr   r   r   r   T  s   
z'EventStream._create_raw_event_generatorc                 C   s4   |  }| j|| j}|d dkr|S t|| j)Nri   rf   )rm   r   rx   r   r   r   )r   r   response_dictparsed_responser   r   r   r   Z  s
   zEventStream._parse_eventc                 C   sD   zt | j}|jd}|dkr|W S W t  ty!   Y t w )Nz:event-typezinitial-response)r   r   rd   rk   r   r(   )r   initial_event
event_typer   r   r   get_initial_responseb  s   
z EventStream.get_initial_responsec                 C   s   | j   dS )z%Closes the underlying streaming body.N)r   closer]   r   r   r   r   l  s   zEventStream.closeN)
r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r     s    +
r   N)r   )r
   binasciir   structr   botocore.exceptionsr   rQ   r   r#   	Exceptionr   r   r   r"   r$   r(   r)   rX   rY   rb   rn   r   r   r   r   r   r   <module>   s*    
Q*Te