U
    M8ÚcâO  ã                   @   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   ú8/tmp/pip-unpacked-wheel-ozje0y8b/botocore/eventstream.pyr      s   r   c                       s    e Zd ZdZ‡ fdd„Z‡  ZS )ÚDuplicateHeaderz$Duplicate header found in the event.c                    s   d| }t ƒ  |¡ d S )NzDuplicate header present: "%s"©ÚsuperÚ__init__)ÚselfÚheaderÚmessage©Ú	__class__r   r   r   #   s    zDuplicateHeader.__init__©r   r   r	   r
   r   Ú__classcell__r   r   r   r   r       s   r   c                       s    e Zd ZdZ‡ fdd„Z‡  ZS )ÚInvalidHeadersLengthz*Headers length is longer than the maximum.c                    s   d  |t¡}tƒ  |¡ d S )Nz.Header length of {} exceeded the maximum of {})ÚformatÚ_MAX_HEADERS_LENGTHr   r   ©r   Úlengthr   r   r   r   r   +   s
    þzInvalidHeadersLength.__init__r   r   r   r   r   r   (   s   r   c                       s    e Zd ZdZ‡ fdd„Z‡  ZS )ÚInvalidPayloadLengthz*Payload length is longer than the maximum.c                    s   d  |t¡}tƒ  |¡ d S )Nz/Payload length of {} exceeded the maximum of {})r   Ú_MAX_PAYLOAD_LENGTHr   r   r   r   r   r   r   6   s
    þzInvalidPayloadLength.__init__r   r   r   r   r   r   3   s   r   c                       s    e Zd ZdZ‡ fdd„Z‡  ZS )ÚChecksumMismatchz8Calculated checksum did not match the expected checksum.c                    s   d  ||¡}tƒ  |¡ d S )Nz9Checksum mismatch: expected 0x{:08x}, calculated 0x{:08x})r   r   r   )r   ÚexpectedZ
calculatedr   r   r   r   r   A   s    þÿzChecksumMismatch.__init__r   r   r   r   r   r   >   s   r   c                       s    e Zd ZdZ‡ fdd„Z‡  ZS )ÚNoInitialResponseErrorzÊAn 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   R   s    zNoInitialResponseError.__init__r   r   r   r   r   r!   K   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 )'ÚDecodeUtilszàUnpacking 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   s   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_trueo   s    zDecodeUtils.unpack_truec                 C   s   dS )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_false|   s    zDecodeUtils.unpack_falsec                 C   s    t tj| dd… ƒd }|dfS )zíParse 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‰   s    
zDecodeUtils.unpack_uint8c                 C   s    t tj| dd… ƒd }|dfS )zîParse 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_FORMATr+   r   r   r   Úunpack_uint32–   s    
zDecodeUtils.unpack_uint32c                 C   s    t tj| dd… ƒd }|dfS )zêParse 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_FORMATr+   r   r   r   Úunpack_int8£   s    
zDecodeUtils.unpack_int8c                 C   s    t tj| dd… ƒd }|dfS )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_FORMATr+   r   r   r   Úunpack_int16°   s    zDecodeUtils.unpack_int16c                 C   s    t tj| dd… ƒd }|dfS )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_FORMATr+   r   r   r   Úunpack_int32¾   s    zDecodeUtils.unpack_int32c                 C   s    t tj| dd… ƒd }|dfS )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_FORMATr+   r   r   r   Úunpack_int64Ì   s    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 preceeding 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_sizeZuint_byte_formatr   Z	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 preceeding 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"   r<   Údecode)r'   r:   r;   Úconsumedr   r   r   Úunpack_utf8_stringó   s
     ÿzDecodeUtils.unpack_utf8_stringc                 C   s   | dd… dfS )zÛParse 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	   r
   r*   ZUINT16_BYTE_FORMATr.   r0   r2   r4   r7   rB   r9   Ústaticmethodr(   r)   r-   r/   r1   r3   r5   r8   r<   r?   rA   rD   r   r   r   r   r"   W   sJ   ý








r"   c                 C   s$   t | |ƒd@ }||kr t||ƒ‚d S )Nl   ÿÿ )r   r   )r'   ZchecksumÚcrcZcomputed_checksumr   r   r   Ú_validate_checksum'  s    rG   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_lengthrF   )r   rJ   rK   rF   r   r   r   r   2  s    zMessagePrelude.__init__c                 C   s   | j | j t d S )z§Calculates the total payload length.

        The extra minus 4 bytes is for the message CRC.

        :rtype: int
        :returns: The total payload length.
        r%   )rJ   rK   rC   ©r   r   r   r   Úpayload_length7  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%   )rJ   rL   r   r   r   Úpayload_endB  s    
zMessagePrelude.payload_endc                 C   s
   t | j S )zÐCalculates 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.
        )rC   rK   rL   r   r   r   Úheaders_endN  s    zMessagePrelude.headers_endN)	r   r   r	   r
   r   ÚpropertyrM   rN   rO   r   r   r   r   rH   /  s   


rH   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 rI   )ÚpreludeÚheadersÚpayloadrF   )r   rR   rS   rT   rF   r   r   r   r   \  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_coderS   Úbody)rS   ÚgetrT   )r   rX   Zmessage_typer   r   r   Úto_response_dictb  s    ýz#EventStreamMessage.to_response_dictN)rU   )r   r   r	   r
   r   r[   r   r   r   r   rQ   Y  s   rQ   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%   é   é   é   r6   é	   c                 C   s
   d | _ d S rI   ©Ú_datarL   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 dicionary of header key, value pairs.
        )rc   Ú_parse_headers©r   r'   r   r   r   Úparse‘  s    
zEventStreamHeaderParser.parsec                 C   s4   i }| j r0|  ¡ \}}||kr&t|ƒ‚|||< q|S rI   )rc   Ú_parse_headerr   )r   rS   Únamer,   r   r   r   rd   ž  s    
z&EventStreamHeaderParser._parse_headersc                 C   s   |   ¡ }|  ¡ }||fS rI   )Ú_parse_nameÚ_parse_value)r   rh   r,   r   r   r   rg   §  s    z%EventStreamHeaderParser._parse_headerc                 C   s    t  | jd¡\}}|  |¡ |S )Nr#   )r"   r?   rc   Ú_advance_data)r   rh   r>   r   r   r   ri   ¬  s    
z#EventStreamHeaderParser._parse_namec                 C   s   t  | j¡\}}|  |¡ |S rI   )r"   r-   rc   rk   )r   Útyper>   r   r   r   Ú_parse_type±  s    
z#EventStreamHeaderParser._parse_typec                 C   s.   |   ¡ }| j| }|| jƒ\}}|  |¡ |S rI   )rm   Ú_HEADER_TYPE_MAPrc   rk   )r   Zheader_typeZvalue_unpackerr,   r>   r   r   r   rj   ¶  s
    

z$EventStreamHeaderParser._parse_valuec                 C   s   | j |d … | _ d S rI   rb   )r   r>   r   r   r   rk   ½  s    z%EventStreamHeaderParser._advance_dataN)r   r   r	   r
   r"   r(   r)   r1   r3   r5   r8   r<   r?   rA   rn   r   rf   rd   rg   ri   rm   rj   rk   r   r   r   r   r\   m  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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 )ÚEventStreamBufferz´Streaming 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ó    )rc   Ú_preluder\   Ú_header_parserrL   r   r   r   r   È  s    zEventStreamBuffer.__init__c                 C   s   |  j |7  _ dS )z‡Add data to the buffer.

        :type data: bytes
        :param data: The bytes to add to the buffer to be used when parsing
        Nrb   re   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 rI   )rK   r   r   rM   r   r   )r   rR   r   r   r   Ú_validate_preludeÕ  s    


z#EventStreamBuffer._validate_preludec                 C   sJ   | j d t… }t |¡\}}t|Ž }|  |¡ t|d td … |jƒ |S ©Nr%   )rc   rC   r"   rD   rH   rt   rG   rF   )r   Zprelude_bytesZraw_preludeÚ_rR   r   r   r   Ú_parse_preludeÜ  s    
z EventStreamBuffer._parse_preludec                 C   s   | j t| jj… }| j |¡S rI   )rc   rC   rq   rO   rr   rf   )r   Úheader_bytesr   r   r   rd   å  s    z EventStreamBuffer._parse_headersc                 C   s   | j }| j|j|j… }|S rI   )rq   rc   rO   rN   )r   rR   Zpayload_bytesr   r   r   Ú_parse_payloadé  s    z EventStreamBuffer._parse_payloadc                 C   s*   | j }| j|j|j… }t |¡\}}|S rI   )rq   rc   rN   rJ   r"   r/   )r   rR   Z	crc_bytesÚmessage_crcrv   r   r   r   Ú_parse_message_crcî  s    z$EventStreamBuffer._parse_message_crcc                 C   s   | j td | jj… }|S ru   )rc   rC   rq   rN   )r   Úmessage_bytesr   r   r   Ú_parse_message_bytesô  s
     ÿz&EventStreamBuffer._parse_message_bytesc                 C   s&   |   ¡ }|  ¡ }t||| jjd |S )N)rF   )r{   r}   rG   rq   rF   )r   rz   r|   r   r   r   Ú_validate_message_crcû  s    z'EventStreamBuffer._validate_message_crcc                 C   s4   |   ¡ }|  ¡ }|  ¡ }t| j|||ƒ}|  ¡  |S rI   )r~   rd   ry   rQ   rq   Ú_prepare_for_next_message)r   rF   rS   rT   r   r   r   r   Ú_parse_message  s    z EventStreamBuffer._parse_messagec                 C   s   | j | jjd … | _ d | _d S rI   )rc   rq   rJ   rL   r   r   r   r   	  s    z+EventStreamBuffer._prepare_for_next_messagec                 C   sH   t | jƒtk rtƒ ‚| jdkr(|  ¡ | _t | jƒ| jjk r@tƒ ‚|  ¡ S )z—Provides the next available message parsed from the stream

        :rtype: EventStreamMessage
        :returns: The next event stream message
        N)Úlenrc   rC   ÚStopIterationrq   rw   rJ   r€   rL   r   r   r   Únext  s    

zEventStreamBuffer.nextc                 C   s   |   ¡ S rI   )rƒ   rL   r   r   r   Ú__next__  s    zEventStreamBuffer.__next__c                 C   s   | S rI   r   rL   r   r   r   Ú__iter__"  s    zEventStreamBuffer.__iter__N)r   r   r	   r
   r   rs   rt   rw   rd   ry   r{   r}   r~   r€   r   rƒ   r„   r…   r   r   r   r   ro   Á  s   	ro   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 rI   )Ú_raw_streamÚ_output_shapeÚ_operation_nameÚ_parserÚ_create_raw_event_generatorÚ_event_generator)r   Z
raw_streamZoutput_shapeÚparserZoperation_namer   r   r   r   R  s
    zEventStream.__init__c                 c   s$   | j D ]}|  |¡}|r|V  qd S rI   )rŒ   Ú_parse_event)r   ÚeventZparsed_eventr   r   r   r…   Y  s    

zEventStream.__iter__c                 c   s.   t ƒ }| j ¡ D ]}| |¡ |E d H  qd S rI   )ro   r‡   Ústreamrs   )r   Zevent_stream_bufferÚchunkr   r   r   r‹   _  s    
z'EventStream._create_raw_event_generatorc                 C   s8   |  ¡ }| j || j¡}|d dkr(|S t|| jƒ‚d S )NrX   rU   )r[   rŠ   rf   rˆ   r   r‰   )r   r   Zresponse_dictZparsed_responser   r   r   rŽ   e  s
    zEventStream._parse_eventc                 C   sH   z(t | jƒ}|j d¡}|dkr&|W S W n tk
r<   Y nX tƒ ‚d S )Nz:event-typezinitial-response)rƒ   rŒ   rS   rZ   r‚   r!   )r   Zinitial_eventZ
event_typer   r   r   Úget_initial_responsem  s    

z EventStream.get_initial_responsec                 C   s   | j  ¡  dS )z%Closes the underlying streaming body.N)r‡   ÚcloserL   r   r   r   r“   w  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   Zbotocore.exceptionsr   rC   r   r   Ú	Exceptionr   r   r   r   r   r!   r"   rG   rH   rQ   r\   ro   r†   r   r   r   r   Ú<module>   s(    Q
*Te