o .&ßa)Pã@sdZddlmZddlmZddlmZdZdZdZ Gdd „d e ƒZ Gd d „d e ƒZ Gd d „d e ƒZ Gdd„de ƒZGdd„de ƒZGdd„de ƒZGdd„deƒZd#dd„ZGdd„deƒZGdd„deƒZGdd„deƒZGdd„deƒZGd d!„d!eƒZd"S)$zBinary Event Stream Decoding é)Úcrc32)Úunpack)ÚEventStreamErroré iic@seZdZdZdS)Ú ParserErrorz.Base binary flow encoding parsing exception. N)Ú__name__Ú __module__Ú __qualname__Ú__doc__©r r ú6/usr/lib/python3/dist-packages/botocore/eventstream.pyrsrcó eZdZdZ‡fdd„Z‡ZS)ÚDuplicateHeaderz%Duplicate header found in the event. csd|}tt|ƒ |¡dS)NzDuplicate header present: "%s")ÚsuperrÚ__init__)ÚselfÚheaderÚmessage©Ú __class__r r r szDuplicateHeader.__init__©rrr r rÚ __classcell__r r rr rórcr )ÚInvalidHeadersLengthz+Headers length is longer than the maximum. có d|tf}tt|ƒ |¡dS)Nz.Header length of %s exceeded the maximum of %s)Ú_MAX_HEADERS_LENGTHrrr©rÚlengthrrr r r'óÿzInvalidHeadersLength.__init__rr r rr r%rrcr )ÚInvalidPayloadLengthz+Payload length is longer than the maximum. cr)Nz/Payload length of %s exceeded the maximum of %s)Ú_MAX_PAYLOAD_LENGTHrrrrrr r r0rzInvalidPayloadLength.__init__rr r rr r.rrcr )ÚChecksumMismatchz9Calculated checksum did not match the expected checksum. cs d||f}tt|ƒ |¡dS)Nz5Checksum mismatch: expected 0x%08x, calculated 0x%08x)rr!r)rÚexpectedÚ calculatedrrr r r9rzChecksumMismatch.__init__rr r rr r!7rr!cr )Ú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. csd}tt|ƒ |¡dS)Nz0First event was not of the initial-response type)rr$r)rrrr r rFszNoInitialResponseError.__init__rr r rr r$@sr$c@sÐeZdZdZdZdZdZdZdZdZ dZ d Z eeed œZ e d d „ƒZe d d„ƒZe dd„ƒZe dd„ƒZe dd„ƒZe dd„ƒZe dd„ƒZe dd„ƒZe d%dd„ƒZe d%dd„ƒZe d d!„ƒZe d"d#„ƒZd$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)ééécCódS)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) )Trr ©Údatar r r Ú unpack_truecó zDecodeUtils.unpack_truecCr))aThis 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) )Frr r*r r r Ú unpack_falsepr-zDecodeUtils.unpack_falsecCó ttj|dd…ƒd}|dfS)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)rr%ÚUINT8_BYTE_FORMAT©r+Úvaluer r r Ú unpack_uint8}ó zDecodeUtils.unpack_uint8cCr/)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)rr%ÚUINT32_BYTE_FORMATr1r r r Ú unpack_uint32Šr4zDecodeUtils.unpack_uint32cCr/)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)rr%ÚINT8_BYTE_FORMATr1r r r Ú unpack_int8—r4zDecodeUtils.unpack_int8cCr/)aParse 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)rr%ÚINT16_BYTE_FORMATr1r r r Ú unpack_int16¤ó zDecodeUtils.unpack_int16cCr/)aParse 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)rr%ÚINT32_BYTE_FORMATr1r r r Ú unpack_int32²r;zDecodeUtils.unpack_int32cCr/)aParse 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)rr%ÚINT64_BYTE_FORMATr1r r r Ú unpack_int64Àr;zDecodeUtils.unpack_int64r'cCs<tj|}t||d|…ƒd}||}|||…}||fS)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_sizeÚuint_byte_formatrÚ bytes_endÚ array_bytesr r r Úunpack_byte_arrayÎs  zDecodeUtils.unpack_byte_arraycCst ||¡\}}| d¡|fS)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). zutf-8)r%rFÚdecode)r+rBrEÚconsumedr r r Úunpack_utf8_stringçsÿzDecodeUtils.unpack_utf8_stringcCs|dd…dfS)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 zDecodeUtils.unpack_uuidcCsttj|ƒtfS)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) )rr%ÚPRELUDE_BYTE_FORMATÚ_PRELUDE_LENGTHr*r r r Úunpack_prelude s zDecodeUtils.unpack_preludeN)r')rrr r r0ÚUINT16_BYTE_FORMATr5r7r9r<r?rLrAÚ staticmethodr,r.r3r6r8r:r=r@rFrIrKrNr r r r r%KsLý            r%cCs$t||ƒd@}||krt||ƒ‚dS)Nlÿÿ)rr!)r+ÚchecksumÚcrcÚcomputed_checksumr r r Ú_validate_checksums ÿrTc@s<eZdZdZdd„Zedd„ƒZedd„ƒZedd „ƒZd S) ÚMessagePreludez3Represents the prelude of an event stream message. cCs||_||_||_dS©N)Ú total_lengthÚheaders_lengthrR)rrWrXrRr r r r$s zMessagePrelude.__init__cCs|j|jtdS)z§Calculates the total payload length. The extra minus 4 bytes is for the message CRC. :rtype: int :returns: The total payload length. r()rWrXrM©rr r r Úpayload_length)s zMessagePrelude.payload_lengthcCs |jdS)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()rWrYr r r Ú payload_end4s zMessagePrelude.payload_endcCs t|jS)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. )rMrXrYr r r Ú headers_end@s zMessagePrelude.headers_endN) rrr r rÚpropertyrZr[r\r r r r rU"s   rUc@s"eZdZdZdd„Zddd„ZdS) ÚEventStreamMessagez$Represents an event stream message. cCs||_||_||_||_dSrV)ÚpreludeÚheadersÚpayloadrR)rr_r`rarRr r r rMs zEventStreamMessage.__init__éÈcCs0|j d¡}|dks|dkrd}||j|jdœS)Nz :message-typeÚerrorÚ exceptioni)Ú status_coder`Úbody)r`Úgetra)rreÚ message_typer r r Úto_response_dictSs ýz#EventStreamMessage.to_response_dictN)rb)rrr r rrir r r r r^Ksr^c @s~eZdZdZejejejejej ej ej ej ej ej dœ Zdd„Zdd„Zdd„Zd d „Zd d „Zd d„Zdd„Zdd„ZdS)Ú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. ) rr&r'ér(ééér>é cCs d|_dSrV©Ú_datarYr r r rs z EventStreamHeaderParser.__init__cCs||_| ¡S)aParses 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. )rqÚ_parse_headers©rr+r r r Úparse‚s zEventStreamHeaderParser.parsecCs8i}|jr| ¡\}}||vrt|ƒ‚|||<|js|SrV)rqÚ _parse_headerr)rr`Únamer2r r r rrs üz&EventStreamHeaderParser._parse_headerscCs| ¡}| ¡}||fSrV)Ú _parse_nameÚ _parse_value)rrvr2r r r ru˜sz%EventStreamHeaderParser._parse_headercCs t |jd¡\}}| |¡|S)Nr&)r%rIrqÚ _advance_data)rrvrHr r r rws z#EventStreamHeaderParser._parse_namecCst |j¡\}}| |¡|SrV)r%r3rqry)rÚtyperHr r r Ú _parse_type¢s z#EventStreamHeaderParser._parse_typecCs.| ¡}|j|}||jƒ\}}| |¡|SrV)r{Ú_HEADER_TYPE_MAPrqry)rÚ header_typeÚvalue_unpackerr2rHr r r rx§s   z$EventStreamHeaderParser._parse_valuecCs|j|d…|_dSrVrp)rrHr r r ry®sz%EventStreamHeaderParser._advance_dataN)rrr r r%r,r.r8r:r=r@rFrIrKr|rrtrrrurwr{rxryr r r r rj^s* ì   rjc@s€eZdZdZdd„Zdd„Zdd„Zdd „Zd d „Zd d „Z dd„Z dd„Z dd„Z dd„Z dd„Zdd„Zdd„Zdd„ZdS)Ú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. cCsd|_d|_tƒ|_dS)Nó)rqÚ_preluderjÚ_header_parserrYr r r r¹s zEventStreamBuffer.__init__cCs|j|7_dS)z‡Add data to the buffer. :type data: bytes :param data: The bytes to add to the buffer to be used when parsing Nrprsr r r Úadd_data¾szEventStreamBuffer.add_datacCs,|jtkr t|jƒ‚|jtkrt|jƒ‚dSrV)rXrrrZr r)rr_r r r Ú_validate_preludeÆs    ÿz#EventStreamBuffer._validate_preludecCsJ|jdt…}t |¡\}}t|Ž}| |¡t|dtd…|jƒ|S©Nr()rqrMr%rNrUr„rTrR)rÚ prelude_bytesÚ raw_preludeÚ_r_r r r Ú_parse_preludeÍs  z EventStreamBuffer._parse_preludecCs|jt|jj…}|j |¡SrV)rqrMrr\r‚rt)rÚ header_bytesr r r rrÖs z EventStreamBuffer._parse_headerscCs|j}|j|j|j…}|SrV)rrqr\r[)rr_Ú payload_bytesr r r Ú_parse_payloadÚsz EventStreamBuffer._parse_payloadcCs*|j}|j|j|j…}t |¡\}}|SrV)rrqr[rWr%r6)rr_Ú crc_bytesÚ message_crcrˆr r r Ú_parse_message_crcßsz$EventStreamBuffer._parse_message_crccCs|jtd|jj…}|Sr…)rqrMrr[)rÚ message_bytesr r r Ú_parse_message_bytesåsz&EventStreamBuffer._parse_message_bytescCs&| ¡}| ¡}t|||jjd|S)N)rR)rr‘rTrrR)rrŽrr r r Ú_validate_message_crcêsz'EventStreamBuffer._validate_message_crccCs4| ¡}| ¡}| ¡}t|j|||ƒ}| ¡|SrV)r’rrrŒr^rÚ_prepare_for_next_message)rrRr`rarr r r Ú_parse_messageðs z EventStreamBuffer._parse_messagecCs|j|jjd…|_d|_dSrV)rqrrWrYr r r r“øs z+EventStreamBuffer._prepare_for_next_messagecCsHt|jƒtkr tƒ‚|jdur| ¡|_t|jƒ|jjkr tƒ‚| ¡S)z—Provides the next available message parsed from the stream :rtype: EventStreamMessage :returns: The next event stream message N)ÚlenrqrMÚ StopIterationrr‰rWr”rYr r r Únextýs  zEventStreamBuffer.nextcCs| ¡SrV)r—rYr r r Ú__next__szEventStreamBuffer.__next__cCs|SrVr rYr r r Ú__iter__szEventStreamBuffer.__iter__N)rrr r rrƒr„r‰rrrŒrr‘r’r”r“r—r˜r™r r r r r²s   rc@s@eZdZdZdd„Zdd„Zdd„Zdd „Zd d „Zd d „Z dS)Ú 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.") cCs&||_||_||_||_| ¡|_dSrV)Ú _raw_streamÚ _output_shapeÚ_operation_nameÚ_parserÚ_create_raw_event_generatorÚ_event_generator)rÚ raw_streamÚ output_shapeÚparserÚoperation_namer r r r@s zEventStream.__init__ccs&|jD] }| |¡}|r|VqdSrV)r Ú _parse_event)rÚeventÚ parsed_eventr r r r™Gs€  €ýzEventStream.__iter__ccs6tƒ}|j ¡D]}| |¡|D]}|Vqq dSrV)rr›Ústreamrƒ)rÚevent_stream_bufferÚchunkr¦r r r rŸMs€ ÿþz'EventStream._create_raw_event_generatorcCs4| ¡}|j ||j¡}|ddkr|St||jƒ‚)Nrerb)riržrtrœrr)rr¦Ú response_dictÚparsed_responser r r r¥Ts   zEventStream._parse_eventcCsDzt|jƒ}|j d¡}|dkr|WSWtƒ‚ty!Ytƒ‚w)Nz :event-typezinitial-response)r—r r`rgr–r$)rÚ initial_eventÚ event_typer r r Úget_initial_response\s  ÿ þþz EventStream.get_initial_responsecCs|j ¡dS)z&Closes the underlying streaming body. N)r›ÚcloserYr r r r°fszEventStream.closeN) rrr r rr™rŸr¥r¯r°r r r r ršs* ršN)r)r ÚbinasciirÚstructrÚbotocore.exceptionsrrMrr Ú Exceptionrrrrr!r$Úobjectr%rTrUr^rjrršr r r r Ús*        P)Tc