
    5iF]                     $   d Z ddlZddlZddlmZmZmZmZm	Z	m
Z
 ddlmZmZmZmZ ddlZddlmZ ddlmZ ddlmZ ddlmZmZmZmZmZ ddlZ G d	 d
e      Z G d de      Z G d de      Z  G d de      Z! G d de!      Z" G d de!      Z#y)z
HTTP AsyncIO support

This module provides asyncio wrappers around the awscrt.http module.
All network operations in `awscrt.aio.http` are asynchronous and use Python's asyncio framework.
    N)HttpClientConnectionBaseHttpRequestHttpClientStreamBaseHttpProxyOptionsHttp2SettingHttpVersion)ClientBootstrapSocketOptionsTlsConnectionOptionsInputStream)deque)BytesIO)Future)ListTupleOptionalCallableAsyncIteratorc                       e Zd ZdZe	 	 	 	 	 	 ddededee   dee	   dee
   dee   d	ed
ee   dd fd       ZddZ	 	 ddddee   deej$                     ddfdZy)AIOHttpClientConnectionUnifiedz
    An async unified HTTP client connection for either a HTTP/1 or HTTP/2 connection.

    Use `AIOHttpClientConnectionUnified.new()` to establish a new connection.
    N	host_nameport	bootstrapsocket_optionstls_connection_optionsproxy_optionsmanual_window_managementinitial_window_sizereturnc	                 |   K   | j                  ||||||d||	      }	t        j                  |	       d{   S 7 w)a!	  
        Asynchronously establish a new AIOHttpClientConnectionUnified.

        Args:
            host_name (str): Connect to host.

            port (int): Connect to port.

            bootstrap (Optional [ClientBootstrap]): Client bootstrap to use when initiating socket connection.
                If None is provided, the default singleton is used.

            socket_options (Optional[SocketOptions]): Optional socket options.
                If None is provided, then default options are used.

            tls_connection_options (Optional[TlsConnectionOptions]): Optional TLS
                connection options. If None is provided, then the connection will
                be attempted over plain-text.

            proxy_options (Optional[HttpProxyOptions]): Optional proxy options.
                If None is provided then a proxy is not used.

            manual_window_management (bool): Set to True to manually manage the flow-control window
                of each stream. If False, the connection maintains flow-control windows such that
                no back-pressure is applied and data arrives as fast as possible. If True, the
                flow-control window of each stream shrinks as body data is received (headers,
                padding, and other metadata do not affect the window). `initial_window_size`
                determines the starting size of each stream's window. When a stream's window
                reaches 0, no further data is received until `update_window()` is called.
                For HTTP/2, this only controls stream windows; connection window is controlled
                by `conn_manual_window_management`. Default is False.

            initial_window_size (Optional[int]): The starting size of each stream's flow-control
                window. Required if `manual_window_management` is True, ignored otherwise.
                For HTTP/2, this becomes the `INITIAL_WINDOW_SIZE` setting and can be overridden
                by `initial_settings`. Must be <= 2^31-1 or connection fails. If set to 0 with
                `manual_window_management` True, streams start with zero window.
                Required if manual_window_management is True, ignored otherwise.

        Returns:
            AIOHttpClientConnectionUnified: A new unified HTTP client connection.
        T)asyncio_connectionr   r   N)_generic_newasynciowrap_future)
clsr   r   r   r   r   r   r   r   futures
             q/home/marpiech/ifpan-abm-pgxpred/analysis/marpiech-gwas-test/venv/lib/python3.12/site-packages/awscrt/aio/http.pynewz"AIOHttpClientConnectionUnified.new#   sR     f !!"#%= 3 " 	5 ((0000s   3<:<c                    K   t        j                  | j                         t        j                  | j
                         d{    y7 w)zClose the connection asynchronously.

        Shutdown is asynchronous. This call has no effect if the connection is already
        closing.

        Returns:
            None: When shutdown is complete.
        N)_awscrthttp_connection_close_bindingr#   r$   shutdown_futureselfs    r'   closez$AIOHttpClientConnectionUnified.closeb   s4      	%%dmm4!!$"6"6777s   AAA
Arequestr   request_body_generatorloopAIOHttpClientStreamUnifiedc                     t        | |||      S )a  Create `AIOHttpClientStreamUnified` to carry out the request/response exchange.

        Args:
            request (HttpRequest): Definition for outgoing request.
            request_body_generator (AsyncIterator[bytes], optional): Async iterator providing chunks of the request body.
                If provided, the body will be sent incrementally as chunks become available.
            loop (Optional[asyncio.AbstractEventLoop]): Event loop to use for async operations.
                If None, the current event loop is used.

        Returns:
            AIOHttpClientStreamUnified: Stream for the HTTP request/response exchange.
        )r4   r/   r1   r2   r3   s       r'   r1   z&AIOHttpClientConnectionUnified.requestn   s      *$9OQUVV    )NNNNFNr   NNN)__name__
__module____qualname____doc__classmethodstrintr   r	   r
   r   r   boolr(   r0   r   bytesr#   AbstractEventLoopr1    r7   r'   r   r      s      :><@KO>B387;<1 <1<1 &o6<1 #+="9	<1
 +33G*H<1 "**:!;<1 -1<1 (0}<1 Aa<1 <1|
8 @D<@W&W(5e(<W w889W FbWr7   r   c                       e Zd ZdZe	 	 	 	 	 	 	 ddededee   dee	   dee
   dee   d	ed
ee   dee   dd fd       Z	 	 ddddee   deej"                     ddfdZy)AIOHttpClientConnectionz{
    An async HTTP/1.1 only client connection.

    Use `AIOHttpClientConnection.new()` to establish a new connection.
    Nr   r   r   r   r   r   r   r   read_buffer_capacityr   c
                    K   | j                  ||||||t        j                  d|||	      }
t        j                  |
       d{   S 7 w)a  
        Asynchronously establish a new AIOHttpClientConnection.

        Args:
            host_name (str): Connect to host.

            port (int): Connect to port.

            bootstrap (Optional [ClientBootstrap]): Client bootstrap to use when initiating socket connection.
                If None is provided, the default singleton is used.

            socket_options (Optional[SocketOptions]): Optional socket options.
                If None is provided, then default options are used.

            tls_connection_options (Optional[TlsConnectionOptions]): Optional TLS
                connection options. If None is provided, then the connection will
                be attempted over plain-text.

            proxy_options (Optional[HttpProxyOptions]): Optional proxy options.
                If None is provided then a proxy is not used.

            manual_window_management (bool): If True, enables manual flow control window management.
                Default is False.

            initial_window_size (Optional[int]): Initial window size for flow control.
                Required if manual_window_management is True, ignored otherwise.

            read_buffer_capacity (Optional[int]): Capacity in bytes of the HTTP/1.1 connection's
                read buffer. The buffer grows when the flow-control window of the incoming stream
                reaches zero. Ignored if `manual_window_management` is False. A capacity that is
                too small may hinder throughput. A capacity that is too large may waste memory
                without improving throughput. If None or zero, a default value is used.

        Returns:
            AIOHttpClientConnection: A new HTTP client connection.
        T)expected_versionr!   r   r   rG   N)r"   r   Http1_1r#   r$   )r%   r   r   r   r   r   r   r   r   rG   r&   s              r'   r(   zAIOHttpClientConnection.new   s^     ^ !!"(00#%= 3!5 " 7 ((0000s   AAA
Ar1   r   r2   r3   AIOHttpClientStreamc                     t        | ||      S )a|  Create `AIOHttpClientStream` to carry out the request/response exchange.

        Args:
            request (HttpRequest): Definition for outgoing request.
            request_body_generator (AsyncIterator[bytes], optional): Async iterator providing chunks of the request body.
                Not supported for HTTP/1.1 connections yet, use the request's body_stream instead.
            loop (Optional[asyncio.AbstractEventLoop]): Event loop to use for async operations.
                If None, the current event loop is used.

        Returns:
            AIOHttpClientStream: Stream for the HTTP request/response exchange.
        )rK   r6   s       r'   r1   zAIOHttpClientConnection.request   s      #4$77r7   )NNNNFNNr9   )r:   r;   r<   r=   r>   r?   r@   r   r	   r
   r   r   rA   r(   r   rB   r#   rC   r1   rD   r7   r'   rF   rF      s      :><@KO>B387;8<:1 :1:1 &o6:1 #+="9	:1
 +33G*H:1 "**:!;:1 -1:1 (0}:1 )1:1 B[:1 :1| @D<@8&8(5e(<8 w8898 F[8r7   rF   c                      e Zd ZdZe	 	 	 	 	 	 	 	 	 	 	 ddededee   dee	   dee
   dee   d	eee      d
eeee   gdf      dedee   dedee   dee   dd fd       Z	 	 ddddee   deej(                     ddfdZdeddfdZy)AIOHttp2ClientConnectionzz
    An async HTTP/2 only client connection.

    Use `AIOHttp2ClientConnection.new()` to establish a new connection.
    Nr   r   r   r   r   r   initial_settingson_remote_settings_changedr   r   conn_manual_window_managementconn_window_size_thresholdstream_window_size_thresholdr   c                    K   | j                  ||||||t        j                  ||d|	|
|||      }t        j                  |       d{   S 7 w)a	  
        Asynchronously establish an HTTP/2 client connection.
        Notes: to set up the connection, the server must support HTTP/2 and TlsConnectionOptions

        This class extends AIOHttpClientConnection with HTTP/2 specific functionality.

        HTTP/2 specific args:
            initial_settings (List[Http2Setting]): The initial settings to change for the connection.

            on_remote_settings_changed: Optional callback invoked once the remote peer changes its settings.
                And the settings are acknowledged by the local connection.
                The function should take the following arguments and return nothing:

                    *   `settings` (List[Http2Setting]): List of settings that were changed.

            manual_window_management (bool): If True, enables manual flow control window management.
                Default is False.

            initial_window_size (Optional[int]): Initial window size for flow control.
                Required if manual_window_management is True, ignored otherwise.

            conn_manual_window_management (bool): If True, enables manual connection-level flow control
                for the entire HTTP/2 connection. When enabled, the connection's flow-control window
                shrinks as body data is received across all streams. The initial connection window is
                65,535 bytes. When the window reaches 0, all streams stop receiving data until
                `update_window()` is called to increment the connection's window.
                Note: Padding in DATA frames counts against the window, but window updates for padding
                are sent automatically even in manual mode. Default is False.

            conn_window_size_threshold (Optional[int]): Threshold for sending connection-level WINDOW_UPDATE
                frames. Ignored if `conn_manual_window_management` is False. When the connection's window
                is above this threshold, WINDOW_UPDATE frames are batched. When it drops below, the update
                is sent. Default is 32,767 (half of the initial 65,535 window).

            stream_window_size_threshold (Optional[int]): Threshold for sending stream-level WINDOW_UPDATE
                frames. Ignored if `manual_window_management` is False. When a stream's window is above
                this threshold, WINDOW_UPDATE frames are batched. When it drops below, the update is sent.
                Default is half of `initial_window_size`.
        T)	rI   rO   rP   r!   r   r   rQ   rR   rS   N)r"   r   Http2r#   r$   )r%   r   r   r   r   r   r   rO   rP   r   r   rQ   rR   rS   r&   s                  r'   r(   zAIOHttp2ClientConnection.new   sk     l !!"(..-'A#%= 3*G'A)E " G  ((0000s   AA	A
Ar1   r   r2   r3   AIOHttp2ClientStreamc                     t        | |||      S )a  Create `AIOHttp2ClientStream` to carry out the request/response exchange.

        Args:
            request (HttpRequest): Definition for outgoing request.
            request_body_generator (AsyncIterator[bytes], optional): Async iterator providing chunks of the request body.
                If provided, the body will be sent incrementally as chunks become available from the iterator.
            loop (Optional[asyncio.AbstractEventLoop]): Event loop to use for async operations.
                If None, the current event loop is used.

        Returns:
            AIOHttp2ClientStream: Stream for the HTTP/2 request/response exchange.
        )rV   r6   s       r'   r1   z AIOHttp2ClientConnection.request'  s      $D'3I4PPr7   increment_sizec                 D    t        j                  | j                  |       y)z
        Update the connection's flow control window.

        Args:
            increment_size (int): Number of bytes to increment the window by.
        N)r*   http2_connection_update_windowr,   )r/   rX   s     r'   update_windowz&AIOHttp2ClientConnection.update_window9  s     	..t}}nMr7   )NNNNNNFNFNNr9   )r:   r;   r<   r=   r>   r?   r@   r   r	   r
   r   r   r   r   r   rA   r(   r   rB   r#   rC   r1   r[   rD   r7   r'   rN   rN      s}     :><@KO>BCG_c387;8=>B@DE1 E1E1 &o6E1 #+="9	E1
 +33G*HE1 "**:!;E1 %-T,-?$@E1 /7xlAS@TVZ@Z7[.\E1 -1E1 (0}E1 26E1 /7smE1 19E1 JdE1 E1R @D<@Q&Q(5e(<Q w889Q F\Q$NC ND Nr7   rN   c                       e Zd ZdZ	 	 ddededee   dee	j                     ddf
 fdZd	ed
eeeef      ddfdZdeddfdZddZdeddfdZddZdee   fdZdefdZdeeeef      fdZdefdZdefdZ xZS )r4   )	_response_status_future_response_headers_future_chunk_futures_received_chunks_completion_future_stream_completed_status_code_loop_deque_lockN
connectionr1   r2   r3   r   c                    |d uxr |j                   t        j                  u }t        |   |||       |t        j                         }n%t        |t
        j                        st        d      || _
        t        j                         | _        t               | _        t               | _        d| _        t%               | _        t%               | _        t%               | _        t%               | _        d | _        || _        | j0                  9| j                  j3                  | j5                  | j0                              | _        t9        j:                  |        y )N)http2_manual_writez5loop must be an instance of asyncio.AbstractEventLoopF)versionr   rU   super_init_commonr#   get_event_loop
isinstancerC   	TypeErrorrd   	threadingLockre   r   r_   r`   rb   r   ra   _remote_completion_futurer]   r^   rc   _request_body_generatorcreate_task_set_request_body_generator_writerr*   http_client_stream_activate)r/   rf   r1   r2   r3   rh   	__class__s         r'   __init__z#AIOHttpClientStreamUnified.__init__O  s    44?kJDVDVZeZkZkDkZEWX <))+DD'";";<STT
 %>>+#g %!& #)()/&'-x$(.% '=$''3::11$2R2RSWSoSo2pqDL 	++D1r7   status_codename_value_pairsc                 ~    || _         | j                  j                  |       | j                  j                  |       y N)rc   r]   
set_resultr^   )r/   ry   rz   s      r'   _on_responsez'AIOHttpClientStreamUnified._on_responseu  s3    '$$//<%%001ABr7   chunkc                    | j                   5  | j                  r| j                  j                         }n%| j                  j	                  |       	 ddd       y	 ddd       j                  |       y# 1 sw Y   xY w)z*Process body chunk - called from C thread.N)re   r_   popleftr`   appendr}   )r/   r   r&   s      r'   _on_bodyz#AIOHttpClientStreamUnified._on_body{  sq     	"",,446%%,,U3	 		 	% 	 	s   AA55A>c                     | j                   5  t        | j                        }| j                  j                          ddd       D ]  }|j	                  d        y# 1 sw Y   "xY w)zHelper to resolve all pending chunk futures with empty bytes.

        This indicates end of stream to any waiting get_next_response_chunk() calls.
        Must be called when either the stream completes or remote peer sends END_STREAM.
        Nr7   )re   listr_   clearr}   )r/   pending_futuresr&   s      r'   _resolve_pending_chunk_futuresz9AIOHttpClientStreamUnified._resolve_pending_chunk_futures  sc      	("4#6#67O%%'	(
 & 	#Fc"	#	( 	(s   0AA'
error_codec                     |dk(  r&| j                   j                  | j                         n8| j                   j                  t        j
                  j                  |             | j                          y)z(Set the completion status of the stream.r   N)ra   r}   rc   set_exceptionawscrt
exceptions	from_coder   )r/   r   s     r'   _on_completez'AIOHttpClientStreamUnified._on_complete  sT    ?##..t/@/@A##11&2C2C2M2Mj2YZ++-r7   c                 Z    | j                   j                  d       | j                          y)z?Called when the remote peer has finished sending (HTTP/2 only).N)rq   r}   r   r.   s    r'   _on_h2_remote_end_streamz3AIOHttpClientStreamUnified._on_h2_remote_end_stream  s"    &&11$7++-r7   body_iteratorc                    K   y wr|   rD   )r/   r   s     r'   rt   z6AIOHttpClientStreamUnified._set_request_body_generator  s	     s   c                 t   K   t        j                  | j                  | j                         d{   S 7 w)zrGet the response status code asynchronously.

        Returns:
            int: The response status code.
        r3   N)r#   r$   r]   rd   r.   s    r'   get_response_status_codez3AIOHttpClientStreamUnified.get_response_status_code  s+      (()E)EDJJWWWW   /868c                 t   K   t        j                  | j                  | j                         d{   S 7 w)zGet the response headers asynchronously.

        Returns:
            List[Tuple[str, str]]: The response headers as a list of (name, value) tuples.
        r   N)r#   r$   r^   rd   r.   s    r'   get_response_headersz/AIOHttpClientStreamUnified.get_response_headers  s+      (()F)FTZZXXXXr   c                   K   | j                   5  | j                  r#| j                  j                         cddd       S | j                  j	                         s| j
                  j	                         r
	 ddd       yt               }| j                  j                  |       	 ddd       t        j                  | j                         d{   S # 1 sw Y   2xY w7 w)zGet the next chunk from the response body.

        Returns:
            bytes: The next chunk of data from the response body.
                Returns empty bytes when the stream is completed and no more chunks are left.
        Nr7   r   )re   r`   r   ra   donerq   r   r_   r   r#   r$   rd   )r/   r&   s     r'   get_next_response_chunkz2AIOHttpClientStreamUnified.get_next_response_chunk  s       	3$$,,446	3 	3 ((--/43Q3Q3V3V3X		3 	3  ##**62	3 ((djjAAA	3 	3 Bs>   C"&C
C"5C4	C"=%C#,C"C C"CC"c                 t   K   t        j                  | j                  | j                         d{   S 7 w)zuWait asynchronously for the stream to complete.

        Returns:
            int: The response status code.
        r   N)r#   r$   ra   rd   r.   s    r'   wait_for_completionz.AIOHttpClientStreamUnified.wait_for_completion  s+      (()@)@tzzRRRRr   r9   r8   )r:   r;   r<   	__slots__rF   r   r   rB   r   r#   rC   rx   r@   r   r   r?   r~   r   r   r   r   rt   r   r   r   r   __classcell__rw   s   @r'   r4   r4   C  s   	I AE=A	$24$2%$2 *7u)=$2   9 9:	$2 GK	$2LC CtE#s(O?T CY] C
!e 
! 
!#.s .t ..
}U?S X XYDsCx,A YBu B&S3 Sr7   r4   c            	       R     e Zd ZdZ	 ddededeej                     ddf fdZ	 xZ
S )	rK   a  Async HTTP stream that sends a request and receives a response.

    Create an AIOHttpClientStream with `AIOHttpClientConnection.request()`.

    Attributes:
        connection (AIOHttpClientConnection): This stream's connection.

        completion_future (asyncio.Future): Future that will contain
            the response status code (int) when the request/response exchange
            completes. If the exchange fails to complete, the Future will
            contain an exception indicating why it failed.

    Notes:
        All async method on a stream (await stream.next(), etc.) must be performed in the
        thread that owns the event loop used to create the stream
    Nrf   r1   r3   r   c                 *    t         |   |||       y)ah  Initialize an HTTP client stream.

        Args:
            connection (AIOHttpClientConnection): The connection to send the request on.
            request (HttpRequest): The HTTP request to send.
            loop (Optional[asyncio.AbstractEventLoop]): Event loop to use for async operations.
                If None, the current event loop is used.
        r   Nrj   rx   )r/   rf   r1   r3   rw   s       r'   rx   zAIOHttpClientStream.__init__  s     	W48r7   r|   )r:   r;   r<   r=   rF   r   r   r#   rC   rx   r   r   s   @r'   rK   rK     sB    $ >B
9#: 
9[ 
9 9 9:
9FJ
9 
9r7   rK   c                   v     e Zd ZdZ	 	 ddededee   dee	j                     ddf
 fdZd	 Zd
ee   fdZ xZS )rV   zHTTP/2 stream that sends a request and receives a response.

    Create an AIOHttp2ClientStream with `AIOHttp2ClientConnection.request()`.
    Nrf   r1   r2   r3   r   c                 ,    t         |   ||||       y )N)r2   r3   r   )r/   rf   r1   r2   r3   rw   s        r'   rx   zAIOHttp2ClientStream.__init__  s    
 	WE[bfgr7   c                    K   t               t        j                  |d      }dt        dd ffd}t	        j
                  | |||       t        j                  | j                         d {    y 7 w)NT)
allow_noner   r   c                     j                         ry | r/j                  t        j                  j	                  |              y j                  d        y r|   )	cancelledr   r   r   r   r}   )r   r&   s    r'   on_write_completez;AIOHttp2ClientStream._write_data.<locals>.on_write_complete  sB    !$$V%6%6%@%@%LM!!$'r7   r   )	r   r   wrapr@   r*   http2_client_stream_write_datar#   r$   rd   )r/   body
end_streambody_streamr   r&   s        @r'   _write_dataz AIOHttp2ClientStream._write_data  sd     !&&t=	(# 	($ 	( 	..t[*N_`!!&tzz:::s   A,A7/A50A7r   c                    K   	 |2 3 d {   }| j                  t        |      d       d {    -7 (7 6 	 | j                  d d       d {  7   y # | j                  d d       d {  7   w xY ww)NFT)r   r   )r/   r   r   s      r'   rt   z0AIOHttp2ClientStream._set_request_body_generator  sq     	/, > >e&&wu~u===>=  - ""4...$""4...s[   A5A 737A 5A 7A A A5AA5A2+A.,A22A5r9   )r:   r;   r<   r=   rF   r   r   rB   r   r#   rC   rx   r   rt   r   r   s   @r'   rV   rV     ss     AE=A	h4h%h *7u)=h   9 9:	h GK	h; /}U?S /r7   rV   )$r=   r*   awscrt.exceptionsr   awscrt.httpr   r   r   r   r   r   	awscrt.ior	   r
   r   r   r#   collectionsr   ior   concurrent.futuresr   typingr   r   r   r   r   ro   r   rF   rN   r4   rK   rV   rD   r7   r'   <module>r      s           % A A bW%= bWJT8< T8nhN= hNVMS!5 MS`94 9>"/5 "/r7   