o
    Þ­j™]  ã                	   @   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© ú_/var/www/html/CropPilot/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 s�w   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:   ÿÿ
+