U
    /j                  
   @   s  d Z ddlZddlZddlmZmZmZmZmZ zddl	Z	W n, e
k
rh Z ze
deW 5 dZ[X Y nX ddlmZ ddlmZ ddlmZ ddlmZ erddl	mZ n.zddl	mZ W n e
efk
r   dZY nX eeZG d	d
 d
ejZG dd dejZdS )zBTransport adapter for Asynchronous HTTP Requests based on aiohttp.    N)AsyncGeneratorMappingOptionalTYPE_CHECKINGUnionzjThe aiohttp library is not installed from please install the aiohttp package to use the aiohttp transport.)_helpers)
exceptions)	transport)ClientTimeoutc                   @   s   e Zd ZdZejdddZee	e
jedddZee	e
jeeef ddd	Ze	e
jdeeedf dddZe	e
jedddZe	e
jdd ZdS )Responseaz  
    Represents an HTTP response and its data. It is returned by ``google.auth.aio.transport.sessions.AsyncAuthorizedSession``.

    Args:
        response (aiohttp.ClientResponse): An instance of aiohttp.ClientResponse.

    Attributes:
        status_code (int): The HTTP status code of the response.
        headers (Mapping[str, str]): The HTTP headers of the response.
    )responsec                 C   s
   || _ d S N)	_response)selfr    r   E/tmp/pip-unpacked-wheel-l8yytoim/google/auth/aio/transport/aiohttp.py__init__9   s    zResponse.__init__returnc                 C   s   | j jS r   )r   statusr   r   r   r   status_code<   s    zResponse.status_codec                 C   s   dd | j j D S )Nc                 S   s   i | ]\}}||qS r   r   ).0keyvaluer   r   r   
<dictcomp>D   s      z$Response.headers.<locals>.<dictcomp>)r   headersitemsr   r   r   r   r   A   s    zResponse.headers   N)
chunk_sizer   c              
   C  s^   z(| j j|2 z3 d H W }|V  q6 W n0 tjk
rX } ztd|W 5 d }~X Y nX d S )Nz'Failed to read from the payload stream.)r   contentZiter_chunkedaiohttpZClientPayloadErrorr   ResponseError)r   r   chunkexcr   r   r   r    F   s    zResponse.contentc              
      sH   z| j  I d H W S  tjk
rB } ztd|W 5 d }~X Y nX d S )Nz!Failed to read the response body.)r   readr!   ZClientResponseErrorr   r"   )r   r$   r   r   r   r%   R   s    zResponse.readc                    s   | j   d S r   )r   closer   r   r   r   r&   Y   s    zResponse.close)r   )__name__
__module____qualname____doc__r!   ZClientResponser   propertyr   Zcopy_docstringr	   r   intr   r   strr   r   bytesr    r%   r&   r   r   r   r   r   -   s   




r   c                   @   sr   e Zd ZdZdeej dddZdddej	fe
e
ee eee
e
f  eeef ejddd	Zdd
ddZdS )Requesta  Asynchronous Requests request adapter.

    This class is used internally for making requests using aiohttp
    in a consistent way. If you use :class:`google.auth.aio.transport.sessions.AsyncAuthorizedSession`
    you do not need to construct or use this class directly.

    This class can be useful if you want to configure a Request callable
    with a custom ``aiohttp.ClientSession`` in :class:`AuthorizedSession` or if
    you want to manually refresh a :class:`~google.auth.aio.credentials.Credentials` instance::

        import aiohttp
        import google.auth.aio.transport.aiohttp

        # Default example:
        request = google.auth.aio.transport.aiohttp.Request()
        await credentials.refresh(request)

        # Custom aiohttp Session Example:
        session = session=aiohttp.ClientSession(auto_decompress=False)
        request = google.auth.aio.transport.aiohttp.Request(session=session)
        auth_session = google.auth.aio.transport.sessions.AsyncAuthorizedSession(auth_request=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__
    N)sessionc                 C   s   || _ d| _d S )NF)_session_closed)r   r0   r   r   r   r   |   s    zRequest.__init__GET)urlmethodbodyr   timeoutr   c              
      s&  z| j rtd| js"t | _t|tjr4|}ntj|d}t	t
|||| | jj||f|||d|I dH }tt
|I dH  t|W S  tjk
r }	 ztd| d}
|
|	W 5 d}	~	X Y nV tjk
r  }	 z4t|tjr|j}n|}td| d}||	W 5 d}	~	X Y nX dS )	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 (float): 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
                aiohttp :meth:`aiohttp.Session.request` method.

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

        Raises:
            - google.auth.exceptions.TransportError: If the request fails or if the session is closed.
            - google.auth.exceptions.TimeoutError: If the request times out.
        zsession is closed.)total)datar   r7   NzFailed to send request to .zRequest timed out after z	 seconds.)r2   r   ZTransportErrorr1   r!   ClientSession
isinstancer
   r   Zrequest_log_LOGGERrequest_helpers_asyncZresponse_log_asyncr   ZClientErrorasyncioTimeoutErrorr8   )r   r4   r5   r6   r   r7   kwargsZclient_timeoutr   
caught_excZ
client_excZtimeout_secondsZtimeout_excr   r   r   __call__   s@    "



zRequest.__call__r   c                    s&   | j s| jr| j I dH  d| _ dS )zY
        Close the underlying aiohttp session to release the acquired resources.
        NT)r2   r1   r&   r   r   r   r   r&      s    zRequest.close)N)r'   r(   r)   r*   r   r!   r;   r   r	   Z_DEFAULT_TIMEOUT_SECONDSr-   r.   r   r   floatr
   r   rD   r&   r   r   r   r   r/   ^   s   
Gr/   )r*   r@   loggingtypingr   r   r   r   r   r!   ImportErrorrC   Zgoogle.authr   r   Zgoogle.auth.aior?   r	   r
   AttributeError	getLoggerr'   r=   r   r/   r   r   r   r   <module>   s0   

1