
    9hn                        S SK r S SKrS SKrS SKrS SKrS SKrS SKJr  S SKJ	r	  S SK
Jr  S SKJr  S SKJrJrJrJrJr  S SKJrJr  S SKJrJr  S	S
KJrJr  S	SKJrJr  S	SK J!r!  \RD                  " \#5      r$ " S S5      r%g)    N)__version__)ConsumerRebalanceListener)AIOKafkaClient)RoundRobinPartitionAssignor)ConsumerStoppedErrorIllegalOperationIllegalStateErrorRecordTooLargeErrorUnsupportedVersionError)ConsumerRecordTopicPartition)commit_structure_validateget_running_loop   )FetcherOffsetResetStrategy)GroupCoordinatorNoGroupCoordinator)SubscriptionStatec            &          \ rS rSrSrSrSrSSS\-   SSSSSSSS	S
SSSSSS\4SSSSSSSSSSSSSSSSSSS.%S jr	\
4S jrS rS rS rS rS  rS! rSAS" jrS# rS$ rS% rS& rS' rS( rS) rS* rS+ rS, rS- rS. rS/ rS0 r SBS1 jr!S2 r"S3 r#S4\$4S5 jr%S6SS7.S4\&\'\(\$   4   4S8 jjr)S9 r*S: r+S; r,S< r-S4\$4S= jr.S> r/S? r0S@r1g)CAIOKafkaConsumer   ai,  
A client that consumes records from a Kafka cluster.

The consumer will transparently handle the failure of servers in the Kafka
cluster, and adapt as topic-partitions are created or migrate between
brokers.

It also interacts with the assigned Kafka Group Coordinator node to allow
multiple consumers to load balance consumption of topics (feature of Kafka
>= 0.9.0.0).

.. _kip-62:
    https://cwiki.apache.org/confluence/display/KAFKA/KIP-62%3A+Allow+consumer+to+send+heartbeats+from+a+background+thread

Arguments:
    *topics (list(str)): optional list of topics to subscribe to. If not set,
        call :meth:`.subscribe` or :meth:`.assign` before consuming records.
        Passing topics directly is same as calling :meth:`.subscribe` API.
    bootstrap_servers (str, list(str)): a ``host[:port]`` string (or list of
        ``host[:port]`` strings) that the consumer should contact to bootstrap
        initial cluster metadata.

        This does not have to be the full node list.
        It just needs to have at least one broker that will respond to a
        Metadata API Request. Default port is 9092. If no servers are
        specified, will default to ``localhost:9092``.
    client_id (str): a name for this client. This string is passed in
        each request to servers and can be used to identify specific
        server-side log entries that correspond to this client. Also
        submitted to :class:`~.consumer.group_coordinator.GroupCoordinator`
        for logging with respect to consumer group administration. Default:
        ``aiokafka-{version}``
    group_id (str or None): name of the consumer group to join for dynamic
        partition assignment (if enabled), and to use for fetching and
        committing offsets. If None, auto-partition assignment (via
        group coordinator) and offset commits are disabled.
        Default: None
    group_instance_id (str or None): name of the group instance ID used for
        static membership (KIP-345)
    key_deserializer (Callable): Any callable that takes a
        raw message key and returns a deserialized key.
    value_deserializer (Callable, Optional): Any callable that takes a
        raw message value and returns a deserialized value.
    fetch_min_bytes (int): Minimum amount of data the server should
        return for a fetch request, otherwise wait up to
        `fetch_max_wait_ms` for more data to accumulate. Default: 1.
    fetch_max_bytes (int): The maximum amount of data the server should
        return for a fetch request. This is not an absolute maximum, if
        the first message in the first non-empty partition of the fetch
        is larger than this value, the message will still be returned
        to ensure that the consumer can make progress. NOTE: consumer
        performs fetches to multiple brokers in parallel so memory
        usage will depend on the number of brokers containing
        partitions for the topic.
        Supported Kafka version >= 0.10.1.0. Default: 52428800 (50 Mb).
    fetch_max_wait_ms (int): The maximum amount of time in milliseconds
        the server will block before answering the fetch request if
        there isn't sufficient data to immediately satisfy the
        requirement given by fetch_min_bytes. Default: 500.
    max_partition_fetch_bytes (int): The maximum amount of data
        per-partition the server will return. The maximum total memory
        used for a request ``= #partitions * max_partition_fetch_bytes``.
        This size must be at least as large as the maximum message size
        the server allows or else it is possible for the producer to
        send messages larger than the consumer can fetch. If that
        happens, the consumer can get stuck trying to fetch a large
        message on a certain partition. Default: 1048576.
    max_poll_records (int): The maximum number of records returned in a
        single call to :meth:`.getmany`. Defaults ``None``, no limit.
    request_timeout_ms (int): Client request timeout in milliseconds.
        Default: 40000.
    retry_backoff_ms (int): Milliseconds to backoff when retrying on
        errors. Default: 100.
    auto_offset_reset (str): A policy for resetting offsets on
        :exc:`.OffsetOutOfRangeError` errors: ``earliest`` will move to the oldest
        available message, ``latest`` will move to the most recent, and
        ``none`` will raise an exception so you can handle this case.
        Default: ``latest``.
    enable_auto_commit (bool): If true the consumer's offset will be
        periodically committed in the background. Default: True.
    auto_commit_interval_ms (int): milliseconds between automatic
        offset commits, if enable_auto_commit is True. Default: 5000.
    check_crcs (bool): Automatically check the CRC32 of the records
        consumed. This ensures no on-the-wire or on-disk corruption to
        the messages occurred. This check adds some overhead, so it may
        be disabled in cases seeking extreme performance. Default: True
    metadata_max_age_ms (int): The period of time in milliseconds after
        which we force a refresh of metadata even if we haven't seen any
        partition leadership changes to proactively discover any new
        brokers or partitions. Default: 300000
    partition_assignment_strategy (list): List of objects to use to
        distribute partition ownership amongst consumer instances when
        group management is used. This preference is implicit in the order
        of the strategies in the list. When assignment strategy changes:
        to support a change to the assignment strategy, new versions must
        enable support both for the old assignment strategy and the new
        one. The coordinator will choose the old assignment strategy until
        all members have been updated. Then it will choose the new
        strategy. Default: [:class:`.RoundRobinPartitionAssignor`]

    max_poll_interval_ms (int): Maximum allowed time between calls to
        consume messages (e.g., :meth:`.getmany`). If this interval
        is exceeded the consumer is considered failed and the group will
        rebalance in order to reassign the partitions to another consumer
        group member. If API methods block waiting for messages, that time
        does not count against this timeout. See `KIP-62`_ for more
        information. Default 300000
    rebalance_timeout_ms (int): The maximum time server will wait for this
        consumer to rejoin the group in a case of rebalance. In Java client
        this behaviour is bound to `max.poll.interval.ms` configuration,
        but as ``aiokafka`` will rejoin the group in the background, we
        decouple this setting to allow finer tuning by users that use
        :class:`.ConsumerRebalanceListener` to delay rebalacing. Defaults
        to ``session_timeout_ms``
    session_timeout_ms (int): Client group session and failure detection
        timeout. The consumer sends periodic heartbeats
        (`heartbeat.interval.ms`) to indicate its liveness to the broker.
        If no hearts are received by the broker for a group member within
        the session timeout, the broker will remove the consumer from the
        group and trigger a rebalance. The allowed range is configured with
        the **broker** configuration properties
        `group.min.session.timeout.ms` and `group.max.session.timeout.ms`.
        Default: 10000
    heartbeat_interval_ms (int): The expected time in milliseconds
        between heartbeats to the consumer coordinator when using
        Kafka's group management feature. Heartbeats are used to ensure
        that the consumer's session stays active and to facilitate
        rebalancing when new consumers join or leave the group. The
        value must be set lower than `session_timeout_ms`, but typically
        should be set no higher than 1/3 of that value. It can be
        adjusted even lower to control the expected time for normal
        rebalances. Default: 3000

    consumer_timeout_ms (int): maximum wait timeout for background fetching
        routine. Mostly defines how fast the system will see rebalance and
        request new data for new partitions. Default: 200
    api_version (str): specify which kafka API version to use.
        :class:`AIOKafkaConsumer` supports Kafka API versions >=0.9 only.
        If set to ``auto``, will attempt to infer the broker version by
        probing various APIs. Default: ``auto``
    security_protocol (str): Protocol used to communicate with brokers.
        Valid values are: ``PLAINTEXT``, ``SSL``, ``SASL_PLAINTEXT``,
        ``SASL_SSL``. Default: ``PLAINTEXT``.
    ssl_context (ssl.SSLContext): pre-configured :class:`~ssl.SSLContext`
        for wrapping socket connections. Directly passed into asyncio's
        :meth:`~asyncio.loop.create_connection`. For more information see
        :ref:`ssl_auth`. Default: None.
    exclude_internal_topics (bool): Whether records from internal topics
        (such as offsets) should be exposed to the consumer. If set to True
        the only way to receive records from an internal topic is
        subscribing to it. Requires 0.10+ Default: True
    connections_max_idle_ms (int): Close idle connections after the number
        of milliseconds specified by this config. Specifying `None` will
        disable idle checks. Default: 540000 (9 minutes).
    isolation_level (str): Controls how to read messages written
        transactionally.

        If set to ``read_committed``, :meth:`.getmany` will only return
        transactional messages which have been committed.
        If set to ``read_uncommitted`` (the default), :meth:`.getmany` will
        return all messages, even transactional messages which have been
        aborted.

        Non-transactional messages will be returned unconditionally in
        either mode.

        Messages will always be returned in offset order. Hence, in
        `read_committed` mode, :meth:`.getmany` will only return
        messages up to the last stable offset (LSO), which is the one less
        than the offset of the first open transaction. In particular any
        messages appearing after messages belonging to ongoing transactions
        will be withheld until the relevant transaction has been completed.
        As a result, `read_committed` consumers will not be able to read up
        to the high watermark when there are in flight transactions.
        Further, when in `read_committed` the seek_to_end method will
        return the LSO. See method docs below. Default: ``read_uncommitted``

    sasl_mechanism (str): Authentication mechanism when security_protocol
        is configured for ``SASL_PLAINTEXT`` or ``SASL_SSL``. Valid values are:
        ``PLAIN``, ``GSSAPI``, ``SCRAM-SHA-256``, ``SCRAM-SHA-512``,
        ``OAUTHBEARER``.
        Default: ``PLAIN``
    sasl_plain_username (str): username for SASL ``PLAIN`` authentication.
        Default: None
    sasl_plain_password (str): password for SASL ``PLAIN`` authentication.
        Default: None
    sasl_oauth_token_provider (~aiokafka.abc.AbstractTokenProvider):
        OAuthBearer token provider instance.
        Default: None

Note:
    Many configuration parameters are taken from Java Client:
    https://kafka.apache.org/documentation.html#newconsumerconfigs

N	localhostz	aiokafka-i  i   r   i   i@  d   latestTi  i i'  i     	PLAINTEXTautoi`= read_uncommittedPLAINkafka)%loopbootstrap_servers	client_idgroup_idgroup_instance_idkey_deserializervalue_deserializerfetch_max_wait_msfetch_max_bytesfetch_min_bytesmax_partition_fetch_bytesrequest_timeout_msretry_backoff_msauto_offset_resetenable_auto_commitauto_commit_interval_ms
check_crcsmetadata_max_age_mspartition_assignment_strategymax_poll_interval_msrebalance_timeout_mssession_timeout_msheartbeat_interval_msconsumer_timeout_msmax_poll_recordsssl_contextsecurity_protocolapi_versionexclude_internal_topicsconnections_max_idle_msisolation_levelsasl_mechanismsasl_plain_passwordsasl_plain_usernamesasl_kerberos_service_namesasl_kerberos_domain_namesasl_oauth_token_providerc       %            Uc  [        5       nO[        R                  " S[        SS9  Ub&  [	        U[
        5      (       a  US:  a  [        S5      eUc  Un[        S0 SU_SU_SU_S	U_S
U_SU_SU_SU_SU_SU_SU _SU"_SU!_SU#_SU$_SU%_6U l        X@l	        XPl
        UU l        UU l        Xl        Xl        Xl        Xl        UU l        UU l        X`l        Xpl        Xl        Xl        Xl        Xl        UU l        UU l        US-  U l        UU l        UU l        UU l        UU l        [A        US9U l!        S U l"        S U l#        Xl$        URK                  5       (       a/  [L        RN                  " [P        RR                  " S5      5      U l*        SU l+        U&(       aF  U RY                  U&5      n&U R                  R[                  U&5        U RB                  R]                  U&S9  g g )NzOThe loop argument is deprecated since 0.7.1, and scheduled for removal in 0.9.0   )
stacklevelr   z-`max_poll_records` should be positive Integerr"   r#   r$   r3   r-   r.   r=   r;   r<   r?   rA   rC   rB   rD   rE   rF     )r"   F)topics )/r   warningswarnDeprecationWarning
isinstanceint
ValueErrorr   _client	_group_id_group_instance_id_heartbeat_interval_ms_session_timeout_ms_retry_backoff_ms_auto_offset_reset_request_timeout_ms_enable_auto_commit_auto_commit_interval_ms_partition_assignment_strategy_key_deserializer_value_deserializer_fetch_min_bytes_fetch_max_bytes_fetch_max_wait_ms_max_partition_fetch_bytes_exclude_internal_topics_max_poll_records_consumer_timeout_isolation_level_rebalance_timeout_ms_max_poll_interval_ms_check_crcsr   _subscription_fetcher_coordinator_loop	get_debug	tracebackextract_stacksys	_getframe_source_traceback_closed_validate_topics
set_topics	subscribe)'selfr"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rK   s'                                          _C:\Suresh\moveshuttle\MDcreated\moveengine\venv\Lib\site-packages\aiokafka/consumer/consumer.py__init__AIOKafkaConsumer.__init__   sB   R <#%DMM5"	 '+S115E5ILMM'#5 % 

/
  
 !4	

  2
 .
 $
 $
 0
 %<
 *
 !4
 !4
 (B
 '@
  '@!
& ""3&;##5 !1"3#5 #5 (?%.K+!1#5  / /"3*C'(?%!1!4t!; /%9"%9"%.D9 
>>%.%<%<S]]1=M%ND"**62FLL##F+(((7     c                     U R                   SL aV  UR                  SU < 3[        U S9  U SS.nU R                  b  U R                  US'   U R                  R                  U5        g g )NFzUnclosed AIOKafkaConsumer )sourcezUnclosed AIOKafkaConsumer)consumermessagesource_traceback)ru   rN   ResourceWarningrt   rn   call_exception_handler)ry   	_warningscontexts      rz   __del__AIOKafkaConsumer.__del__Y  st    <<5 NN,TH5   !6G %%1.2.D.D*+JJ--g6 !r}   c                   #    U R                   [        5       L d   S5       eU R                  b   S5       eU R                  R	                  5       I Sh  vN   U R                  5       I Sh  vN   U R                  R                  S:  a"  [        SU R                  R                   35      eU R                  S:X  a%  U R                  R                  S:  a  [        S5      e[        U R                  U R                  U R                  U R                  U R                  U R                  U R                   U R"                  U R$                  U R&                  U R(                  U R*                  U R                  S	9U l        U R,                  Gb0  [/        U R                  U R                  U R,                  U R0                  U R2                  U R4                  U R(                  U R6                  U R8                  U R:                  U R<                  U R>                  U R@                  S
9U l!        U R                  RD                  b|  U R                  RG                  5       (       a#  U R                  RI                  5       I Sh  vN   gU RB                  RK                  U R                  RD                  RL                  5        gg[O        U R                  U R                  U R<                  S9U l!        U R                  RD                  b\  U R                  RG                  5       (       a<  U R                  RQ                  5       I Sh  vN   U RB                  RS                  SS9  ggg GN
 GN N N(7f)zConnect to Kafka cluster. This will:

* Load metadata for all cluster nodes and partition allocation
* Wait for possible topic autocreation
* Join group if ``group_id`` provided
z8Please create objects with the same loop as running withNzDid you call `start` twice?)r   	   zUnsupported Kafka version: read_committed)r      zJ`read_committed` isolation_level available only for Brokers 0.11 and above)r'   r(   r+   r*   r)   r,   r2   fetcher_timeoutr.   r/   r@   )r%   r&   r8   r7   r.   r0   r1   	assignorsr>   r6   r5   )r>   T)check_unknown)*rn   r   rl   rS   	bootstrap_wait_topicsr=   rR   rg   r   r   rk   r^   r_   r`   ra   rb   rc   rj   rf   rX   rY   rT   r   rU   rV   rW   r[   r\   r]   rd   rh   ri   rm   subscriptionpartitions_auto_assignedwait_for_assignment!start_commit_offsets_refresh_task
assignmentr   force_metadata_updateassign_all_partitionsry   s    rz   startAIOKafkaConsumer.starth  s     JJ*,,	FE	F,}}$C&CC$ll$$&&&!!!<<##f,:4<<;S;S:TUVV !!%55((72)! 
  LL!33#77 11 11"55&*&E&E'' 22!33"55 11
  >>% 0"""&"9"9&*&A&A#'#;#;!%!7!7#'#;#;(,(E(E==(,(E(E%)%?%?%)%?%?!D !!..:%%>>@@ ,,@@BBB
 %%GG**77BB ; !3""(,(E(E!D ""//;&&??AA ll88:::!!77d7K B <M 	'!f C. ;sJ   AM&MM&*M+HM&9M":CM&;M$<!M&M&"M&$M&c                    #    U R                   R                  bK  U R                   R                  R                   H&  nU R                  R	                  U5      I S h  vN   M(     g g  N
7fN)rk   r   rK   rS   _wait_on_metadatary   topics     rz   r   AIOKafkaConsumer._wait_topics  sT     **6++88??ll44U;;; @ 7;s   AA(A&A(c                 n    [        U[        [        [        45      (       d  [	        S5      e[        U5      $ )Nz Topics should be list of strings)rP   tuplesetlist	TypeError)ry   rK   s     rz   rv   !AIOKafkaConsumer._validate_topics  s,    &5#t"455>??6{r}   c                 \   U R                   R                  U5        U R                  R                  U Vs/ s H  o"R                  PM     sn5        U R
                  bJ  U R                  b<  U R                   R                  R                  nU R
                  R                  U5        gggs  snf )a  Manually assign a list of :class:`.TopicPartition` to this consumer.

This interface does not support incremental assignment and will
replace the previous assignment (if there was one).

Arguments:
    partitions (list(TopicPartition)): assignment for this instance.

Raises:
    IllegalStateError: if consumer has already called :meth:`subscribe`

Warning:
    It is not possible to use both manual partition assignment with
    :meth:`assign` and group assignment with :meth:`subscribe`.

Note:
    Manual topic assignment through this method does not use the
    consumer's group management functionality. As such, there will be
    **no rebalance operation triggered** when group membership or
    cluster and topic metadata change.
N)
rk   assign_from_userrS   rw   r   rm   rT   r   r   r   )ry   
partitionstpr   s       rz   assignAIOKafkaConsumer.assign  s    , 	++J7J ?JbJ ?@ (T^^-G++88CCJ??
K .H( !@s   B)c                 6    U R                   R                  5       $ )a+  Get the set of partitions currently assigned to this consumer.

If partitions were directly assigned using :meth:`assign`, then this will
simply return the same partitions that were previously assigned.

If topics were subscribed using :meth:`subscribe`, then this will give
the set of topic partitions currently assigned to the consumer (which
may be empty if the assignment hasn't happened yet or if the partitions
are in the process of being reassigned).

Returns:
    set(TopicPartition): the set of partitions currently assigned to
    this consumer
)rk   assigned_partitionsr   s    rz   r   AIOKafkaConsumer.assignment  s     !!5577r}   c                   #    U R                   (       a  g[        R                  S5        SU l         U R                  (       a"  U R                  R	                  5       I Sh  vN   U R
                  (       a"  U R
                  R	                  5       I Sh  vN   U R                  R	                  5       I Sh  vN   [        R                  S5        g No N> N7f)zClose the consumer, while waiting for finalizers:

* Commit last consumed message if autocommit enabled
* Leave group if used Consumer Groups
NzClosing the KafkaConsumer.TzThe KafkaConsumer has closed.)ru   logdebugrm   closerl   rS   r   s    rz   stopAIOKafkaConsumer.stop  s      <<		./##))+++==--%%'''ll  """		12	 ,'"s6   ACC 2CC!C4C5CCCc                   #    U R                   c  [        S5      eU R                  R                  nUc  [	        S5      eUR
                  nUc  [	        S5      eUc  UR                  5       nO2[        U5      nU H!  nXCR                  ;  d  M  [	        SU S35      e   U R                  R                  X15      I Sh  vN   g N7f)a  Commit offsets to Kafka.

This commits offsets only to Kafka. The offsets committed using this
API will be used on the first fetch after every rebalance and also on
startup. As such, if you need to store offsets in anything other than
Kafka, this API should not be used.

Currently only supports kafka-topic offset storage (not Zookeeper)

When explicitly passing `offsets` use either offset of next record,
or tuple of offset and metadata::

    tp = TopicPartition(msg.topic, msg.partition)
    metadata = "Some utf-8 metadata"
    # Either
    await consumer.commit({tp: msg.offset + 1})
    # Or position directly
    await consumer.commit({tp: (msg.offset + 1, metadata)})

.. note:: If you want *fire and forget* commit, like
    :meth:`~kafka.KafkaConsumer.commit_async` in `kafka-python`_, just
    run it in a task. Something like::

        fut = loop.create_task(consumer.commit())
        fut.add_done_callback(on_commit_done)

Arguments:
    offsets (dict, Optional): A mapping from :class:`.TopicPartition` to
      ``(offset, metadata)`` to commit with the configured ``group_id``.
      Defaults to current consumed offsets for all subscribed partitions.
Raises:
    ~aiokafka.errors.CommitFailedError: If membership already changed on broker.
    ~aiokafka.errors.IllegalOperation: If used with ``group_id == None``.
    ~aiokafka.errors.IllegalStateError: If partitions not assigned.
    ~aiokafka.errors.KafkaError: If commit failed on broker side. This
        could be due to invalid offset, too long metadata, authorization
        failure, etc.
    ValueError: If offsets is of wrong format.

.. versionchanged:: 0.4.0

    Changed :exc:`AssertionError` to
    :exc:`~aiokafka.errors.IllegalStateError` in case of unassigned
    partition.

.. versionchanged:: 0.4.0

    Will now raise :exc:`~aiokafka.errors.CommitFailedError` in case
    membership changed, as (possibly) this partition is handled by
    another consumer.

.. _kafka-python: https://github.com/dpkp/kafka-python
NRequires group_idzNot subscribed to any topicszNo partitions assigned
Partition  is not assigned)rT   r   rk   r   r	   r   all_consumed_offsetsr   tpsrm   commit_offsets)ry   offsetsr   r   r   s        rz   commitAIOKafkaConsumer.commit  s     l >>!"#677))66#$BCC!,,
#$<==? 557G/8G^^++j<L,MNN  ..zCCCs   BC/C=C>Cc                    #    U R                   c  [        S5      eU R                  R                  U/5      I Sh  vN nX;   a  X!   R                  nUS:X  a  SnU$ SnU$  N%7f)aY  Get the last committed offset for the given partition. (whether the
commit happened by this process or another).

This offset will be used as the position for the consumer in the event
of a failure.

This call will block to do a remote call to get the latest offset, as
those are not cached by consumer (Transactional Producer can change
them without Consumer knowledge as of Kafka 0.11.0)

Arguments:
    partition (TopicPartition): the partition to check

Returns:
    The last committed offset, or None if there was no prior commit.

Raises:
    IllegalOperation: If used with ``group_id == None``
Nr   )rT   r   rm   fetch_committed_offsetsoffset)ry   	partition
commit_map	committeds       rz   r   AIOKafkaConsumer.committedV  ss     ( >>!"#677,,DDi[QQ
""-44IB 	  I Rs   8A"A &A"c                 r   #    U R                   R                  5       I Sh  vN nUR                  5       $  N7f)zIGet all topics the user is authorized to view.

Returns:
    set: topics
N)rS   fetch_all_metadatarK   )ry   clusters     rz   rK   AIOKafkaConsumer.topicsv  s.      7799~~ :s   757c                 L    U R                   R                  R                  U5      $ )zGet metadata about the partitions for a given topic.

This method will return `None` if Consumer does not already have
metadata for this topic.

Arguments:
    topic (str): topic to check

Returns:
    set: partition ids
)rS   r   partitions_for_topicr   s     rz   r   %AIOKafkaConsumer.partitions_for_topic  s     ||##88??r}   c                   #     U R                   R                  U5      (       d  [        SU S35      eU R                   R                  R                  nUR                  U5      nUR                  (       Gd  U R                  R                  5         [        R                  " UR                  5       UR                  /U R                  S-  [        R                  S9I Sh  vN   UR                  (       d  U R                   R                  c  [        SU S35      eU R                   R                  R                  c<  U R                  R                  5         U R                   R                  5       I Sh  vN   GMw  UR                   $  N N7f)a  Get the offset of the *next record* that will be fetched (if a
record with that offset exists on broker).

Arguments:
    partition (TopicPartition): partition to check

Returns:
    int: offset

Raises:
    IllegalStateError: partition is not assigned

.. versionchanged:: 0.4.0

    Changed :exc:`AssertionError` to
    :exc:`~aiokafka.errors.IllegalStateError` in case of unassigned
    partition
r   r   rJ   timeoutreturn_whenN)rk   is_assignedr	   r   r   state_valuehas_valid_positionrm   check_errorsasynciowaitwait_for_positionunassign_futurerZ   FIRST_COMPLETEDr   position)ry   r   r   tp_states       rz   r   AIOKafkaConsumer.position  sT    & %%11)<<'*YK?O(PQQ++88CCJ!--i8H...!!..0ll//1:3M3MN 44t; ' 7 7  
  22))66>/(3CD  ))66AAI))668"00DDFFF$$$ Gs%   CF
FBF
2F3F
F
c                     U R                   R                  U5      (       d   S5       eU R                   R                  R                  nUR	                  U5      R
                  $ )ab  Last known highwater offset for a partition.

A highwater offset is the offset that will be assigned to the next
message that is produced. It may be useful for calculating lag, by
comparing with the reported position. Note that both position and
highwater refer to the *next* offset - i.e., highwater offset is one
greater than the newest available message.

Highwater offsets are returned as part of ``FetchResponse``, so will
not be available if messages for this partition were not requested yet.

Arguments:
    partition (TopicPartition): partition to check

Returns:
    int or None: offset if available
Partition is not assigned)rk   r   r   r   r   	highwaterry   r   r   s      rz   r   AIOKafkaConsumer.highwater  sU    $ !!--i88U:UU8''44??
%%i0:::r}   c                     U R                   R                  U5      (       d   S5       eU R                   R                  R                  nUR	                  U5      R
                  $ )a  Returns the Last Stable Offset of a topic. It will be the last
offset up to which point all transactions were completed. Only
available in with isolation_level `read_committed`, in
`read_uncommitted` will always return -1. Will return None for older
Brokers.

As with :meth:`highwater` will not be available until some messages are
consumed.

Arguments:
    partition (TopicPartition): partition to check

Returns:
    int or None: offset if available
r   )rk   r   r   r   r   lsor   s      rz   last_stable_offset#AIOKafkaConsumer.last_stable_offset  sU      !!--i88U:UU8''44??
%%i0444r}   c                     U R                   R                  U5      (       d   S5       eU R                   R                  R                  nUR	                  U5      R
                  $ )a  Returns the timestamp of the last poll of this partition (in ms).
It is the last time :meth:`highwater` and :meth:`last_stable_offset` were
updated. However it does not mean that new messages were received.

As with :meth:`highwater` will not be available until some messages are
consumed.

Arguments:
    partition (TopicPartition): partition to check

Returns:
    int or None: timestamp if available
r   )rk   r   r   r   r   	timestampr   s      rz   last_poll_timestamp$AIOKafkaConsumer.last_poll_timestamp  sU     !!--i88U:UU8''44??
%%i0:::r}   c                     [        U[        5      (       a  US:  a  [        S5      e[        R	                  SX!5        U R
                  R                  X5        g)ax  Manually specify the fetch offset for a :class:`.TopicPartition`.

Overrides the fetch offsets that the consumer will use on the next
:meth:`getmany`/:meth:`getone` call. If this API is invoked for the same
partition more than once, the latest offset will be used on the next
fetch.

Note:
    You may lose data if this API is arbitrarily used in the middle
    of consumption to reset the fetch offsets. Use it either on
    rebalance listeners or after all pending messages are processed.

Arguments:
    partition (TopicPartition): partition for seek operation
    offset (int): message offset in partition

Raises:
    ValueError: if offset is not a positive integer
    IllegalStateError: partition is not currently assigned

.. versionchanged:: 0.4.0

    Changed :exc:`AssertionError` to
    :exc:`~aiokafka.errors.IllegalStateError` and :exc:`ValueError` in
    respective cases.
r   z!Offset must be a positive integerz%Seeking to offset %s for partition %sN)rP   rQ   rR   r   r   rl   seek_to)ry   r   r   s      rz   seekAIOKafkaConsumer.seek  sD    6 &#&&&1*@AA		96Mi0r}   c                   #    [        S U 5       5      (       d  [        S5      eU(       d)  U R                  R                  5       nU(       d   S5       eO<[	        U5      U R                  R                  5       -
  nU(       a  [        SU S35      eU H  n[        R                  SU5        M     U R                  R                  U[        R                  5      nU R                  R                  R                  n[        R                  " XER                   /U R"                  S-  [        R$                  S9I S	h  vN   U R&                  R)                  5         UR+                  5       $  N.7f)
am  Seek to the oldest available offset for partitions.

Arguments:
    *partitions: Optionally provide specific :class:`.TopicPartition`,
        otherwise default to all assigned partitions.

Raises:
    IllegalStateError: If any partition is not currently assigned
    TypeError: If partitions are not instances of :class:`.TopicPartition`

.. versionadded:: 0.3.0

c              3   B   #    U  H  n[        U[        5      v   M     g 7fr   rP   r   .0ps     rz   	<genexpr>5AIOKafkaConsumer.seek_to_beginning.<locals>.<genexpr>"       E*Q:a00*   +partitions must be TopicPartition instances$No partitions are currently assignedPartitions  are not assignedz$Seeking to beginning of partition %srJ   r   N)allr   rk   r   r   r	   r   r   rl   request_offset_resetr   EARLIESTr   r   r   r   r   rZ   r   rm   r   donery   r   not_assignedr   futr   s         rz   seek_to_beginning"AIOKafkaConsumer.seek_to_beginning  s0     E*EEEIJJ++??AJEEE:z?T-?-?-S-S-UUL'+l^CT(UVVBII<bA  mm00+44
 ''44??
ll,,-,,t3//
 	
 	

 	&&(xxz	
   D7E*9E(:/E*c                   #    [        S U 5       5      (       d  [        S5      eU(       d)  U R                  R                  5       nU(       d   S5       eO<[	        U5      U R                  R                  5       -
  nU(       a  [        SU S35      eU H  n[        R                  SU5        M     U R                  R                  U[        R                  5      nU R                  R                  R                  n[        R                  " XER                   /U R"                  S-  [        R$                  S9I S	h  vN   U R&                  R)                  5         UR+                  5       $  N.7f)
ar  Seek to the most recent available offset for partitions.

Arguments:
    *partitions: Optionally provide specific :class:`.TopicPartition`,
        otherwise default to all assigned partitions.

Raises:
    IllegalStateError: If any partition is not currently assigned
    TypeError: If partitions are not instances of :class:`.TopicPartition`

.. versionadded:: 0.3.0

c              3   B   #    U  H  n[        U[        5      v   M     g 7fr   r   r   s     rz   r   /AIOKafkaConsumer.seek_to_end.<locals>.<genexpr>J  r   r   r   r   r   r   zSeeking to end of partition %srJ   r   N)r   r   rk   r   r   r	   r   r   rl   r   r   LATESTr   r   r   r   r   rZ   r   rm   r   r  r  s         rz   seek_to_endAIOKafkaConsumer.seek_to_end<  s)     E*EEEIJJ++??AJEEE:z?T-?-?-S-S-UUL'+l^CT(UVVBII6; mm00=P=W=WX''44??
ll,,-,,t3//
 	
 	

 	&&(xxz	
r  c                   #    [        S U 5       5      (       d  [        S5      eU(       d)  U R                  R                  5       nU(       d   S5       eO<[	        U5      U R                  R                  5       -
  nU(       a  [        SU S35      e0 nU Hb  nU R                  U5      I Sh  vN nXSU'   [        R                  SXE5        U(       d  M?  US:  d  MG  U R                  R                  XE5        Md     U$  NP7f)	a%  Seek to the committed offset for partitions.

Arguments:
    *partitions: Optionally provide specific :class:`.TopicPartition`,
        otherwise default to all assigned partitions.

Returns:
    dict(TopicPartition, int): mapping
    of the currently committed offsets.

Raises:
    IllegalStateError: If any partition is not currently assigned
    IllegalOperation: If used with ``group_id == None``

.. versionchanged:: 0.3.0

    Changed :exc:`AssertionError` to
    :exc:`~aiokafka.errors.IllegalStateError` in case of unassigned
    partition
c              3   B   #    U  H  n[        U[        5      v   M     g 7fr   r   r   s     rz   r   5AIOKafkaConsumer.seek_to_committed.<locals>.<genexpr>v  r   r   r   r   r   r   Nz'Seeking to committed of partition %s %sr   )r   r   rk   r   r   r	   r   r   r   rl   r   )ry   r   r  committed_offsetsr   r   s         rz   seek_to_committed"AIOKafkaConsumer.seek_to_committeda  s     * E*EEEIJJ++??AJEEE:z?T-?-?-S-S-UUL'+l^CT(UVVB>>"--F$*b!II?Lv&1*%%b1  !  .s   B*C?,C=-#C?C?"C?c                 `  #    U R                   R                  S::  a"  [        SU R                   R                   35      eUR                  5        H*  u  p#[	        U5      X'   US:  d  M  [        SU SU S35      e   U R                  R                  XR                  5      I Sh  vN nU$  N7f)a  
Look up the offsets for the given partitions by timestamp. The returned
offset for each partition is the earliest offset whose timestamp is
greater than or equal to the given timestamp in the corresponding
partition.

The consumer does not have to be assigned the partitions.

If the message format version in a partition is before 0.10.0, i.e.
the messages do not have timestamps, ``None`` will be returned for that
partition.

Note:
    This method may block indefinitely if the partition does not exist.

Arguments:
    timestamps (dict(TopicPartition, int)): mapping from partition
        to the timestamp to look up. Unit should be milliseconds since
        beginning of the epoch (midnight Jan 1, 1970 (UTC))

Returns:
    dict(TopicPartition, OffsetAndTimestamp): mapping from
    partition to the timestamp and offset of the first message with
    timestamp greater than or equal to the target timestamp.

Raises:
    ValueError: If the target timestamp is negative
    UnsupportedVersionError: If the broker does not support looking
        up the offsets by timestamp.
    KafkaTimeoutError: If fetch failed in `request_timeout_ms`

.. versionadded:: 0.3.0

r   
   r   8offsets_for_times API not supported for cluster version r   zThe target time for partition z is z%. The target time cannot be negative.N)	rS   r=   r   itemsrQ   rR   rl   get_offsets_by_timesrZ   )ry   
timestampsr   tsr   s        rz   offsets_for_times"AIOKafkaConsumer.offsets_for_times  s     F <<##z1)((,(@(@'AC  !&&(FB WJNAv 4RDRD A; ;  ) ::00
 
 
s   A#B.)<B.%B,&B.c                    #    U R                   R                  S::  a"  [        SU R                   R                   35      eU R                  R	                  XR
                  5      I Sh  vN nU$  N7f)av  Get the first offset for the given partitions.

This method does not change the current consumer position of the
partitions.

Note:
    This method may block indefinitely if the partition does not exist.

Arguments:
    partitions (list[TopicPartition]): List of :class:`.TopicPartition`
        instances to fetch offsets for.

Returns:
    dict [TopicPartition, int]: mapping of partition to  earliest
    available offset.

Raises:
    UnsupportedVersionError: If the broker does not support looking
        up the offsets by timestamp.
    KafkaTimeoutError: If fetch failed in `request_timeout_ms`.

.. versionadded:: 0.3.0

r  r  N)rS   r=   r   rl   beginning_offsetsrZ   ry   r   r   s      rz   r   "AIOKafkaConsumer.beginning_offsets  sq     2 <<##z1)((,(@(@'AC  7700
 
 
   A%A0'A.(A0c                    #    U R                   R                  S::  a"  [        SU R                   R                   35      eU R                  R	                  XR
                  5      I Sh  vN nU$  N7f)a  Get the last offset for the given partitions. The last offset of a
partition is the offset of the upcoming message, i.e. the offset of the
last available message + 1.

This method does not change the current consumer position of the
partitions.

Note:
    This method may block indefinitely if the partition does not exist.

Arguments:
    partitions (list[TopicPartition]): List of :class:`.TopicPartition`
        instances to fetch offsets for.

Returns:
    dict [TopicPartition, int]: mapping of partition to last
    available offset + 1.

Raises:
    UnsupportedVersionError: If the broker does not support looking
        up the offsets by timestamp.
    KafkaTimeoutError: If fetch failed in ``request_timeout_ms``

.. versionadded:: 0.3.0

r  r  N)rS   r=   r   rl   end_offsetsrZ   r!  s      rz   r%  AIOKafkaConsumer.end_offsets  sk     6 <<##z1)((,(@(@'AC  11*>V>VWW Xr#  c                 `   U(       d  U(       d  [        S5      eU(       a  U(       a  [        S5      eUb   [        U[        5      (       d  [        S5      eUbb   [        R                  " U5      nU R                  R                  X#S9  U R                  R                  / 5        [        R                  SU5        gU(       a  U R                  U5      nU R                  R                  XS9  U R                  R                  U R                  R                  R                   5        U R"                  c8  U R                  R%                  5         U R&                  b  0 U R&                  l        [        R                  S	U5        gg! [        R
                   a  n[        U< SU 35      UeSnAff = f)
a  Subscribe to a list of topics, or a topic regex pattern.

Partitions will be dynamically assigned via a group coordinator.
Topic subscriptions are not incremental: this list will replace the
current assignment (if there is one).

This method is incompatible with :meth:`assign`.

Arguments:
   topics (list): List of topics for subscription.
   pattern (str): Pattern to match available topics. You must provide
       either topics or pattern, but not both.
   listener (ConsumerRebalanceListener): Optionally include listener
       callback, which will be called before and after each rebalance
       operation.
       As part of group management, the consumer will keep track of
       the list of consumers that belong to a particular group and
       will trigger a rebalance operation if one of the following
       events trigger:

       * Number of partitions change for any of the subscribed topics
       * Topic is created or deleted
       * An existing member of the consumer group dies
       * A new member is added to the consumer group

       When any of these events are triggered, the provided listener
       will be invoked first to indicate that the consumer's
       assignment has been revoked, and then again when the new
       assignment has been received. Note that this listener will
       immediately override any listener set in a previous call
       to subscribe. It is guaranteed, however, that the partitions
       revoked/assigned
       through this interface are from topics subscribed in this call.
Raises:
    IllegalStateError: if called after previously calling :meth:`assign`
    ValueError: if neither topics or pattern is provided or both
       are provided
    TypeError: if listener is not a :class:`.ConsumerRebalanceListener`
z/You should provide either `topics` or `pattern`z-You can't provide both `topics` and `pattern`Nz;listener should be an instance of ConsumerRebalanceListenerz is not a valid pattern: )patternlistenerzSubscribed to topic pattern: %s)rK   r)  zSubscribed to topic(s): %s)r   rP   r   recompileerrorrR   rk   subscribe_patternrS   rw   r   inforv   rx   r   rK   rT   r   rm   _metadata_snapshot)ry   rK   r(  r)  errs        rz   rx   AIOKafkaConsumer.subscribe  sl   P 'MNNgKLL
8=V(W(WM  X**W- 000T LL##B'HH6@**62F(((JLL##D$6$6$C$C$J$JK~~% 224$$0;=D%%8HH16:  88 X G;.Gu!MNTWWXs   F F-F((F-c                 .    U R                   R                  $ )zSGet the current topics subscription.

Returns:
    frozenset(str): a set of topics
)rk   rK   r   s    rz   r   AIOKafkaConsumer.subscriptionN  s     !!(((r}   c                     U R                   R                  5         U R                  b  U R                  R	                  5         U R
                  R                  / 5        [        R                  S5        g)z>Unsubscribe from all topics and clear all assigned partitions.Nz;Unsubscribed all topics or patterns and assigned partitions)	rk   unsubscriberT   rm   maybe_leave_grouprS   rw   r   r.  r   s    rz   r5  AIOKafkaConsumer.unsubscribeV  sO    &&(>>%//1#NOr}   returnc                 ^  #    [        S U 5       5      (       d   eU R                  (       a
  [        5       eU R                  R	                  5         U R
                  R                  5          U R                  R                  U5      I Sh  vN nSSS5        U$  N! , (       d  f       W$ = f7f)a  
Get one message from Kafka.
If no new messages prefetched, this method will wait for it.

Arguments:
    partitions (list(TopicPartition)): Optional list of partitions to
        return from. If no partitions specified then returned message
        will be from any partition, which consumer is subscribed to.

Returns:
    ~aiokafka.structs.ConsumerRecord: the message

Will return instance of

.. code:: python

    collections.namedtuple(
        "ConsumerRecord",
        ["topic", "partition", "offset", "key", "value"])

Example usage:

.. code:: python

    while True:
        message = await consumer.getone()
        topic = message.topic
        partition = message.partition
        # Process message
        print(message.offset, message.key, message.value)

c              3   B   #    U  H  n[        U[        5      v   M     g 7fr   r   r   ks     rz   r   *AIOKafkaConsumer.getone.<locals>.<genexpr>  r   r   N)	r   ru   r   rm   r   rk   fetch_contextrl   next_record)ry   r   msgs      rz   getoneAIOKafkaConsumer.getone^  s     B E*EEEEE<<&(( 	&&(--/11*==C 0
 > 0/
s0   A)B-+B
BB
B-B
B*%B-r   )
timeout_msmax_recordsc                  #    [        S U 5       5      (       d   eU R                  (       a
  [        5       eUb&  [        U[        5      (       a  US:  a  [        S5      eU R                  R                  5         US-  nU R                  R                  5          U R                  R                  X4U=(       d    U R                  S9I Sh  vN nSSS5        U$  N! , (       d  f       W$ = f7f)aY  Get messages from assigned topics / partitions.

Prefetched messages are returned in batches by topic-partition.
If messages is not available in the prefetched buffer this method waits
`timeout_ms` milliseconds.

Arguments:
    partitions (list[TopicPartition]): The partitions that need
        fetching message. If no one partition specified then all
        subscribed partitions will be used
    timeout_ms (int, Optional): milliseconds spent waiting if
        data is not available in the buffer. If 0, returns immediately
        with any records that are available currently in the buffer,
        else returns empty. Must not be negative. Default: 0
Returns:
    dict(TopicPartition, list[ConsumerRecord]): topic to list of
    records since the last fetch for the subscribed list of topics and
    partitions

Example usage:


.. code:: python

    data = await consumer.getmany()
    for tp, messages in data.items():
        topic = tp.topic
        partition = tp.partition
        for message in messages:
            # Process message
            print(message.offset, message.key, message.value)

c              3   B   #    U  H  n[        U[        5      v   M     g 7fr   r   r;  s     rz   r   +AIOKafkaConsumer.getmany.<locals>.<genexpr>  r   r   Nr   z(`max_records` must be a positive IntegerrJ   )rD  )r   ru   r   rP   rQ   rR   rm   r   rk   r>  rl   fetched_recordsre   )ry   rC  rD  r   r   recordss         rz   getmanyAIOKafkaConsumer.getmany  s     H E*EEEEE<<&((";,,aGHH 	&&(t#--/ MM991V@V@V :  G 0  0/ s0   BC-1C
CC
C-C
C*%C-c                     [        S U 5       5      (       d  [        S5      eU H4  n[        R                  SU5        U R                  R                  U5        M6     g)a  Suspend fetching from the requested partitions.

Future calls to :meth:`.getmany` will not return any records from these
partitions until they have been resumed using :meth:`.resume`.

Note: This method does not affect partition subscription.
In particular, it does not cause a group rebalance when automatic
assignment is used.

Arguments:
    *partitions (list[TopicPartition]): Partitions to pause.
c              3   B   #    U  H  n[        U[        5      v   M     g 7fr   r   r   s     rz   r   )AIOKafkaConsumer.pause.<locals>.<genexpr>  r   r   -partitions must be TopicPartition namedtupleszPausing partition %sN)r   r   r   r   rk   pausery   r   r   s      rz   rP  AIOKafkaConsumer.pause  sN     E*EEEKLL#III,i8$$Y/ $r}   c                 6    U R                   R                  5       $ )zsGet the partitions that were previously paused using
:meth:`.pause`.

Returns:
    set[TopicPartition]: partitions
)rk   paused_partitionsr   s    rz   pausedAIOKafkaConsumer.paused  s     !!3355r}   c                     [        S U 5       5      (       d  [        S5      eU H4  n[        R                  SU5        U R                  R                  U5        M6     g)zResume fetching from the specified (paused) partitions.

Arguments:
    *partitions (list[TopicPartition]): Partitions to resume.
c              3   B   #    U  H  n[        U[        5      v   M     g 7fr   r   r   s     rz   r   *AIOKafkaConsumer.resume.<locals>.<genexpr>  r   r   rO  zResuming partition %sN)r   r   r   r   rk   resumerQ  s      rz   rZ  AIOKafkaConsumer.resume  sN     E*EEEKLL#III-y9%%i0 $r}   c                 <    U R                   (       a
  [        5       eU $ r   )ru   r   r   s    rz   	__aiter__AIOKafkaConsumer.__aiter__  s    <<&((r}   c                    #      U R                  5       I Sh  vN $  N! [         a    [        Se[         a    [        R                  S5         Of = fMR  7f)zAsyncio iterator interface for consumer

Note:
    TopicAuthorizationFailedError and OffsetOutOfRangeError
    exceptions can be raised in iterator.
    All other KafkaError exceptions will be logged and not raised
Nzerror in consumer iterator: %s)rA  r   StopAsyncIterationr
   r   	exceptionr   s    rz   	__anext__AIOKafkaConsumer.__anext__  sU      @![[]***' 3(d2& @>?@ s1   A  A /AAAAc                 B   #    U R                  5       I S h  vN   U $  N7fr   )r   r   s    rz   
__aenter__AIOKafkaConsumer.__aenter__   s     jjl 	s   c                 @   #    U R                  5       I S h  vN   g  N7fr   )r   )ry   exc_typeexctbs       rz   	__aexit__AIOKafkaConsumer.__aexit__  s     iiks   )r\   rY   rj   rS   ru   rf   rm   r[   rd   ra   rb   r`   rl   rT   rU   rV   rg   r^   rn   rc   ri   re   r]   rh   rZ   rX   rW   rt   rk   r_   r   )rL   NN)2__name__
__module____qualname____firstlineno____doc__ru   rt   r   r   r{   rM   r   r   r   rv   r   r   r   r   r   rK   r   r   r   r   r   r   r  r  r  r  r   r%  rx   r   r5  r   rA  dictr   r   rJ  rP  rU  rZ  r]  rb  re  rk  __static_attributes__rL   r}   rz   r   r      s   BH G
 %+ "1$" $)'B&D#! "% $ &*  #*"&"&Or8h !) 7WLr<

L>8"3"HDT@ @)%V;,5(;$1@&P#J'!R2h!F!FH;T)P*> *Z '(T5	nd>22	35n0(61
@ @ r}   r   )&r   loggingr*  rr   rp   rM   aiokafkar   aiokafka.abcr   aiokafka.clientr   )aiokafka.coordinator.assignors.roundrobinr   aiokafka.errorsr   r   r	   r
   r   aiokafka.structsr   r   aiokafka.utilr   r   fetcherr   r   group_coordinatorr   r   subscription_stater   	getLoggerrm  r   r   rL   r}   rz   <module>r     sZ      	 
     2 * Q  < E 1 C 1!h hr}   