o
    eZh[                     @   s  U d dl Z d dlZd dlZd dlZd dlZd dlmZ d dlmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZ ddlmZmZ ddlmZmZmZmZmZ ddlmZmZm Z m!Z!m"Z"m#Z# ddl$m%Z%m&Z&m'Z'm(Z(m)Z) dd	l*m+Z+m,Z, dd
l-m.Z. ddl/m0Z0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6m7Z7 e)e(e%e'dZ8ee9ee& f e:d< h dZ;de6e4fZ<e=dZ>G dd deZ?G dd dZ@dee" deAdeAdeAdee ddfddZBdee" ddfdd ZCdS )!    N)python_version)AnyCallable
CollectionDictListMapping
NamedTupleOptionalTupleTypeUnioncast   )Lockwarn_stacklevel)ConnectionErrorConnectionTimeoutSniffingErrorTransportErrorTransportWarning)DEFAULTApiResponseMetaDefaultTypeHttpHeaders
NodeConfigSniffOptions)AiohttpHttpNodeBaseNodeHttpxAsyncHttpNodeRequestsHttpNodeUrllib3HttpNode)NodePoolNodeSelector)OpenTelemetrySpan)DEFAULT_SERIALIZERS
SerializerSerializerCollection)__version__)client_meta_versionresolve_default)urllib3requestsZaiohttpZ
httpxasyncNODE_CLASS_NAMES>   Ni  i  i  i  i  i  etzelastic_transport.transportc                   @   s   e Zd ZU eed< eed< dS )TransportApiResponsemetabodyN)__name__
__module____qualname__r   __annotations__r    r6   r6   S/var/www/html/lang_env/lib/python3.10/site-packages/elastic_transport/_transport.pyr/   U   s   
 r/   c                +   @   s  e Zd ZdZeedddddddddddddd	ddefd
ee de	e
ee f dee dedee	e
ee f  dee dee deee
ef  de
dedee dededededee dedeed dge	ee ee f f  dedee
e
f f(dd Zdeeeeeeed!d"e
d#e
d$ee d%e	ee
ef ef de	eef de	ee ef de	eef d&e	ee ef d'e	eee
e
f d(f ef d)e	eef d*efd+d,Zd4d-ed*dfd.d/Zd5d0d1Zd-ed*efd2d3Z dS )6	Transportz
    Encapsulation of transport-related to logic. Handles instantiation of the
    individual nodes as well as creating a node pool to hold them.

    Main interface is the :meth:`elastic_transport.Transport.perform_request` method.
    TNzapplication/json   )i  i  i  i  Fg      ?g      $@node_configs
node_classnode_pool_classrandomize_nodes_in_poolnode_selector_classdead_node_backoff_factormax_dead_node_backoffserializersdefault_mimetypemax_retriesretry_on_statusretry_on_timeoutsniff_on_startsniff_before_requestssniff_on_node_failuresniff_timeoutmin_delay_between_sniffingsniff_callbackr   meta_headerclient_meta_servicec                 C   s  t |tr!|tvrdtt }td| d| dt| }t| j	}t|j	}||krDtd|r7dnd d|r>d	nd
 dt
|||||d |dtt fdttff| _tttttf  t|dd}|ru|  j|f7  _t |ts~td|| _t }|r|| t||	d| _|
| _|| _|| _i }|dur||d< |dur||d< |dur||d< ||f||d|| _|| _|| _ || _!|| _"|| _#t$ | _%|| _&d| _'|r| (d dS dS )a
  
        :arg node_configs: List of 'NodeConfig' instances to create initial set of nodes.
        :arg node_class: subclass of :class:`~elastic_transport.BaseNode` to use
            or the name of the Connection (ie 'urllib3', 'requests')
        :arg node_pool_class: subclass of :class:`~elastic_transport.NodePool` to use
        :arg randomize_nodes_in_pool: Set to false to not randomize nodes within the pool.
            Defaults to true.
        :arg node_selector_class: Class to be used to select nodes within
            the :class:`~elastic_transport.NodePool`.
        :arg dead_node_backoff_factor: Exponential backoff factor to calculate the amount
            of time to timeout a node after an unsuccessful API call.
        :arg max_dead_node_backoff: Maximum amount of time to timeout a node after an
            unsuccessful API call.
        :arg serializers: optional dict of serializer instances that will be
            used for deserializing data coming from the server. (key is the mimetype)
        :arg max_retries: Maximum number of retries for an API call.
            Set to 0 to disable retries. Defaults to ``0``.
        :arg retry_on_status: set of HTTP status codes on which we should retry
            on a different node. defaults to ``(429, 502, 503, 504)``
        :arg retry_on_timeout: should timeout trigger a retry on different
            node? (default ``False``)
        :arg sniff_on_start: If ``True`` will sniff for additional nodes as soon
            as possible, guaranteed before the first request.
        :arg sniff_on_node_failure: If ``True`` will sniff for additional nodees
            after a node is marked as dead in the pool.
        :arg sniff_before_requests: If ``True`` will occasionally sniff for additional
            nodes as requests are sent.
        :arg sniff_timeout: Timeout value in seconds to use for sniffing requests.
            Defaults to 1 second.
        :arg min_delay_between_sniffing: Number of seconds to wait between calls to
            :meth:`elastic_transport.Transport.sniff` to avoid sniffing too frequently.
            Defaults to 10 seconds.
        :arg sniff_callback: Function that is passed a :class:`elastic_transport.Transport` and
            :class:`elastic_transport.SniffOptions` and should do node discovery and
            return a list of :class:`elastic_transport.NodeConfig` instances.
        :arg meta_header: If set to False the ``X-Elastic-Client-Meta`` HTTP header won't be sent.
            Defaults to True.
        :arg client_meta_service: Key-value pair for the service field of the client metadata header.
            Defaults to the service key-value for Elastic Transport.
        z', 'z Unknown option for node_class: 'z'. Available options are: ''zSpecified 'node_class' iszis notz async, should be asyncsyncz instead)r:   rF   rG   rH   rK   pytZ_CLIENT_META_HTTP_CLIENTNz"'meta_header' must be of type bool)rB   r>   r?   r@   )r;   Zrandomize_nodesg        T))
isinstancestrr-   joinsortedkeys
ValueErrorinspectiscoroutinefunctionperform_requestvalidate_sniffing_optionsr)   r   r(   _transport_client_metar   r
   r   getattrbool	TypeErrorrL   r%   copyupdater'   rA   rC   rD   rE   	node_poolZ_sniff_on_start_sniff_before_requests_sniff_on_node_failure_sniff_timeout_sniff_callbackr   _sniffing_lock_min_delay_between_sniffing_last_sniffed_atsniff)selfr:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   optionsZis_transport_asyncZis_node_asyncZhttp_client_metaZ_serializersZnode_pool_kwargsr6   r6   r7   __init__b   s   
D




zTransport.__init__)r1   headersrC   rD   rE   request_timeoutclient_meta	otel_spanmethodtargetr1   rp   rq   rr   .rs   returnc                C   s6  |t u rt }nt|}t|| j}t|| j}t|| j}t|
td}
| jr:ddd | j	t|	d D |d< |durVd|vrFt
d| jj||d d	}|
| nd}g }t|d
 D ]7}| jrk| d d}d}d}| j }t }zI|
|j|j|j| |j|||||d}td||j||jjt | f  |dkr| j|j|jj}nd}|jj|v rd}t |j|}W n t!yD } zttd||j|dt | f  t"|t#r|}d}n	t"|t$rd}d}|r| j%| | j&rz| d W n
 t!y   Y nw |r||kr,|dur&|W  Y d}~  S t'||_( tj)d|||d |*| W Y d}~q`d}~ww d|jj  krSdk s[n |jjt+v rb| j,| n| j%| | j&r~z| d W n
 t!y}   Y nw |r||krt |j|  S t)d|jj|| q`dS )a@  
        Perform the actual request. Retrieve a node from the node
        pool, pass all the information to it's perform_request method and
        return the data.

        If an exception was raised, mark the node as failed and retry (up
        to ``max_retries`` times).

        If the operation was successful and the node used was previously
        marked as dead, mark it as live, resetting it's failure count.

        :arg method: HTTP method to use
        :arg target: HTTP request target
        :arg body: body of the request, will be serialized using serializer and
            passed to the node
        :arg headers: Additional headers to send with the request.
        :arg max_retries: Maximum number of retries before giving up on a request.
            Set to ``0`` to disable retries.
        :arg retry_on_status: Collection of HTTP status codes to retry.
        :arg retry_on_timeout: Set to true to retry after timeout errors.
        :arg request_timeout: Amount of time to wait for a response to fail with a timeout error.
        :arg client_meta: Extra client metadata key-value pairs to send in the client meta header.
        :arg otel_span: OpenTelemetry span used to add metadata to the span.

        :returns: Tuple of the :class:`elastic_transport.ApiResponseMeta` with the deserialized response.
        N,c                 s   s"    | ]\}}| d | V  qdS )=Nr6   .0kvr6   r6   r7   	<genexpr>2  s
    
z,Transport.perform_request.<locals>.<genexpr>r6   zx-elastic-client-metazcontent-typez<Must provide a 'Content-Type' header to requests with bodies)mimetyper   F)r1   rp   rq   z"%s %s%s [status:%s duration:%.3fs]HEADTzN/Az1Retrying request after failure (attempt %d of %d)exc_info   i+  zBRetrying request after non-successful status %d (attempt %d of %d))-r   r   r*   rC   rE   rD   r$   rL   rV   r^   rY   rA   dumpsZset_db_statementrangere   rl   rd   gettimeZset_node_metadatahostportbase_urlr\   _loggerinfor0   statusloadsr1   r~   r/   r   rT   r   r   Z	mark_deadrf   tupleerrorswarningappendNOT_DEAD_NODE_HTTP_STATUSESZ	mark_live)rm   rt   ru   r1   rp   rC   rD   rE   rq   rr   rs   Zrequest_headersrequest_bodyr   attemptretryZnode_failureZlast_responsenode
start_timeresper6   r6   r7   r\      s   (








8zTransport.perform_requestis_initial_sniffc              
   C   s  | j }| |}zwzS|r[td t | _ t|| jd}| jd us$J | | |}|s2|r2tdt	| j
}|D ]}| j
| q9t	|}|t	| j
|  }	||	 }
td||	|
 W n tys } ztjd|d || _  d }~ww W |r~| j  d S d S |r| j  w w )Nz%Started sniffing for additional nodes)r   rI   z<No viable nodes were discovered on the initial sniff attemptzFDiscovered %d nodes during sniffing (%d new nodes, %d already in pool)z$Encountered an error during sniffingr   )rk   _should_sniffr   r   r   r   rg   rh   r   lenrd   adddebug	Exceptionr   ri   release)rm   r   Zpreviously_sniffed_atZshould_sniffrn   r:   Zprev_node_pool_sizenode_configZsniffed_nodesZ	new_nodesZexisting_nodesr   r6   r6   r7   rl     sP   



	zTransport.sniffc                 C   s   | j  D ]}|  qdS )zE
        Explicitly closes all nodes in the transport's pool
        N)rd   allclose)rm   r   r6   r6   r7   r     s   
zTransport.closec                 C   s(   |st   | j | jk rdS | jdS )zDecide if we should sniff or not. If we return ``True`` from this
        method the caller has a responsibility to unlock the ``_sniffing_lock``
        F)r   rk   rj   ri   acquire)rm   r   r6   r6   r7   r     s   zTransport._should_sniff)F)rv   N)!r2   r3   r4   __doc__r!   r"   DEFAULT_CLIENT_META_SERVICEr   r   r   rU   r   r   r`   r
   r#   floatr   r&   intr   r   r   ro   r   r   r   r$   r/   r\   rl   r   r   r6   r6   r6   r7   r8   Z   s    
	


 $

	


 G
-r8   r:   rG   rF   rH   rK   rv   c                 C   sP   |p|p|}|r|st d|s|rt d|r$t| dkr&t|  dS dS dS )z3Validates the Transport configurations for sniffingz8Enabling sniffing requires specifying a 'sniff_callback'zzUsing 'sniff_callback' requires enabling sniffing via 'sniff_on_start', 'sniff_before_requests' or 'sniff_on_node_failure'r   N)rY   r   #warn_if_varying_node_config_options)r:   rG   rF   rH   rK   Zsniffing_enabledr6   r6   r7   r]     s   
r]   c                    s^   h d d}| D ]$} fddt | D }|du r|}q||kr,tjdtt d qdS )zMFunction which detects situations when sniffing may produce incorrect configs>   r   _extrasZconnections_per_noder   Nc                    s   i | ]\}}| vr||qS r6   r6   ry   Zexempt_attrsr6   r7   
<dictcomp>"  s
    z7warn_if_varying_node_config_options.<locals>.<dictcomp>zDetected NodeConfig instances with different options. It's recommended to keep all options except for 'host' and 'port' the same for sniffing to work reliably.)category
stacklevel)dataclassesasdictitemswarningswarnr   r   )r:   Zmatch_attr_dictr   	attr_dictr6   r   r7   r     s    
r   )Dr   rZ   loggingr   r   platformr   typingr   r   r   r   r   r   r	   r
   r   r   r   r   _compatr   r   _exceptionsr   r   r   r   r   Z_modelsr   r   r   r   r   r   _noder   r   r   r    r!   Z
_node_poolr"   r#   Z_otelr$   Z_serializerr%   r&   r'   _versionr(   Zclient_utilsr)   r*   r-   rU   r5   r   r   	getLoggerr   r/   r8   r`   r]   r   r6   r6   r6   r7   <module>   sV   
8 

   .
