o
    `juU                     @  s   d Z ddlmZ ddlm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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eeZG dd deeZG dd deeZG dd dZG dd deeZG dd deeZdS )zwConfiguration management mixin for KafkaAdminClient.

Also defines ConfigResource and ConfigResourceType data classes.
    )annotations)defaultdict)IntEnumN)TYPE_CHECKING)AlterConfigsRequestDescribeConfigsRequestIncrementalAlterConfigsRequestListConfigResourcesRequest)
EnumHelper)KafkaConnectionManagerc                   @  s2  e Zd ZU dZded< ded< dd Zedd	 Zed
d Zedd Z	edd Z
ed<ddZedd Zedd Zedd Zed=ddZd>ddZd?ddZed d! Zd@d#d$Zd@d%d&Zd'd( Zd)d* Zd+d, ZedAd-d.Zed/d0 ZdAd1d2ZdBd4d5ZdBd6d7ZdBd8d9ZdBd:d;Zd"S )CConfigAdminMixinzFMixin providing configuration management methods for KafkaAdminClient.r   _managerdictconfigc                 C  s,   z
| j jt W dS  tjy   Y dS w )NTF)r   broker_version_dataapi_versionr   ErrorsIncompatibleBrokerVersionself r   R/home/djax/ivt_ai_plugin/venv/lib/python3.10/site-packages/kafka/admin/_configs.py(_check_incremental_alter_configs_support!   s   z9ConfigAdminMixin._check_incremental_alter_configs_supportc                 C  s~   | sg S t | tstdg }|  D ])\}}t |tr!|\}}ntj|}}t|}|tjj	kr4d }|
|||f q|S )Nzcalter_configs requires configs as a dict of {key: (op, value)} or {key: value} (interpreted as SET))
isinstancer   	TypeErroritemstupleAlterConfigOpSET	value_forDELETEvalueappendconfigsentriesnameop_valueopr!   op_coder   r   r   _incremental_configs_entries)   s   



z-ConfigAdminMixin._incremental_configs_entriesc                 C  s   t | trt|  S | S N)r   r   listkeysr$   r   r   r   _describe_configs_entries<   s   z*ConfigAdminMixin._describe_configs_entriesc                 C  s   | sg S t | tstdt|  g }|  D ].\}}t |tr&|\}}ntj|}}t|}|tjj	kr?t
d| d|||f q|S )Nz0configs should be a dict of {key: value}, found z?Non-incremental AlterConfigsRequest does not support operation z (SET only))r   r   r   typer   r   r   r   r   r!   
ValueErrorr"   r#   r   r   r   _alter_configs_entries@   s   



z'ConfigAdminMixin._alter_configs_entriesc              	   C  sp   t t}g }| D ]+}|jtjtjfv r.zt|j}W n ty%   tdw || 	| q|	| q||fS )NzHBroker resource names must be an integer or a string represented integer)
r   r,   resource_typeConfigResourceTypeBROKERBROKER_LOGGERintr&   r1   r"   )config_resourcesbroker_resourcesother_resourcesconfig_resource	broker_idr   r   r   _group_config_resourcesR   s   z(ConfigAdminMixin._group_config_resourcesFc                   s(   |rdnd}t  fdd|D ||dS )N   r   c                   "   g | ]}|j |j |jfqS r   )r3   r&   r/   r$   .0crclsr   r   
<listcomp>e       z>ConfigAdminMixin._describe_configs_request.<locals>.<listcomp>)	resourcesinclude_synonymsmin_version)r   )rD   r8   rH   rI   r   rC   r   _describe_configs_requesta   s   
z*ConfigAdminMixin._describe_configs_requestc                 C  sJ   d| v rt | d S | d r|tju rt jS | ddr t jS t |S )Nconfig_source	read_only
is_defaultF)ConfigSourceType
build_fromr4   r5   STATIC_BROKER_CONFIGgetDEFAULT_CONFIGdynamic_for_resource_type)r   r3   r   r   r   _get_config_sourcej   s   
z#ConfigAdminMixin._get_config_sourcec                 C  s4   |t jkr|d rdS | ||}||rdS dS )NrL   TF)ConfigFilterTypeDYNAMICrT   should_skip)rD   r   config_filterr3   rK   r   r   r   _should_skip_configu   s   
z$ConfigAdminMixin._should_skip_configc                 C  sf   | d}| ||}|j|d< d|v r$|d D ]}t|d j|d< qd|v r1t|d j|d< |S )Nr&   rK   synonymssourceconfig_type)poprT   r&   rN   
ConfigType)rD   r   r3   r&   rK   synonymr   r   r   _process_config~   s   

z ConfigAdminMixin._process_configmodifiedc                 C  s   t |}tt}|D ]4}|jD ].}t|j}i }|jD ]}| }	| 	|	|}
| 
|	||s3|	||
< q|||j  |j< qqt|S r+   )rU   rO   r   r   resultsr4   r3   r$   to_dictr`   rY   r&   lowerresource_name)rD   	responsesrX   retresponseresultr3   resource_configsconfig_structr   r&   r   r   r   #_describe_configs_process_responses   s   



	z4ConfigAdminMixin._describe_configs_process_responsesc                   s   |  |\}}g }| D ]\}}	| |	|}
|| jj|
|dI d H  q|r;| ||}
|| j|
I d H  | || |rL fdd|D S  S )Nnode_idc                   s"   g | ]} |j j  |j qS r   )r3   r&   rd   rA   resourcerg   r   r   rE      rF   z<ConfigAdminMixin._async_describe_configs.<locals>.<listcomp>)r=   r   rJ   r"   r   sendrl   )r   r8   rH   rX   flatr9   r:   rf   r<   rG   requestr   rq   r   _async_describe_configs   s   
z(ConfigAdminMixin._async_describe_configsc                 C  s   | j | j|||S )a  Fetch configuration parameters for one or more Kafka resources.

        Arguments:
            config_resources: An list of ConfigResource objects.
                Any keys in ConfigResource.configs dict will be used to filter the
                result. Setting the configs dict to None will get all values. An
                empty dict will get zero values (as per Kafka protocol).

        Keyword Arguments:
            include_synonyms (bool, optional): If True, return synonyms in response. Not
                supported by all versions. Default: False.
            config_filter (ConfigFilterType or str): Modified returns only keys that have
                non-default values; Dynamic returns all keys that can be modified with
                alter_configs; All returns all available keys. Default: Modified.

        Returns:
            dict of {resource_type (str): {resource_name (str): {config_key: {config data}}}}
        )r   runru   )r   r8   rH   rX   r   r   r   describe_configs   s   z!ConfigAdminMixin.describe_configsc                 C  s`   t | j}|t jur|d| tt}| jD ]}t|j	}||j
  |j qt|S )Nz5ListConfigResourcesRequest failed with response '{}'.)r   for_code
error_codeNoErrorformatr   r,   r8   r4   r3   r&   rd   r"   re   r   )rh   
error_typerg   rp   r3   r   r   r   '_list_config_resources_process_response   s   


z8ConfigAdminMixin._list_config_resources_process_responseNc                   sP   g }|pg D ]}t |}||j qt|d}| j|I d H }| |S )N)resource_types)r4   rO   r"   r!   r	   r   rr   r}   )r   r~   
wire_typesrtrt   rh   r   r   r   _async_list_config_resources   s   


z-ConfigAdminMixin._async_list_config_resourcesc                 C  s   | j | j|S )a  List config resources known to the cluster.

        Useful for discovering resource types that have no separate enumeration
        API (e.g. ``CLIENT_METRICS``, ``GROUP``). For ``TOPIC`` and ``BROKER``
        the data is also available via ``Metadata`` / cluster descriptions.

        Keyword Arguments:
            resource_types (list, optional): Filter by resource type. Each entry
                may be a :class:`ConfigResourceType` or its name (e.g. ``'TOPIC'``).
                If None or empty, the broker returns all supported types.
                Requires broker >= 4.1 for anything other than ``CLIENT_METRICS``.

        Returns:
            dict of {resource_type (str): [resource_name (str)]}
        )r   rv   r   )r   r~   r   r   r   list_config_resources   s   z&ConfigAdminMixin.list_config_resourcesc           
        s   dd |D }| j |dddI d H }g }t||D ]$\}}i }|D ]}||jvr8|| d }	|	d u r4q"|	||< q"|| q|S )Nc                 S     g | ]	}t |j|jqS r   ConfigResourcer3   r&   ro   r   r   r   rE          zBConfigAdminMixin._get_missing_modified_configs.<locals>.<listcomp>ra   TrX   rs   r!   )ru   zipr$   r"   )
r   r8   resource_lookupsdynamic_configsmissing_resource_configsrp   describemissing
config_keyconfig_valuer   r   r   _get_missing_modified_configs   s   
z.ConfigAdminMixin._get_missing_modified_configsc                   sR   |  |I d H }t||D ]\}}t|ts tdt| |j| qd S )Nz&missing configs: expected dict, found )r   r   r   r   r   r0   r$   update)r   r8   r   rp   r   r   r   r   _add_missing_dynamic_configs   s   
z-ConfigAdminMixin._add_missing_dynamic_configsc                   sf   dd |D }| j |dddI d H }t||D ]\}}t|jp!g t| }|r0td| qd S )Nc                 S  r   r   r   ro   r   r   r   rE      r   z>ConfigAdminMixin._validate_dynamic_configs.<locals>.<listcomp>dynamicTr   zUnrecognized configs: )ru   r   setr$   r1   )r   r8   r   r   rp   r   unknownr   r   r   _validate_dynamic_configs   s   z*ConfigAdminMixin._validate_dynamic_configsc                   s8   |rt  fdd|D |dS t fdd|D |dS )Nc                   r?   r   )r3   r&   r*   r$   r@   rC   r   r   rE   
  rF   z;ConfigAdminMixin._alter_configs_request.<locals>.<listcomp>)rG   validate_onlyc                   r?   r   )r3   r&   r2   r$   r@   rC   r   r   rE     rF   )r   r   )rD   r8   r   incrementalr   rC   r   _alter_configs_request  s   

z'ConfigAdminMixin._alter_configs_requestc                 C  s^   t t}| D ]$}|jdkrd}ntt|j|j}t|jj	
 }||| |j< qt|S )Nr   OK)r   r   ry   strr   rx   error_messager4   r3   r&   rd   re   )rf   rg   rh   ri   result_typer   r   r    _alter_configs_process_responses  s   
z1ConfigAdminMixin._alter_configs_process_responsesc                   s   |  |\}}g }| D ]\}}| |||}	| jj|	|dI d H }
||
j q|rC| |||}	| j|	I d H }
||
j | |S )Nrm   )r=   r   r   r   rr   extendrf   r   )r   r8   r   r   r9   r:   rf   r<   rG   rt   rh   r   r   r   _send_alter_configs_requests  s   
z-ConfigAdminMixin._send_alter_configs_requestsTc                   sN   |r|  |I d H  |d u r|  }|s| |I d H  | |||I d H S r+   )r   r   r   r   r   r8   r   raise_on_unknownr   r   r   r   _async_alter_configs,  s   z%ConfigAdminMixin._async_alter_configsc                 C     | j | j||||S )a6  Alter configuration parameters of one or more Kafka resources.

        Arguments:
            config_resources: A list of ConfigResource objects. Each resource's
                ``configs`` must be a dict mapping config key to either
                ``(op, value)`` (where ``op`` is an :class:`AlterConfigOp`,
                its name, or its int value) or a bare value (interpreted as SET).
                For DELETE operations the value is ignored and sent as null.
                APPEND/SUBTRACT require broker >= 2.3. On older brokers only
                SET is supported; non-SET ops raise ValueError. On older brokers
                the client also fills in all other modified dynamic keys before
                submitting, since AlterConfigsRequest resets any omitted key to
                its default (be aware of the inherent race in that approach).
            validate_only (bool, optional): If True, changes are sent to broker for
                validation only. Changes will not be applied. Default: False
            raise_on_unknown (bool, optional): If True, raises ValueError if any
                config key is not recognized as a dynamic config for the resource.
            incremental (bool, optional): Set to True/False to force use of
                IncrementalAlterConfigs (True) or AlterConfigs (False).
                By Default, the admin client will use IncrementalAlterConfigs
                if supported by the broker, otherwise AlterConfigs.

        Returns:
            dict of {resource_type (str): {resource_name (str): Error/Result}}
        )r   rv   r   r   r   r   r   alter_configs5  s   zConfigAdminMixin.alter_configsc           
        s   |r|  |I d H  |d u r|  }|s2dd |D }| |I d H }t||D ]\}}||_q)n*dd |D }	| |	I d H }t|	|D ]\}}||_qF|D ]}dd |jD |_qP| |||I d H S )Nc                 S  s   g | ]}|j r|qS r   r.   ro   r   r   r   rE   Z      z9ConfigAdminMixin._async_reset_configs.<locals>.<listcomp>c                 S  s   g | ]}|j s|qS r   r.   ro   r   r   r   rE   `  r   c                 S  s   i | ]}|t jd fqS r+   )r   r    )rA   keyr   r   r   
<dictcomp>f  s    z9ConfigAdminMixin._async_reset_configs.<locals>.<dictcomp>)r   r   r   r   r$   r   )
r   r8   r   r   r   partial_resetsr   rp   r   full_resetsr   r   r   _async_reset_configsQ  s(   
z%ConfigAdminMixin._async_reset_configsc                 C  r   )a,  Reset configuration parameters of one or more Kafka resources to defaults.

        On 2.3+ brokers, the client will submit an IncrementalAlterConfigsRequest
        with op DELETE for each resource/key. On older brokers, the client will
        use submit an AlterConfigsRequest and attempt to include all modified
        dynamic config values for each resource except the keys marked for reset.
        (AlterConfigsRequest will reset any missing config key to its default).

        Arguments:
            config_resources: A list of ConfigResource objects. Each resource's
                ``configs`` should be a list or dict of config keys to reset.
                (if dict, the values are ignored).

        Returns:
            dict of {resource_type (str): {resource_name (str): Error/Result}}
        )r   rv   r   r   r   r   r   reset_configsj  s   zConfigAdminMixin.reset_configs)F)ra   )Fra   F)Fra   r+   )FF)FTN) __name__
__module____qualname____doc____annotations__r   staticmethodr*   r/   r2   r=   classmethodrJ   rT   rY   r`   rl   ru   rw   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r      sR   
 












	



	
r   c                   @  s   e Zd ZdZdZdZdZdS )r   r   r>         N)r   r   r   r   r    APPENDSUBTRACTr   r   r   r   r   ~  s
    r   c                   @  s(   e Zd ZdZdZdZdZdZdd ZdS )	rU   r   r>   r   r      c                 C  s>   | t ju r
|  S | t ju r| S | t ju r|tjuS dS )NF)rU   MODIFIEDis_modifiedDEFAULTSTATICrN   rP   )r   rK   r   r   r   rW     s   




zConfigFilterType.should_skipN)	r   r   r   ALLrV   r   r   r   rW   r   r   r   r   rU     s    rU   c                   @  s$   e Zd ZdZdZdZdZdZdZdS )r4   r   r   r             N)	r   r   r   UNKNOWNTOPICr5   r6   CLIENT_METRICSGROUPr   r   r   r   r4     s    r4   c                   @  s*   e Zd ZdZd	ddZdd Zdd ZdS )
r   a  A class for specifying config resources.

    Arguments:
        resource_type (ConfigResourceType): the type of kafka resource
        name (string): The name of the kafka resource
        configs ([key] or {key : value}): config keys (values required to alter)
    Nc                 C  s0   t |tstt|  }|| _|| _|| _d S r+   )r   r4   r   upperr3   r&   r$   )r   r3   r&   r$   r   r   r   __init__  s
   

zConfigResource.__init__c                 C  s   d| j  d| j S )NzConfigResource =)r&   r3   r   r   r   r   __str__  s   zConfigResource.__str__c                 C  s   d| j  d| j d| j dS )NzConfigResource(z, ))r3   r&   r$   r   r   r   r   __repr__  s   zConfigResource.__repr__r+   )r   r   r   r   r   r   r   r   r   r   r   r     s
    
r   c                   @  s4   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdS )r^   r   r>   r   r   r            r   	   N)r   r   r   r   BOOLEANSTRINGINTSHORTLONGDOUBLELISTCLASSPASSWORDr   r   r   r   r^     s    r^   c                   @  sD   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
d Zedd ZdS )rN   r   r>   r   r   r   r   r   r   r   c                 C  s
   | j dvS )N)r   r   r   )r!   r   r   r   r   r     s   
zConfigSourceType.is_modifiedc                 C  sn   |t ju rtjS |t ju rtjS |t ju rtjS |t ju r tjS |t j	u r(tj
S |t ju r0tjS td| )NzUnrecognized resource type )r4   r   rN   r   DYNAMIC_TOPIC_CONFIGr5   DYNAMIC_BROKER_CONFIGr6   DYNAMIC_BROKER_LOGGER_CONFIGr   DYNAMIC_CLIENT_METRICS_CONFIGr   DYNAMIC_GROUP_CONFIGRuntimeError)rD   r3   r   r   r   rS     s   





z*ConfigSourceType.dynamic_for_resource_typeN)r   r   r   r   r   r   DYNAMIC_DEFAULT_BROKER_CONFIGrP   rR   r   r   r   r   r   rS   r   r   r   r   rN     s    rN   ) r   
__future__r   collectionsr   enumr   loggingtypingr   kafka.errorserrorsr   kafka.protocol.adminr   r   r   r	   
kafka.utilr
   kafka.net.managerr   	getLoggerr   logr   r   rU   r4   r   r^   rN   r   r   r   r   <module>   s*    
  d	