
    p[i]                     &   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rd dlZd d	lmZ n	 d dlZd d	lmZ 	 d d
lmZ dZed        Z G d d      Z y# eef$ r dZY 'w xY w# e$ r dZY +w xY w)    N)asynccontextmanager)MappingOptionalTYPE_CHECKINGUnion)_exponential_backoff
exceptions)	transport)Credentials)mtls)TimeoutError)ClientTimeout)RequestTFc                   K   t        j                         | fdfd}	 |          y#          w xY w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                  h    t        j                         z
  } | z
  }|dk  rt        d d      |S )Nr   z3Context manager exceeded the configured timeout of s.)time	monotonicr   )elapsed	remainingstarttotal_timeouts     [/mnt/data/GridWatch/venv/lib/python3.12/site-packages/google/auth/aio/transport/sessions.py_remaining_timez&timeout_guard.<locals>._remaining_timeB   sG    .."U*!G+	>Em_TVW      c                    K   	         }t        j                  | |       d {   }|S 7 # t         j                  t        f$ r}t        d|  d d      |d }~ww xY ww)NzThe operation z$ exceeded the configured timeout of r   )asynciowait_forr   )coror   responseer   r   s       r   with_timeoutz#timeout_guard.<locals>.with_timeoutK   sq     	')I$--dI>>HO ?$$l3 	 &J=/Y[\	s1   A" . ,. A". AAAA"N)r   r   )timeoutr"   r   r   r   s     @@@r   timeout_guardr$   0   s=      NNEM 	s   #A6 A	?Ac                      e Zd ZdZ	 ddedeej                     fdZ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Z ej,                  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       Z ej,                  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       Z ej,                  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       Z ej,                  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       Z ej,                  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       Zed        ZddZy)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                    t        |t              s"t        j                  dt	        |       d      || _        |}|st        r
t               }d| _        d | _	        d | _
        |t        j                  d      || _        y )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(   r4   s       r   __init__zAsyncAuthorizedSession.__init__   s     +{3((5d;6G5H  IS  T  ($!2*,M#  ++ I  +r   c                     K    j                   % fd}t        j                   |              _          j                    d{   S 7 w)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                    K   t        j                  t        j                  j                  j
                  j                         d {   } | sd
_        y 	 t        j                  	       d {   \  
_        }}
j                  r|
_	        t        j                  t         j                  ||       d {   }t        r}t        
j                  t              rbt        j                   |      }t        j"                  |      }
j                  }t        |      
_        |j%                          d {    y y y y 7 7 7 7 # t&        j(                  t*        t,        f$ r}t'        j.                  |      }||d }~ww xY ww)NF)ssl)	connector)session)r   _run_in_executorgoogleauthr
   _mtls_helpercheck_use_client_certr0   get_client_cert_and_keyr2   make_client_cert_ssl_contextr.   r*   r4   r/   aiohttpTCPConnectorClientSessioncloser	   ClientCertErrorImportErrorOSErrorMutualTLSChannelError)use_client_certcertkeyssl_contextr:   new_sessionold_auth_request
caught_excnew_excclient_cert_callbackr5   s            r   _do_configurezDAsyncAuthorizedSession.configure_mtls_channel.<locals>._do_configure   se    (,(=(=KK))66LL) # '$)DM2
 #::;OPP	 }},0),0,A,A ==tS- '
 - ..2 )0(<(<(MI*1*?*?)*TK/3/A/A,1?1TD."2"8"8":::2, %# Q' ; .. 2
 )>>zJG!z12sn   AF	E	F	E 0E1AE 9E:B E :E	;E ?F	E E 	E F)FFF	)r1   r   create_task)r5   rS   rT   s   `` r   configure_mtls_channelz-AsyncAuthorizedSession.configure_mtls_channel   sD     2 '(2T $+#6#6}#GD )))))s   AAA
Amethodurldataheadersmax_allowed_timer#   total_attemptsreturnc                   K   | j                   r	 | j                    d{    t        j                  |      }	|i }t	        |      4 d{   }
 |
| j
                  j                  | j                  |||             d{    d}t        +t        |t              r|j                  |j                  nd}n!t        |t        t        f      rt        |      }|	2 3 d{   } |
 | j                  |||||fi |       d{   }|j                  t        j                  vsK ddd      d{    S 7 # t        $ r Y 'w xY w7 7 7 q7 N6 07 $# 1 d{  7  sw Y   S xY ww)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)r\   g        )r1   	Exceptionr   AsyncExponentialBackoffr$   r-   before_requestr4   r   r*   totalintfloatstatus_coder
   DEFAULT_RETRYABLE_STATUS_CODES)r5   rW   rX   rY   rZ   r[   r#   r\   kwargsretriesr"   actual_timeout_r    s                 r   requestzAsyncAuthorizedSession.request   s    V ****
 '>>)
 ?G !12 	 	l!!00&&W   %(N(Z-O29--2KQTGc5\2!&w #  a!-&D&&VT7NFL" 
 ''y/W/WW+	 	, A +  	 #	 	 	 	, s   E2D? D<D? )E2EE22EEAEE"E#E&!EE E)E*E25E6E2<D? ?	EE2EE2EEEEE2E/"E%#E/*E2c           	      P   K    | j                   d||||||fi | d{   S 7 w)  
        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rk   r5   rX   rY   rZ   r[   r#   r\   rg   s           r   getzAsyncAuthorizedSession.get.  E     T "T\\	
 	
 	
 		
 	
   &$&c           	      P   K    | j                   d||||||fi | d{   S 7 w)rm   POSTNro   rp   s           r   postzAsyncAuthorizedSession.postc  sE     T "T\\	
 	
 	
 		
 	
rs   c           	      P   K    | j                   d||||||fi | d{   S 7 w)rm   PUTNro   rp   s           r   putzAsyncAuthorizedSession.put  rr   rs   c           	      P   K    | j                   d||||||fi | d{   S 7 w)rm   PATCHNro   rp   s           r   patchzAsyncAuthorizedSession.patch  sE     T "T\\	
 	
 	
 		
 	
rs   c           	      P   K    | j                   d||||||fi | d{   S 7 w)rm   DELETENro   rp   s           r   deletezAsyncAuthorizedSession.delete  sE     T "T\\	
 	
 	
 		
 	
rs   c                     | j                   S )z#Indicates if mutual TLS is enabled.)r0   r5   s    r   is_mtlszAsyncAuthorizedSession.is_mtls7  s     }}r   c                 T   K   | j                   j                          d{    y7 w)z<
        Close the underlying auth request session.
        N)r4   rF   r   s    r   rF   zAsyncAuthorizedSession.close<  s         &&(((s   (&()N)r]   N)__name__
__module____qualname____doc__r   r   r
   r   r6   rV   _DEFAULT_TIMEOUT_SECONDSDEFAULT_MAX_RETRY_ATTEMPTSstrbytesr   rd   r   r   rc   Responserk   	functoolswrapsrq   rv   ry   r|   r   propertyr   rF    r   r   r&   r&   \   sV   #L UY+&+6>y?P?P6Q+(G*Z !%/3"+"D"D/8/Q/Q(1(L(LMM M uo	M
 '#s(+,M  M um+,M !M 
		M^ Y__W !%/3"+"D"D/8/Q/Q(1(L(L2
2
 uo2
 '#s(+,	2

  2
 um+,2
 !2
 
		2
 2
h Y__W !%/3"+"D"D/8/Q/Q(1(L(L2
2
 uo2
 '#s(+,	2

  2
 um+,2
 !2
 
		2
 2
h Y__W !%/3"+"D"D/8/Q/Q(1(L(L2
2
 uo2
 '#s(+,	2

  2
 um+,2
 !2
 
		2
 2
h Y__W !%/3"+"D"D/8/Q/Q(1(L(L2
2
 uo2
 '#s(+,	2

  2
 um+,2
 !2
 
		2
 2
h Y__W !%/3"+"D"D/8/Q/Q(1(L(L2
2
 uo2
 '#s(+,	2

  2
 um+,2
 !2
 
		2
 2
h  )r   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_helperr=   rC   r   rH   AttributeError!google.auth.aio.transport.aiohttpr   r/   r.   r$   r&   r   r   r   <module>r      s     *   : : 8 % 3 * / )%)
K
 ( (Vd) d)q (   s$   
A7 B 7	BBBB