U
    %FZh7                  	   @  sD  d Z ddlmZ ddlZddlmZmZmZmZm	Z	m
Z
 ddlZddlZddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZ eeZeejjdrddiZ nddiZ ejf dddddgddde Z!edddgddZ"dZ#de$ iZ%G dd dZ&G dd de&Z'G dd dej(Z)G dd dZ*dS )zoInternal HTTP client module.

This module provides utilities for making HTTP calls using the requests library.
    )annotationsN)AnyDict	GeneratorOptionalTupleUnion)retry)credentials)	transport)requests)_utils)
HttpxRetryHttpxRetryTransportallowed_methodsmethod_whitelist      i  i  Fg      ?)connectreadstatusstatus_forcelistraise_on_statusbackoff_factor)max_retriesr   r   x   zx-goog-api-clientc                   @  s   e Zd ZdZddddeefddZedd Zedd	 Z	ed
d Z
dd Zdd Zdd Zdd Zdd Zdd Zdd ZdS )
HttpClientzBase HTTP client used to make HTTP calls.

    HttpClient maintains an HTTP session, and handles request authentication and retries if
    necessary.
    N c                 C  s   |rt j|| _n|r || _n
t | _|r<| jj| |rp| jdtjj	|d | jdtjj	|d || _
|| _dS )a  Creates a new HttpClient instance from the provided arguments.

        If a credential is provided, initializes a new HTTP session authorized with it. If neither
        a credential nor a session is provided, initializes a new unauthorized session.

        Args:
          credential: A Google credential that can be used to authenticate requests (optional).
          session: A custom HTTP session (optional).
          base_url: A URL prefix to be added to all outgoing requests (optional).
          headers: A map of headers to be added to all outgoing requests (optional).
          retries: A urllib retry configuration. Default settings would retry once for low-level
              connection and socket read errors, and up to 4 times for HTTP 500 and 503 errors.
              Pass a False value to disable retries (optional).
          timeout: HTTP timeout in seconds. Defaults to 120 seconds when not specified. Set to
              None to disable timeouts (optional).
        http://)r   https://N)r   r   ZAuthorizedSession_sessionSessionheadersupdatemountadaptersHTTPAdapter	_base_url_timeout)self
credentialsessionbase_urlr"   retriestimeout r/   b/home/aprabhat/apps/x.techxrdev.in/venv/lib/python3.8/site-packages/firebase_admin/_http_client.py__init__?   s    
zHttpClient.__init__c                 C  s   | j S N)r    r)   r/   r/   r0   r+   a   s    zHttpClient.sessionc                 C  s   | j S r2   r'   r3   r/   r/   r0   r,   e   s    zHttpClient.base_urlc                 C  s   | j S r2   r(   r3   r/   r/   r0   r.   i   s    zHttpClient.timeoutc                 C  s   t d S r2   )NotImplementedErrorr)   respr/   r/   r0   
parse_bodym   s    zHttpClient.parse_bodyc                 K  sH   d|kr| j |d< |di t | jj|| j| f|}|  |S )a	  Makes an HTTP call using the Python requests library.

        This is the sole entry point to the requests library. All other helper methods in this
        class call this method to send HTTP requests out. Refer to
        http://docs.python-requests.org/en/master/api/ for more information on supported options
        and features.

        Args:
          method: HTTP method name as a string (e.g. get, post).
          url: URL of the remote endpoint.
          **kwargs: An additional set of keyword arguments to be passed into the requests API
              (e.g. json, params, timeout).

        Returns:
          Response: An HTTP response object.

        Raises:
          RequestException: Any requests exceptions encountered while making the HTTP call.
        r.   r"   )r.   
setdefaultr#   METRICS_HEADERSr    requestr,   raise_for_statusr)   methodurlkwargsr8   r/   r/   r0   r<   p   s    
zHttpClient.requestc                 K  s   | j ||f|}|jS r2   r<   r"   r>   r/   r/   r0   r"      s    zHttpClient.headersc                 K  s   | j ||f|}| ||fS r2   r<   r9   r>   r/   r/   r0   body_and_response   s    zHttpClient.body_and_responsec                 K  s   | j ||f|}| |S r2   rC   r>   r/   r/   r0   body   s    zHttpClient.bodyc                 K  s    | j ||f|}|j| |fS r2   r<   r"   r9   r>   r/   r/   r0   headers_and_body   s    zHttpClient.headers_and_bodyc                 C  s   | j   d | _ d S r2   )r    closer3   r/   r/   r0   rH      s    
zHttpClient.close)__name__
__module____qualname____doc__DEFAULT_RETRY_CONFIGDEFAULT_TIMEOUT_SECONDSr1   propertyr+   r,   r.   r9   r<   r"   rD   rE   rG   rH   r/   r/   r/   r0   r   8   s*       
"


r   c                   @  s    e Zd ZdZdd Zdd ZdS )JsonHttpClientz5An HTTP client that parses response messages as JSON.c                 K  s   t j| f| d S r2   )r   r1   )r)   rA   r/   r/   r0   r1      s    zJsonHttpClient.__init__c                 C  s   |  S r2   jsonr7   r/   r/   r0   r9      s    zJsonHttpClient.parse_bodyN)rI   rJ   rK   rL   r1   r9   r/   r/   r/   r0   rP      s   rP   c                   @  s@   e Zd ZdZddddZdddd	d
dZdddddZdS )GoogleAuthCredentialFlowz Google Auth Credential Auth Flowzcredentials.Credentials)r*   c                 C  s   || _ d| _d| _d S )N   )i  )_credential_max_refresh_attempts_refresh_status_codes)r)   r*   r/   r/   r0   r1      s    z!GoogleAuthCredentialFlow.__init__zhttpx.Requestzgoogle_auth_requests.RequestNone)r<   auth_requestreturnc                 C  s@   t d| jj | j||jt|j|j t d| jj dS )zA helper function that refreshes credentials if needed and mutates the request headers
        to contain access token and any other Google Auth headers.z@Attempting to apply auth headers. Credential validity before: %sz3Auth headers applied. Credential validity after: %sN)	loggerdebugrU   ZvalidZbefore_requestr?   strr@   r"   )r)   r<   rY   r/   r/   r0   apply_auth_headers   s       z+GoogleAuthCredentialFlow.apply_auth_headersz.Generator[httpx.Request, httpx.Response, None])r<   rZ   c                 c  s   |j  }d}t }| |_ | || td|| j |V }|j| j	kr|| jk rtd|j|d | j | j
| |d7 }qtd|j| j qqtd|j qqd S )Nr   z%Dispatching request, attempt %d of %dzeReceived status %d. Attempting explicit credential refresh.                         Attempt %d of %d.r   zpReceived status %d, but max auth refresh attempts (%d) reached.                         Returning last response.z<Status code %d does not require refresh. Returning response.)r"   copygoogle_auth_requestsRequestr^   r[   r\   rV   status_coderW   rU   refresh)r)   r<   Z_original_headersZ_credential_refresh_attemptrY   responser/   r/   r0   	auth_flow   s@    

 

 z"GoogleAuthCredentialFlow.auth_flowN)rI   rJ   rK   rL   r1   r^   re   r/   r/   r/   r0   rS      s   rS   c                	   @  s   e Zd ZdZdddeedfddddd	d
ddddZedd Zedd Z	edd Z
dddddddZdddddddZdddddddZdddddd d!Zdddd"dd#d$Zddd%d&d'Zdd(d)d*ZdS )+HttpxAsyncClientzAsync HTTP client used to make HTTP/2 calls using HTTPX.

    HttpxAsyncClient maintains an async HTTPX client, handles request authentication, and retries
    if necessary.
    Nr   Tz!Optional[credentials.Credentials]r]   z.Optional[Union[httpx.Headers, Dict[str, str]]]r   intboolrX   )r*   r,   r"   retry_configr.   http2rZ   c                 C  s   || _ || _|r|tnt| _|| _t| j|dt| j|dd| _|rltj|| j| jt	|| jd| _
ntj|| j| j| jd| _
dS )a  Creates a new HttpxAsyncClient instance from the provided arguments.

        If a credential is provided, initializes a new async HTTPX client authorized with it.
        Otherwise, initializes a new unauthorized async HTTPX client.

        Args:
            credential: A Google credential that can be used to authenticate requests (optional).
            base_url: A URL prefix to be added to all outgoing requests (optional).
            headers: A map of headers to be added to all outgoing requests (optional).
            retry_config: A HttpxRetry configuration. Default settings would retry up to 4 times for
                HTTP 500 and 503 errors (optional).
            timeout: HTTP timeout in seconds. Defaults to 120 seconds when not specified (optional).
            http2: A boolean indicating if HTTP/2 support should be enabled. Defaults to `True` when
                not specified (optional).
        )r	   rj   )r   r   )rj   r.   r"   authmounts)rj   r.   r"   rl   N)r'   r(   r;   _headersZ_retry_configr   Z_mountshttpxZAsyncClientrS   _async_client)r)   r*   r,   r"   ri   r.   rj   r/   r/   r0   r1      s*    
zHttpxAsyncClient.__init__c                 C  s   | j S r2   r4   r3   r/   r/   r0   r,   )  s    zHttpxAsyncClient.base_urlc                 C  s   | j S r2   r5   r3   r/   r/   r0   r.   -  s    zHttpxAsyncClient.timeoutc                 C  s   | j S r2   )ro   r3   r/   r/   r0   async_client1  s    zHttpxAsyncClient.async_clientr   zhttpx.Response)r?   r@   rA   rZ   c                   s8   d|kr| j |d< | jj|| j| f|I dH }| S )aM  Makes an HTTP call using the HTTPX library.

        This is the sole entry point to the HTTPX library. All other helper methods in this
        class call this method to send HTTP requests out. Refer to
        https://www.python-httpx.org/api/ for more information on supported options
        and features.

        Args:
            method: HTTP method name as a string (e.g. get, post).
            url: URL of the remote endpoint.
            **kwargs: An additional set of keyword arguments to be passed into the HTTPX API
                (e.g. json, params, timeout).

        Returns:
            Response: An HTTPX response object.

        Raises:
            HTTPError: Any HTTPX exceptions encountered while making the HTTP call.
            RequestException: Any requests exceptions encountered while making the HTTP call.
        r.   N)r.   ro   r<   r,   r=   r>   r/   r/   r0   r<   5  s    
zHttpxAsyncClient.requestzhttpx.Headersc                   s   | j ||f|I d H }|jS r2   rB   r>   r/   r/   r0   r"   O  s    zHttpxAsyncClient.headerszTuple[Any, httpx.Response]c                   s$   | j ||f|I d H }| ||fS r2   rC   r>   r/   r/   r0   rD   S  s    z"HttpxAsyncClient.body_and_responsec                   s    | j ||f|I d H }| |S r2   rC   r>   r/   r/   r0   rE   X  s    zHttpxAsyncClient.bodyzTuple[httpx.Headers, Any]c                   s&   | j ||f|I d H }|j| |fS r2   rF   r>   r/   r/   r0   rG   \  s    z!HttpxAsyncClient.headers_and_body)r8   rZ   c                 C  s   |  S r2   rQ   r7   r/   r/   r0   r9   a  s    zHttpxAsyncClient.parse_body)rZ   c                   s   | j  I d H  d S r2   )ro   acloser3   r/   r/   r0   rq   d  s    zHttpxAsyncClient.aclose)rI   rJ   rK   rL   DEFAULT_HTTPX_RETRY_CONFIGrN   r1   rO   r,   r.   rp   r<   r"   rD   rE   rG   r9   rq   r/   r/   r/   r0   rf      s*   3


rf   )+rL   
__future__r   loggingtypingr   r   r   r   r   r   rn   Zrequests.adaptersr   Zrequests.packages.urllib3.utilr	   Zgoogle.authr
   r   Zgoogle.auth.transportr`   Zfirebase_adminr   Zfirebase_admin._retryr   r   	getLoggerrI   r[   hasattrRetryDEFAULTZ_ANY_METHODrM   rr   rN   Zget_metrics_headerr;   r   rP   ZAuthrS   rf   r/   r/   r/   r0   <module>   sL    

       g	H