o
    `jt0                     @  s   d Z ddlmZ ddlZddlZddlmZ ddlZddlm	Z
 ddlmZ ddlmZmZ ddlmZ er<dd	lmZ eeZG d
d dZG dd dZdS )zPTopic management mixin for KafkaAdminClient.

Also defines NewTopic data class.
    )annotationsN)TYPE_CHECKING)IncompatibleBrokerVersion)CreateTopicsRequestDeleteTopicsRequest   )ConfigResourceType)KafkaConnectionManagerc                   @  sn   e Zd ZU dZded< ded< dd Zdd	d
Zedd Z		dddZ	dddZ
edd ZdddZdS )TopicAdminMixinz>Mixin providing topic management methods for KafkaAdminClient.r	   _managerdictconfigc                 C  s"   | j | jd}dd |d D S )zwRetrieve a list of all topic names in the cluster.

        Returns:
            A list of topic name strings.
        Nc                 S  s   g | ]}|d  qS name .0tr   r   Q/home/djax/ivt_ai_plugin/venv/lib/python3.10/site-packages/kafka/admin/_topics.py
<listcomp>$   s    z/TopicAdminMixin.list_topics.<locals>.<listcomp>topicsr   run_get_cluster_metadata)selfmetadatar   r   r   list_topics   s   zTopicAdminMixin.list_topicsNc                 C  s   | j | j|}|d S )a!  Fetch metadata for the specified topics or all topics if None.

        Keyword Arguments:
            topics (list, optional): A list of topic names or
                :class:`uuid.UUID` topic ids (KIP-516). Strings and UUIDs may
                be mixed. Describing by id requires broker >= 2.8
                (MetadataRequest v12+); name-based describe works on any
                broker. If None, metadata for all topics is retrieved.

        Returns:
            A list of dicts describing each topic (including partition info).
        r   r   )r   r   r   r   r   r   describe_topics&   s   zTopicAdminMixin.describe_topicsc                   sF  t j}|j |jg }t| trN|  D ]8\}}|di }||||dd|dd fdd|di  D fdd|di  D d	 qnJt	d
d | D rg| D ]}|||ddd qYn1t	dd | D r| D ]%}|||j
|j|j fdd|j D fdd|j D d	 qr|std|  |S )Nconfigsnum_partitionsreplication_factorc                      g | ]
\}} ||d qS )partition_index
broker_idsr   r   partition_idreplicas_Assignmentr   r   r   D       z@TopicAdminMixin._process_create_topics_input.<locals>.<listcomp>assignmentsc                   r"   )r   valuer   r   
config_keyconfig_value_Configr   r   r   F   r+   )r   r   r!   r,   r   c                 s      | ]}t |tV  qd S N)
isinstancestrr   vr   r   r   	<genexpr>I       z?TopicAdminMixin._process_create_topics_input.<locals>.<genexpr>)r   r   r!   c                 s  r4   r5   )r6   NewTopicr8   r   r   r   r:   M   r;   c                   r"   r#   r   r&   r)   r   r   r   S   r+   c                   r"   r-   r   r/   r2   r   r   r   U   r+   z%No valid topics found in new_topics: )r   CreatableTopicCreatableReplicaAssignmentCreatableTopicConfigr6   r   itemsgetappendallr   r   r!   replica_assignmentstopic_configs
ValueError)
new_topics_Topicr   topicdatar   	new_topicr   )r*   r3   r   _process_create_topics_input6   sN   








	z,TopicAdminMixin._process_create_topics_inputFTc                 C  s  |r|rt d| |}|r| jjdk rtd| jj| |}| jjdk r;tdd |D r;td| jjt|||d}d	d
 }| j	| j
|||}	|r]| dd |jD  |	 }
|
dd |
d D ] }|dd}|ri }|D ]}| |tj}|||< qy||d< qk|
S )aL  Create new topics in the cluster.

        Arguments:
            new_topics: A list of topic names, or a dict mapping each topic
                name to a dict of options (all keys optional)::

                    {topic_name: {num_partitions: int (default -1),
                                  replication_factor: int (default -1),
                                  assignments: {partition_id: [broker_ids]},
                                  configs: {key: value}}}

                List of NewTopic objects is deprecated.
                Note: for brokers < 2.4, num_partitions and replication_factor
                are required and must be provided via dict or [NewTopic].

        Keyword Arguments:
            timeout_ms (numeric, optional): Milliseconds to wait for new topics to be created
                before the broker returns.
            validate_only (bool, optional): If True, don't actually create new topics.
                Not supported by all versions. Default: False
            raise_errors (bool, optional): Whether to raise errors as exceptions. Default True.
            wait_for_metadata (bool, optional): If True, block until each new topic is visible
                in broker metadata with a leader assigned for every partition. Default: False

        Returns:
            dict of CreateTopicsResponse key/vals.
        z:validate_only and wait_for_metadata are mutually exclusive)r   
      zUvalidate_only requires CreateTopicsRequest >= v1, which is not supported by Kafka {}.)rN      c                 s  s$    | ]}|j d kp|jd kV  qdS )r    N)r   r!   r   rI   r   r   r   r:      s   " z0TopicAdminMixin.create_topics.<locals>.<genexpr>zIBroker version {} requires explicit num_partitions and replication_factor)r   
timeout_msvalidate_onlyc                 s       | j D ]	}t|jV  qd S r5   )r   Errorsfor_code
error_code)rrI   r   r   r   response_errors      
z6TopicAdminMixin.create_topics.<locals>.response_errorsc                 S  s   g | ]}|j qS r   r   )r   rK   r   r   r   r          z1TopicAdminMixin.create_topics.<locals>.<listcomp>throttle_time_msNr   r   )rF   _validate_timeoutr   broker_versionr   formatrL   anyr   r   _send_request_to_controllerwait_for_topicsr   to_dictpop_process_configr   TOPIC)r   rG   rQ   rR   raise_errorswait_for_metadatar   requestrX   responseresultrI   r   processed_configsr   r   r   r   r   create_topics\   sH   




zTopicAdminMixin.create_topics'  c           
   
   C  s   |sdS t |}t |d  }dd |D }	 z| j|d}W n ty: } ztd| g }W Y d}~nd}~ww dd |D }i }|D ]}| ||}	|	durX|	||< qF|s]dS t |krlt	
d	||f td
 q)a  Block until each of the given topics is ready to use.

        CreateTopicsResponse only confirms that the broker accepted the create
        request; propagating the new topics into the broker's metadata cache --
        and electing a leader for every partition -- can lag behind, especially
        on KRaft clusters. This method polls :meth:`describe_topics` at a fixed
        interval until every requested topic both:

          - is returned with ``error_code == 0``, and
          - has ``error_code == 0`` and a leader assigned (``leader_id >= 0``)
            for every partition.

        Arguments:
            topic_names ([str]): Topic names to wait for.

        Keyword Arguments:
            timeout_ms (numeric, optional): Maximum milliseconds to wait.
                Default: 10000.

        Raises:
            KafkaTimeoutError: if any topic is still not ready when the
                deadline expires.
        Ng     @@c                 S  s   i | ]}|d qS )znot yet queriedr   )r   r   r   r   r   
<dictcomp>   rZ   z3TopicAdminMixin.wait_for_topics.<locals>.<dictcomp>T)r   z=describe_topics failed while waiting for topic visibility: %sc                 S  s   i | ]}| d |qS r   )rA   r   r   r   r   rn      s    zTopics not ready after %sms: %sg?)listtime	monotonicr   	Exceptionlogdebug_topic_not_ready_reasonrA   rT   KafkaTimeoutErrorsleep)
r   topic_namesrQ   deadlinependingr   excby_namer   reasonr   r   r   ra      s8   

zTopicAdminMixin.wait_for_topicsc                 C  s   | du rdS |  dd}|dkrt|jS |  dpg }|s!dS g }|D ].}| dd}| d}|dkrD|d|t|jf  q%| d	d
dk rS|d|  q%|r[d|S dS )z@Return a string reason if ``topic_info`` isn't ready, else None.Nzmissing from metadata responserV   r   
partitionszno partitions reportedr$   zp%s=%s	leader_idr    zp%s=no leader,)rA   rT   rU   __name__rB   join)
topic_inforV   r~   badpp_erridxr   r   r   ru      s*   

z'TopicAdminMixin._topic_not_ready_reasonc                   sl   |  |}tj t fdd|D |d}dd }| j| j|||}| }|dd |d|d	< |S )
a  Delete topics from the cluster.

        Arguments:
            topics ([str]): A list of topic name strings or uuid.UUID ids.

        Keyword Arguments:
            timeout_ms (numeric, optional): Milliseconds to wait for topics to be deleted
                before the broker returns.
            raise_errors (bool, optional): Whether to raise errors as exceptions. Default True.

        Returns:
            dict of DeleteTopicsResponse key/vals (version-dependent)
        c                   s,   g | ]}t |tjr |d n |dqS ))topic_idr   )r6   uuidUUIDrP   rH   r   r   r      s    $z1TopicAdminMixin.delete_topics.<locals>.<listcomp>)r   rQ   c                 s  rS   r5   )	responsesrT   rU   rV   )rW   ri   r   r   r   rX      rY   z6TopicAdminMixin.delete_topics.<locals>.response_errorsr[   Nr   r   )r\   r   DeleteTopicStater   r   r`   rb   rc   )r   r   rQ   rf   rh   rX   ri   rj   r   r   r   delete_topics   s   

zTopicAdminMixin.delete_topicsr5   )NFTF)rm   )NT)r   
__module____qualname____doc____annotations__r   r   staticmethodrL   rl   ra   ru   r   r   r   r   r   r
      s   
 
	
%

C0
r
   c                   @  s   e Zd ZdZ		dddZdS )r<   a(  DEPRECATED: A class for new topic creation.

    Arguments:
        name (string): name of the topic
        num_partitions (int): number of partitions, or -1 if
            replica_assignment has been specified
        replication_factor (int): replication factor, or -1 if
            replica assignment is specified
        replica_assignments (dict of int: [int]): A mapping containing
            partition id and replicas to assign to it.
        topic_configs (dict of str: str): A mapping of config key
            and value for the topic.
    r    Nc                 C  s*   || _ || _|| _|pi | _|pi | _d S r5   )r   r   r!   rD   rE   )r   r   r   r!   rD   rE   r   r   r   __init__  s
   
zNewTopic.__init__)r    r    NN)r   r   r   r   r   r   r   r   r   r<     s
    r<   )r   
__future__r   loggingrp   typingr   r   kafka.errorserrorsrT   r   kafka.protocol.adminr   r   _configsr   kafka.net.managerr	   	getLoggerr   rs   r
   r<   r   r   r   r   <module>   s     
 n