o
    +i]                  	   @   s  d dl Z d dlmZ d dlZd dlZd dlmZmZmZm	Z	 d dl
mZ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ZerOd dlZd d	lmZ nzd dlZd d	lmZ W n eefyh   dZY nw z
d d
lmZ dZW n ey~   dZY nw edd ZG dd dZ dS )    N)asynccontextmanager)MappingOptionalTYPE_CHECKINGUnion)_exponential_backoff
exceptions)	transport)Credentials)mtls)TimeoutError)ClientTimeout)RequestTFc                   sF   t  | fdd  fdd}z	|V  W    dS    w )a  
    timeout_guard is an asynchronous context manager to apply a timeout to an asynchronous block of code.

    Args:
        timeout (float): The time in seconds before the context manager times out.

    Raises:
        google.auth.exceptions.TimeoutError: If the code within the context exceeds the provided timeout.

    Usage:
        async with timeout_guard(10) as with_timeout:
            await with_timeout(async_function())
    c                     s0   t    } |  }|dkrtd d|S )Nr   z3Context manager exceeded the configured timeout of s.)time	monotonicr   )elapsed	remaining)starttotal_timeout Z/home/livre-enfant/venv/lib/python3.10/site-packages/google/auth/aio/transport/sessions.py_remaining_timeB   s   
z&timeout_guard.<locals>._remaining_timec              
      sX   z  }t | |I d H }|W S  t jtfy+ } ztd|  d d|d }~ww )NzThe operation z$ exceeded the configured timeout of r   )asynciowait_forr   )coror   responsee)r   r   r   r   with_timeoutK   s   z#timeout_guard.<locals>.with_timeoutN)r   r   )timeoutr   r   )r   r   r   r   timeout_guard0   s   	
r    c                   @   s  e Zd ZdZ	d!dedeej fddZd!ddZ	ddej
ej
ejfd	ed
edee deeeef  dedeeef dee dejfddZeeddej
ej
ejfd
edee deeeef  dedeeef dee dejfddZeeddej
ej
ejfd
edee deeeef  dedeeef dee dejfddZeeddej
ej
ejfd
edee deeeef  dedeeef dee dejfddZeeddej
ej
ejfd
edee deeeef  dedeeef dee dejfddZeeddej
ej
ejfd
edee deeeef  dedeeef dee dejfddZedd Zd"dd ZdS )#AsyncAuthorizedSessiona  This is an asynchronous implementation of :class:`google.auth.requests.AuthorizedSession` class.
    We utilize an instance of a class that implements :class:`google.auth.aio.transport.Request` configured
    by the caller or otherwise default to `google.auth.aio.transport.aiohttp.Request` if the external aiohttp
    package is installed.

    A Requests Session class with credentials.

    This class is used to perform asynchronous requests to API endpoints that require
    authorization::

        import aiohttp
        from google.auth.aio.transport import sessions

        async with sessions.AsyncAuthorizedSession(credentials) as authed_session:
            response = await authed_session.request(
                'GET', 'https://www.googleapis.com/storage/v1/b')

    The underlying :meth:`request` implementation handles adding the
    credentials' headers to the request and refreshing credentials as needed.

    Args:
        credentials (google.auth.aio.credentials.Credentials):
            The credentials to add to the request.
        auth_request (Optional[google.auth.aio.transport.Request]):
            An instance of a class that implements
            :class:`~google.auth.aio.transport.Request` used to make requests
            and refresh credentials. If not passed,
            an instance of :class:`~google.auth.aio.transport.aiohttp.Request`
            is created.

    Raises:
        - google.auth.exceptions.TransportError: If `auth_request` is `None`
            and the external package `aiohttp` is not installed.
        - google.auth.exceptions.InvalidType: If the provided credentials are
            not of type `google.auth.aio.credentials.Credentials`.
    Ncredentialsauth_requestc                 C   sf   t |tstdt| d|| _|}|strt }d| _d | _	d | _
|d u r.td|| _d S )Nz#The configured credentials of type zJ are invalid and must be of type `google.auth.aio.credentials.Credentials`Fzv`auth_request` must either be configured or the external package `aiohttp` must be installed to use the default value.)
isinstancer
   r   InvalidTypetype_credentialsAIOHTTP_INSTALLEDAiohttpRequest_is_mtls_mtls_init_task_cached_certTransportError_auth_request)selfr"   r#   r.   r   r   r   __init__   s    

zAsyncAuthorizedSession.__init__c                    s4   j du r fdd}t| _ j I dH S )a  Configure the client certificate and key for SSL connection.

        The function does nothing unless `GOOGLE_API_USE_CLIENT_CERTIFICATE` is
        explicitly set to `true`. In this case if client certificate and key are
        successfully obtained (from the given client_cert_callback or from application
        default SSL credentials), the underlying transport will be reconfigured
        to use mTLS.
        Note: This function does nothing if the `aiohttp` library is not
        installed.
        Important: Calling this method will close any ongoing API requests associated
        with the current session. To ensure a smooth transition, it is recommended
        to call this during session initialization.

        Args:
            client_cert_callback (Optional[Callable[[], (bytes, bytes)]]):
                The optional callback returns the client certificate and private
                key bytes both in PEM format.
                If the callback is None, application default SSL credentials
                will be used.

        Raises:
            google.auth.exceptions.MutualTLSChannelError: If mutual TLS channel
                creation failed for any reason.
        Nc            	   
      s   t tjjjjI d H } | sd_d S zMt  I d H \_}}jrY|_	t t j
||I d H }tr\tjtr_tj|d}tj|d}j}t|d_| I d H  W d S W d S W d S W d S  tjttfyy } zt|}||d }~ww )NF)ssl)	connector)session)r   _run_in_executorgoogleauthr	   _mtls_helpercheck_use_client_certr*   get_client_cert_and_keyr,   make_client_cert_ssl_contextr(   r$   r.   r)   aiohttpTCPConnectorClientSessioncloser   ClientCertErrorImportErrorOSErrorMutualTLSChannelError)	use_client_certcertkeyssl_contextr2   new_sessionold_auth_request
caught_excnew_excclient_cert_callbackr/   r   r   _do_configure   sJ   



zDAsyncAuthorizedSession.configure_mtls_channel.<locals>._do_configure)r+   r   create_task)r/   rL   rM   r   rK   r   configure_mtls_channel   s
   
*z-AsyncAuthorizedSession.configure_mtls_channelmethodurldataheadersmax_allowed_timer   total_attemptsreturnc              	      s.  | j rz| j I dH  W n	 ty   Y nw tj|d}	|du r"i }t|4 I dH `}
|
| j| j|||I dH  d}tdurPt	|trP|j
durM|j
nd}nt	|ttfr[t|}|	2 z 3 dH W }|
| j|||||fi |I dH }|jtjvr} nq]6 W d  I dH  |S 1 I dH sw   Y  |S )aY  
        Args:
                method (str): The http method used to make the request.
                url (str): The URI to be requested.
                data (Optional[bytes]): The payload or body in HTTP request.
                headers (Optional[Mapping[str, str]]): Request headers.
                timeout (float, aiohttp.ClientTimeout):
                The amount of time in seconds to wait for the server response
                with each individual request.
                max_allowed_time (float):
                If the method runs longer than this, a ``Timeout`` exception is
                automatically raised. Unlike the ``timeout`` parameter, this
                value applies to the total method execution time, even if
                multiple requests are made under the hood.
                total_attempts (int):
                The total number of retry attempts.

                Mind that it is not guaranteed that the timeout error is raised
                at ``max_allowed_time``. It might take longer, for example, if
                an underlying request takes a lot of time, but the request
                itself does not timeout, e.g. if a large file is being
                transmitted. The timeout error will be raised after such
                request completes.

        Returns:
                google.auth.aio.transport.Response: The HTTP response.

        Raises:
                google.auth.exceptions.TimeoutError: If the method does not complete within
                the configured `max_allowed_time` or the request exceeds the configured
                `timeout`.
        N)rU   g        )r+   	Exceptionr   AsyncExponentialBackoffr    r'   before_requestr.   r   r$   totalintfloatstatus_coder	   DEFAULT_RETRYABLE_STATUS_CODES)r/   rP   rQ   rR   rS   rT   r   rU   kwargsretriesr   actual_timeout_r   r   r   r   request   sN   +



zAsyncAuthorizedSession.requestc                    &   | j d||||||fi |I dH S )  
        Args:
                url (str): The URI to be requested.
                data (Optional[bytes]): The payload or body in HTTP request.
                headers (Optional[Mapping[str, str]]): Request headers.
                max_allowed_time (float):
                If the method runs longer than this, a ``Timeout`` exception is
                automatically raised. Unlike the ``timeout`` parameter, this
                value applies to the total method execution time, even if
                multiple requests are made under the hood.
                timeout (float, aiohttp.ClientTimeout):
                The amount of time in seconds to wait for the server response
                with each individual request.
                total_attempts (int):
                The total number of retry attempts.

                Mind that it is not guaranteed that the timeout error is raised
                at ``max_allowed_time``. It might take longer, for example, if
                an underlying request takes a lot of time, but the request
                itself does not timeout, e.g. if a large file is being
                transmitted. The timeout error will be raised after such
                request completes.

        Returns:
                google.auth.aio.transport.Response: The HTTP response.

        Raises:
                google.auth.exceptions.TimeoutError: If the method does not complete within
                the configured `max_allowed_time` or the request exceeds the configured
                `timeout`.
        GETNrc   r/   rQ   rR   rS   rT   r   rU   r_   r   r   r   get.     *zAsyncAuthorizedSession.getc                    rd   )re   POSTNrg   rh   r   r   r   postc  rj   zAsyncAuthorizedSession.postc                    rd   )re   PUTNrg   rh   r   r   r   put  rj   zAsyncAuthorizedSession.putc                    rd   )re   PATCHNrg   rh   r   r   r   patch  rj   zAsyncAuthorizedSession.patchc                    rd   )re   DELETENrg   rh   r   r   r   delete  rj   zAsyncAuthorizedSession.deletec                 C   s   | j S )z#Indicates if mutual TLS is enabled.)r*   r/   r   r   r   is_mtls7  s   zAsyncAuthorizedSession.is_mtlsc                    s   | j  I dH  dS )z<
        Close the underlying auth request session.
        N)r.   r>   rs   r   r   r   r>   <  s   zAsyncAuthorizedSession.close)N)rV   N)__name__
__module____qualname____doc__r
   r   r	   r   r0   rO   _DEFAULT_TIMEOUT_SECONDSDEFAULT_MAX_RETRY_ATTEMPTSstrbytesr   r\   r   r   r[   Responserc   	functoolswrapsri   rl   rn   rp   rr   propertyrt   r>   r   r   r   r   r!   \   s   &

M


O
	4
	4
	4
	4
	4
r!   )!r   
contextlibr   r~   r   typingr   r   r   r   google.authr   r   google.auth.aior	   google.auth.aio.credentialsr
   google.auth.aio.transportr   google.auth.exceptionsr   "google.auth.transport._mtls_helperr5   r;   r   r@   AttributeError!google.auth.aio.transport.aiohttpr   r)   r(   r    r!   r   r   r   r   <module>   s:   
+