B ㊇cO@sdZddlmZddlmZddlmZdZdZdZ Gdd d e Z Gd d d e Z Gd d d e Z Gddde ZGddde ZGddde ZGdddZd#ddZGdddZGdddZGdddZGdddZGd d!d!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 o/private/var/folders/8c/hx9_v10d5x38qmnzt13b7b8j1k3n5b/T/pip-target-x6xd5gna/lib/python/botocore/eventstream.pyrsrcs eZdZdZfddZZS)DuplicateHeaderz$Duplicate header found in the event.csd|}t|dS)NzDuplicate header present: "%s")super__init__)selfheadermessage) __class__r r r#szDuplicateHeader.__init__)rrr r r __classcell__r r )rr r sr cs eZdZdZfddZZS)InvalidHeadersLengthz*Headers length is longer than the maximum.csd|t}t|dS)Nz.Header length of {} exceeded the maximum of {})format_MAX_HEADERS_LENGTHrr)rlengthr)rr r r+szInvalidHeadersLength.__init__)rrr r rrr r )rr r(srcs eZdZdZfddZZS)InvalidPayloadLengthz*Payload length is longer than the maximum.csd|t}t|dS)Nz/Payload length of {} exceeded the maximum of {})r_MAX_PAYLOAD_LENGTHrr)rrr)rr r r6szInvalidPayloadLength.__init__)rrr r rrr r )rr r3srcs eZdZdZfddZZS)ChecksumMismatchz8Calculated checksum did not match the expected checksum.csd||}t|dS)Nz9Checksum mismatch: expected 0x{:08x}, calculated 0x{:08x})rrr)rexpectedZ calculatedr)rr r rAszChecksumMismatch.__init__)rrr r rrr r )rr r>srcs eZdZdZfddZZS)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. csd}t|dS)Nz0First event was not of the initial-response type)rr)rr)rr r rRszNoInitialResponseError.__init__)rrr r rrr r )rr rKsrc@seZdZdZdZdZdZdZdZdZ dZ d Z eeed Z e d d Ze d dZe ddZe ddZe ddZe ddZe ddZe ddZe d%ddZe d&ddZe d d!Ze d"d#Zd$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)cCsdS)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_trueos zDecodeUtils.unpack_truecCsdS)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_false|s zDecodeUtils.unpack_falsecCs ttj|ddd}|dfS)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) Nrr)rrUINT8_BYTE_FORMAT)r"valuer r r unpack_uint8s zDecodeUtils.unpack_uint8cCs ttj|ddd}|dfS)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)rrUINT32_BYTE_FORMAT)r"r&r r r unpack_uint32s zDecodeUtils.unpack_uint32cCs ttj|ddd}|dfS)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) Nrr)rrINT8_BYTE_FORMAT)r"r&r r r unpack_int8s zDecodeUtils.unpack_int8cCs ttj|ddd}|dfS)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)rrINT16_BYTE_FORMAT)r"r&r r r unpack_int16s zDecodeUtils.unpack_int16cCs ttj|ddd}|dfS)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)rrINT32_BYTE_FORMAT)r"r&r r r unpack_int32s zDecodeUtils.unpack_int32cCs ttj|ddd}|dfS)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) Nr)rrINT64_BYTE_FORMAT)r"r&r r r unpack_int64s zDecodeUtils.unpack_int64r cCs<tj|}t||d|d}||}|||}||fS)aParse 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)rUINT_BYTE_FORMATr)r"length_byte_sizeZuint_byte_formatrZ bytes_end array_bytesr r r unpack_byte_arrays   zDecodeUtils.unpack_byte_arraycCst||\}}|d|fS)aParse 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)rr6decode)r"r4r5consumedr r r unpack_utf8_strings zDecodeUtils.unpack_utf8_stringcCs|dddfS)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). Nr )r"r r r unpack_uuid s zDecodeUtils.unpack_uuidcCsttj|tfS)aParse 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) )rrPRELUDE_BYTE_FORMAT_PRELUDE_LENGTH)r"r r r unpack_preludes zDecodeUtils.unpack_preludeN)r )r )rrr r r%ZUINT16_BYTE_FORMATr(r*r,r.r1r<r3 staticmethodr#r$r'r)r+r-r/r2r6r9r;r>r r r r rWs4      rcCs$t||d@}||kr t||dS)Nl)rr)r"ZchecksumcrcZcomputed_checksumr r r _validate_checksum'srAc@s<eZdZdZddZeddZeddZedd Zd S) MessagePreludez2Represents the prelude of an event stream message.cCs||_||_||_dS)N) total_lengthheaders_lengthr@)rrCrDr@r r r r2szMessagePrelude.__init__cCs|j|jtdS)zCalculates the total payload length. The extra minus 4 bytes is for the message CRC. :rtype: int :returns: The total payload length. r!)rCrDr=)rr r r payload_length7s 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!)rC)rr r r payload_endBs zMessagePrelude.payload_endcCs t|jS)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. )r=rD)rr r r headers_endNszMessagePrelude.headers_endN) rrr r rpropertyrErFrGr r r r rB/s  rBc@s"eZdZdZddZdddZdS) EventStreamMessagez#Represents an event stream message.cCs||_||_||_||_dS)N)preludeheaderspayloadr@)rrJrKrLr@r r r r\szEventStreamMessage.__init__cCs0|jd}|dks|dkr d}||j|jdS)Nz :message-typeerror exceptioni) status_coderKbody)rKgetrL)rrPZ message_typer r r to_response_dictbs  z#EventStreamMessage.to_response_dictN)rM)rrr r rrSr r r r rIYsrIc @s~eZdZdZejejejejej ej ej ej ej ej d ZddZddZddZd d Zd d Zd dZddZddZdS)EventStreamHeaderParseraParses 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. ) rrr r!r0 cCs d|_dS)N)_data)rr r r rsz 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. )rZ_parse_headers)rr"r r r parses zEventStreamHeaderParser.parsecCs8i}x.|jr2|\}}||kr(t||||<qW|S)N)rZ _parse_headerr )rrKnamer&r r r r[s  z&EventStreamHeaderParser._parse_headerscCs|}|}||fS)N) _parse_name _parse_value)rr^r&r r r r]sz%EventStreamHeaderParser._parse_headercCs t|jd\}}|||S)Nr)rr9rZ _advance_data)rr^r8r r r r_s z#EventStreamHeaderParser._parse_namecCst|j\}}|||S)N)rr'rZra)rtyper8r r r _parse_types z#EventStreamHeaderParser._parse_typecCs.|}|j|}||j\}}|||S)N)rc_HEADER_TYPE_MAPrZra)rZ header_typeZvalue_unpackerr&r8r r r r`s   z$EventStreamHeaderParser._parse_valuecCs|j|d|_dS)N)rZ)rr8r r r rasz%EventStreamHeaderParser._advance_dataN)rrr r rr#r$r+r-r/r2r6r9r;rdrr\r[r]r_rcr`rar r r r rTms&   rTc@seZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZddZddZddZdS)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. cCsd|_d|_t|_dS)N)rZ_preluderT_header_parser)rr r r rszEventStreamBuffer.__init__cCs|j|7_dS)zAdd data to the buffer. :type data: bytes :param data: The bytes to add to the buffer to be used when parsing N)rZ)rr"r r r add_dataszEventStreamBuffer.add_datacCs,|jtkrt|j|jtkr(t|jdS)N)rDrrrErr)rrJr r r _validate_preludes   z#EventStreamBuffer._validate_preludecCsJ|jdt}t|\}}t|}||t|dtd|j|S)Nr!)rZr=rr>rBrjrAr@)rZ prelude_bytesZ raw_prelude_rJr r r _parse_preludes  z EventStreamBuffer._parse_preludecCs|jt|jj}|j|S)N)rZr=rgrGrhr\)r header_bytesr r r r[sz EventStreamBuffer._parse_headerscCs|j}|j|j|j}|S)N)rgrZrGrF)rrJZ payload_bytesr r r _parse_payloadsz EventStreamBuffer._parse_payloadcCs*|j}|j|j|j}t|\}}|S)N)rgrZrFrCrr))rrJZ crc_bytes message_crcrkr r r _parse_message_crcsz$EventStreamBuffer._parse_message_crccCs|jtd|jj}|S)Nr!)rZr=rgrF)r message_bytesr r r _parse_message_bytessz&EventStreamBuffer._parse_message_bytescCs&|}|}t|||jjd|S)N)r@)rprrrArgr@)rrorqr r r _validate_message_crcsz'EventStreamBuffer._validate_message_crccCs4|}|}|}t|j|||}||S)N)rsr[rnrIrg_prepare_for_next_message)rr@rKrLrr r r _parse_messages z EventStreamBuffer._parse_messagecCs|j|jjd|_d|_dS)N)rZrgrC)rr r r rt sz+EventStreamBuffer._prepare_for_next_messagecCsHt|jtkrt|jdkr(||_t|j|jjkr@t|S)zProvides the next available message parsed from the stream :rtype: EventStreamMessage :returns: The next event stream message N)lenrZr= StopIterationrgrlrCru)rr r r nexts  zEventStreamBuffer.nextcCs|S)N)rx)rr r r __next__szEventStreamBuffer.__next__cCs|S)Nr )rr r r __iter__"szEventStreamBuffer.__iter__N)rrr r rrirjrlr[rnrprrrsrurtrxryrzr r r r res rec@s@eZdZdZddZddZddZdd Zd d Zd d Z dS) EventStreamaWrapper 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&||_||_||_||_||_dS)N) _raw_stream _output_shape_operation_name_parser_create_raw_event_generator_event_generator)rZ raw_streamZ output_shapeparserZoperation_namer r r rRs zEventStream.__init__ccs(x"|jD]}||}|r|VqWdS)N)r _parse_event)reventZ parsed_eventr r r rzYs  zEventStream.__iter__ccs2t}x&|jD]}|||EdHqWdS)N)rer|streamri)rZevent_stream_bufferchunkr r r r_s z'EventStream._create_raw_event_generatorcCs8|}|j||j}|ddkr(|St||jdS)NrPrM)rSrr\r}rr~)rrZ response_dictZparsed_responser r r res  zEventStream._parse_eventcCsFy&t|j}|jd}|dkr$|SWntk r:YnXtdS)Nz :event-typezinitial-response)rxrrKrRrwr)rZ initial_eventZ event_typer r r get_initial_responsems  z EventStream.get_initial_responsecCs|jdS)z%Closes the underlying streaming body.N)r|close)rr r r rwszEventStream.closeN) rrr r rrzrrrrr r r r r{&s* r{N)r)r binasciirstructrZbotocore.exceptionsrr=rr Exceptionrr rrrrrrArBrIrTrer{r r r r  s(       Q *Te