
    @wja                     .   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
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     `/root/dashboard-youtube/.venv/lib/python3.12/site-packages/google/auth/aio/transport/sessions.py_remaining_timez&timeout_guard.<locals>._remaining_timeD   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_timeoutM   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$   2   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.

        This method configures mTLS if client certificates are explicitly enabled
        (via GOOGLE_API_USE_CLIENT_CERTIFICATE=true) or auto-enabled (when the env
        variable is unset and workload certificates are discovered). In these cases,
        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                  8  K   t        j                  t        j                  j                  j
                  j                         d {   } | sy 	 t        j                  
       d {   \  }}}|rt        rt        j                  t              rt        j                  t         j                  ||       d {   }t        j                  |      }t        j                  |      }j                  }t        |      _
        	 |j!                          d {    nd}t%        j&                  dt(               |_        |r|_        y d _        y 7 7 7 7 A# t"        $ r Y -w xY w# t"        $ r}t/        j0                  |      }	|	|d }~ww xY ww)N)ssl)	connector)sessionFa9  Attempted to establish mTLS, but a custom async transport was provided. google-auth cannot automatically configure custom transports for mTLS. Falling back to standard TLS. If your custom transport is not manually configured for mTLS, you may encounter 401 Unauthorized errors when using Certificate-Bound Tokens.)r   _run_in_executorgoogleauthr
   _mtls_helpercheck_use_client_certget_client_cert_and_keyr.   r*   r4   r/   make_client_cert_ssl_contextaiohttpTCPConnectorClientSessionclose	ExceptionwarningswarnUserWarningr0   r2   r	   MutualTLSChannelError)use_client_certis_mtls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   s    (,(=(=KK))66LL) # '-2
 #::;OPP	 , ..2 150E0E $ A A41 +K )0(<(<(MI*1*?*?)*TK/3/A/A,1?1TD.%&6&<&<&> > >
 ',G$MM!B
 !, %,DM,0),0)_# Q+ !?#, % $%( ! 2(>>zJG!z12s   AFE	FE1 )E*AE1 <E=AE1 E" E E" #-E1 FE1 FE1 E1  E" "	E.+E1 -E..E1 1	F:FFF)r1   r   create_task)r5   rU   rV   s   `` r   configure_mtls_channelz-AsyncAuthorizedSession.configure_mtls_channel   sD     2 '52n $+#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   rG   r   AsyncExponentialBackoffr$   r-   before_requestr4   r   r*   totalintfloatstatus_coder
   DEFAULT_RETRYABLE_STATUS_CODES)r5   rY   rZ   r[   r\   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rl   r5   rZ   r[   r\   r]   r#   r^   rh   s           r   getzAsyncAuthorizedSession.get=  E     T "T\\	
 	
 	
 		
 	
   &$&c           	      P   K    | j                   d||||||fi | d{   S 7 w)rn   POSTNrp   rq   s           r   postzAsyncAuthorizedSession.postr  sE     T "T\\	
 	
 	
 		
 	
rt   c           	      P   K    | j                   d||||||fi | d{   S 7 w)rn   PUTNrp   rq   s           r   putzAsyncAuthorizedSession.put  rs   rt   c           	      P   K    | j                   d||||||fi | d{   S 7 w)rn   PATCHNrp   rq   s           r   patchzAsyncAuthorizedSession.patch  sE     T "T\\	
 	
 	
 		
 	
rt   c           	      P   K    | j                   d||||||fi | d{   S 7 w)rn   DELETENrp   rq   s           r   deletezAsyncAuthorizedSession.delete  sE     T "T\\	
 	
 	
 		
 	
rt   c                     | j                   S )z#Indicates if mutual TLS is enabled.)r0   r5   s    r   rM   zAsyncAuthorizedSession.is_mtlsF  s     }}r   c                 4  K   | j                   rI| j                   j                         s/| j                   j                          	 | j                    d{    | j
                  j                          d{    y7 '# t        j                  $ r Y :w xY w7  w)z<
        Close the underlying auth request session.
        N)r1   donecancelr   CancelledErrorr4   rF   r   s    r   rF   zAsyncAuthorizedSession.closeK  s      (<(<(A(A(C  '')****   &&((( +)) (sH   ABA= A;A= B5B6B;A= =BBBB)N)r_   N)__name__
__module____qualname____doc__r   r   r
   r   r6   rX   _DEFAULT_TIMEOUT_SECONDSDEFAULT_MAX_RETRY_ATTEMPTSstrbytesr   re   r   r   rd   Responserl   	functoolswrapsrr   rw   rz   r}   r   propertyrM   rF    r   r   r&   r&   ^   sV   #L UY+&+6>y?P?P6Q+(T*t !%/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   rH   google.authr   r	   google.auth.aior
   google.auth.aio.credentialsr   google.auth.aio.transportr   google.auth.exceptionsr   "google.auth.transport._mtls_helperr=   rC   r   ImportErrorAttributeError!google.auth.aio.transport.aiohttpr   r/   r.   r$   r&   r   r   r   <module>r      s     *   : :  8 % 3 * / )%)K
 ( (Vw) w)s (   s$   
A;  B
 ;	BB
BB