
    g9                        d Z ddlmZ ddlZddl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Z G d d	e	j                        Z G d
 de	j                        Z G d de	j                         Z G d dej"                        Zy)zTransport adapter for Async HTTP (aiohttp).

NOTE: This async support is experimental and marked internal. This surface may
change in minor releases.
    )absolute_importN)
exceptions)	transport)requests   c                   X    e Zd ZdZd Zd Zed        Zed        Zed        Z	d Z
d Zy	)
_CombinedResponsea@  
    In order to more closely resemble the `requests` interface, where a raw
    and deflated content could be accessed at once, this class lazily reads the
    stream in `transport.Response` so both return forms can be used.

    The gzip and deflate transfer-encodings are automatically decoded for you
    because the default parameter for autodecompress into the ClientSession is set
    to False, and therefore we add this class to act as a wrapper for a user to be
    able to access both the raw and decoded response bodies - mirroring the sync
    implementation.
    c                      || _         d | _        y N)	_response_raw_contentselfresponses     \/var/www/openai/venv/lib/python3.12/site-packages/google/auth/transport/_aiohttp_requests.py__init__z_CombinedResponse.__init__3   s    !     c                 ^    | j                   j                  }d|v xr |d   dk(  xs |d   dk(  S )NContent-Encodinggzipdeflater   headers)r   r   s     r   _is_compressedz _CombinedResponse._is_compressed7   sD    ..((!W, 
&'61 8)*i7	
r   c                 .    | j                   j                  S r   r   statusr   s    r   r   z_CombinedResponse.status>       ~~$$$r   c                 .    | j                   j                  S r   r   r   s    r   r   z_CombinedResponse.headersB       ~~%%%r   c                 .    | j                   j                  S r   r   contentr   s    r   dataz_CombinedResponse.dataF   r!   r   c                    K   | j                   1| j                  j                  j                          d {   | _         | j                   S 7 wr   )r   r   r$   readr   s    r   raw_contentz_CombinedResponse.raw_contentJ   sB     $&*nn&<&<&A&A&C CD    !Ds   4AAAc                   K   | j                          d {    | j                         rSt        j                  j	                  | j
                  j                  d         }|j                  | j                        }|S | j                  S 7 sw)Nr   )	r(   r   urllib3r   MultiDecoderr   r   
decompressr   )r   decoderdecompresseds      r   r$   z_CombinedResponse.contentO   s|         &&33&&'9:G #--d.?.?@L    	!s   BB
A4BN)__name__
__module____qualname____doc__r   r   propertyr   r   r%   r(   r$    r   r   r	   r	   &   sW    
!
 % % & & & &!

!r   r	   c                   F    e Zd ZdZd Zed        Zed        Zed        Zy)	_Responsezz
    Requests transport response adapter.

    Args:
        response (requests.Response): The raw Requests response.
    c                     || _         y r   )r   r   s     r   r   z_Response.__init__d   s	    !r   c                 .    | j                   j                  S r   r   r   s    r   r   z_Response.statusg   r   r   c                 .    | j                   j                  S r   r   r   s    r   r   z_Response.headersk   r!   r   c                 .    | j                   j                  S r   r#   r   s    r   r%   z_Response.datao   r!   r   N)	r/   r0   r1   r2   r   r3   r   r   r%   r4   r   r   r6   r6   \   sH    " % % & & & &r   r6   c                   (    e Zd ZdZddZdddefdZy)Requesta  Requests request adapter.

    This class is used internally for making requests using asyncio transports
    in a consistent way. If you use :class:`AuthorizedSession` you do not need
    to construct or use this class directly.

    This class can be useful if you want to manually refresh a
    :class:`~google.auth.credentials.Credentials` instance::

        import google.auth.transport.aiohttp_requests

        request = google.auth.transport.aiohttp_requests.Request()

        credentials.refresh(request)

    Args:
        session (aiohttp.ClientSession): An instance :class:`aiohttp.ClientSession` used
            to make HTTP requests. If not specified, a session will be created.

    .. automethod:: __call__
    Nc                 X    |!|j                   rt        j                  d      || _        y )Nz<Client sessions with auto_decompress=True are not supported.)_auto_decompressr   InvalidOperationsession)r   r@   s     r   r   zRequest.__init__   s/    7#;#;--N  r   GETc                   K   	 | j                   t        j                  d      | _         t        j                  j                  d||        | j                   j                  ||f|||d| d{   }t        |      S 7 # t        j                  $ r}t        j                  |      }	|	|d}~wt        j                  $ r}t        j                  |      }	|	|d}~ww xY ww)a  
        Make an HTTP request using aiohttp.

        Args:
            url (str): The URL to be requested.
            method (Optional[str]):
                The HTTP method to use for the request. Defaults to 'GET'.
            body (Optional[bytes]):
                The payload or body in HTTP request.
            headers (Optional[Mapping[str, str]]):
                Request headers.
            timeout (Optional[int]): The number of seconds to wait for a
                response from the server. If not specified or if None, the
                requests default timeout will be used.
            kwargs: Additional arguments passed through to the underlying
                requests :meth:`requests.Session.request` method.

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

        Raises:
            google.auth.exceptions.TransportError: If any exception occurred.
        NF)auto_decompresszMaking request: %s %sr%   r   timeout)r@   aiohttpClientSessionr   _LOGGERdebugrequestr	   ClientErrorr   TransportErrorasyncioTimeoutError)
r   urlmethodbodyr   rE   kwargsr   
caught_excnew_excs
             r   __call__zRequest.__call__   s     B	*||#&44$)  ""#:FCH1T\\11"&LR H %X..
 "" 	* //
;Gz)## 	* //
;Gz)	*sG   C$A-B 1B2B  C$B C!B..C!CC!!C$r   )r/   r0   r1   r2   r   _DEFAULT_TIMEOUTrU   r4   r   r   r<   r<   t   s    ,  2*r   r<   c                   l     e Zd ZdZej
                  ej                  dddf fd	Zdddedf fd	Z	 xZ
S )AuthorizedSessionaN  This is an async implementation of the Authorized Session class. We utilize an
    aiohttp transport instance, and the interface mirrors the google.auth.transport.requests
    Authorized Session class, except for the change in the transport used in the async use case.

    A Requests Session class with credentials.

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

        from google.auth.transport import aiohttp_requests

        async with aiohttp_requests.AuthorizedSession(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._credentials_async.Credentials):
            The credentials to add to the request.
        refresh_status_codes (Sequence[int]): Which HTTP status codes indicate
            that credentials should be refreshed and the request should be
            retried.
        max_refresh_attempts (int): The maximum number of times to attempt to
            refresh the credentials and retry the request.
        refresh_timeout (Optional[int]): The timeout value in seconds for
            credential refresh HTTP requests.
        auth_request (google.auth.transport.aiohttp_requests.Request):
            (Optional) An instance of
            :class:`~google.auth.transport.aiohttp_requests.Request` used when
            refreshing credentials. If not passed,
            an instance of :class:`~google.auth.transport.aiohttp_requests.Request`
            is created.
        kwargs: Additional arguments passed through to the underlying
            ClientSession :meth:`aiohttp.ClientSession` object.
    NFc                     t        t        | 
  di | || _        || _        || _        || _        d| _        || _        d | _	        t        j                         | _        t        j                         | _        || _        y )NFr4   )superrX   r   credentials_refresh_status_codes_max_refresh_attempts_refresh_timeout_is_mtls_auth_request_auth_request_sessionrM   get_event_loop_loopLock_refresh_lockr>   )	r   r[   refresh_status_codesmax_refresh_attemptsrefresh_timeoutauth_requestrC   rR   	__class__s	           r   r   zAuthorizedSession.__init__   su     	/9&9&%9"%9" /)%)"++-
$\\^ /r   c           
        K   |rA|j                         D ].  }	t        ||	         t        u s||	   j                  d      ||	<   0 t	        j
                  | j                  |j                  dd            4 d{   | _        t        | j                        }
|
| _
        |j                  dd      }||j                         ni }|| j                  n t        j                  | j                  |      }
|}t        j                   |t"        j$                        5 }| j&                  j)                  |
|||       d{    ddd       t        j                   |t"        j$                        5 }t+        t,        | ^  ||f|||d	| d{   }ddd       j0                  }j2                  | j4                  v rE|| j6                  k  r5t        j8                  j;                  d
|j2                  |dz   | j6                         || j                  n t        j                  | j                  |      }
t        j                   |t"        j$                        5 }| j<                  4 d{    | j>                  jA                  d| j&                  jB                  |
       d{    ddd      d{    ddd       |j0                  } | j.                  ||f|||||dz   d| d{   cddd      d{    S ddd      d{    |S 7 7 # 1 sw Y   xY w7 # 1 sw Y   xY w7 7 7 # 1 d{  7  sw Y   xY w# 1 sw Y   xY w7 q7 c7 T# 1 d{  7  sw Y   S xY ww)a  Implementation of Authorized Session aiohttp request.

        Args:
            method (str):
                The http request method used (e.g. GET, PUT, DELETE)
            url (str):
                The url at which the http request is sent.
            data (Optional[dict]): Dictionary, list of tuples, bytes, or file-like
                object to send in the body of the Request.
            headers (Optional[dict]): Dictionary of HTTP Headers to send with the
                Request.
            timeout (Optional[Union[float, aiohttp.ClientTimeout]]):
                The amount of time in seconds to wait for the server response
                with each individual request. Can also be passed as an
                ``aiohttp.ClientTimeout`` object.
            max_allowed_time (Optional[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.

                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 timout error will be raised after such
                request completes.
        zutf-8	trust_envF)rC   rl   N_credential_refresh_attemptr   )rE   rD   z;Refreshing credentials due to a %s response. Attempt %s/%s.   )r%   r   max_allowed_timerE   rm   )"keystypebytesdecoderF   rG   r>   getra   r<   r`   popcopy	functoolspartialr   TimeoutGuardrM   rN   r[   before_requestrZ   rX   rJ   remaining_timeoutr   r\   r]   rH   infore   rc   run_in_executorrefresh)r   rP   rO   r%   r   ro   rE   rC   rR   keyri   rm   request_headersremaining_timeguardr   rj   s                   r   rJ   zAuthorizedSession.request  sf    V ||~%.#*3<#6#6w#?GCL & (( 11jje4
 
 '"4#=#=>L!-D +1**5RTU*V' 180CgllnO ? ""&&t'9'97K  .N&&~w7K7KLPU&&55 &#   M
 &&~w7K7KLPU!&'8$!G" +#" "  M #44N 4#=#==/$2L2LL   %%QOO/!3..	  &&"**4+=+=wO  **"G$8$8#111"jj88 $"2"2":":L    21 "'!8!8)T\\	 #%3#0Ka0O	 	 	O
 
 
 
 
d e
2 ML MLF  2  2111 	O
 
 
 
 
d s3  *M<AM<<L=M< BM&"L?L L,M&0L,L)L,C	M&M,L9
-M05L?%L;
&L?*M5L=6M:4M&.M /M&2M<>M"?M<M$M<LL&	!M&)L,,L6	1M&9M;L?=M?MMMMM	M&"M<$M<&M9,M/-M94M<)r/   r0   r1   r2   r   DEFAULT_REFRESH_STATUS_CODESDEFAULT_MAX_REFRESH_ATTEMPTSr   rV   rJ   __classcell__)rj   s   @r   rX   rX      sH    $R 'CC&CC04  B Br   rX   )r2   
__future__r   rM   rw   rF   r*   google.authr   r   google.auth.transportr   rV   Responser	   r6   r<   rG   rX   r4   r   r   <module>r      sz    '     " ! *  3!	** 3!l&	"" &0Q*i Q*h-- r   