Debian Codegraph @

awscrt/aio/http.py

raw symbols SCIP
1 """
2 HTTP AsyncIO support
3
4 This module provides asyncio wrappers around the awscrt.http module.
5 All network operations in `awscrt.aio.http` are asynchronous and use Python's asyncio framework.
6 """
7
8 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
9 # SPDX-License-Identifier: Apache-2.0.
10
11 import _awscrt
12 import awscrt.exceptions
13 from awscrt.http import (
14 HttpClientConnectionBase, HttpRequest, HttpClientStreamBase, HttpProxyOptions,
15 Http2Setting, HttpVersion
16 )
17 from awscrt.io import (
18 ClientBootstrap, SocketOptions, TlsConnectionOptions, InputStream
19 )
20 import asyncio
21 from collections import deque
22 from io import BytesIO
23 from concurrent.futures import Future
24 from typing import List, Tuple, Optional, Callable, AsyncIterator
25 import threading
26
27
28 class AIOHttpClientConnectionUnified(HttpClientConnectionBase):
29 """
30 An async unified HTTP client connection for either a HTTP/1 or HTTP/2 connection.
31
32 Use `AIOHttpClientConnectionUnified.new()` to establish a new connection.
33 """
34
35 @classmethod
36 async def new(cls,
37 host_name: str,
38 port: int,
39 bootstrap: Optional[ClientBootstrap] = None,
40 socket_options: Optional[SocketOptions] = None,
41 tls_connection_options: Optional[TlsConnectionOptions] = None,
42 proxy_options: Optional[HttpProxyOptions] = None,
43 manual_window_management: bool = False,
44 initial_window_size: Optional[int] = None) -> "AIOHttpClientConnectionUnified":
45 """
46 Asynchronously establish a new AIOHttpClientConnectionUnified.
47
48 Args:
49 host_name (str): Connect to host.
50
51 port (int): Connect to port.
52
53 bootstrap (Optional [ClientBootstrap]): Client bootstrap to use when initiating socket connection.
54 If None is provided, the default singleton is used.
55
56 socket_options (Optional[SocketOptions]): Optional socket options.
57 If None is provided, then default options are used.
58
59 tls_connection_options (Optional[TlsConnectionOptions]): Optional TLS
60 connection options. If None is provided, then the connection will
61 be attempted over plain-text.
62
63 proxy_options (Optional[HttpProxyOptions]): Optional proxy options.
64 If None is provided then a proxy is not used.
65
66 manual_window_management (bool): Set to True to manually manage the flow-control window
67 of each stream. If False, the connection maintains flow-control windows such that
68 no back-pressure is applied and data arrives as fast as possible. If True, the
69 flow-control window of each stream shrinks as body data is received (headers,
70 padding, and other metadata do not affect the window). `initial_window_size`
71 determines the starting size of each stream's window. When a stream's window
72 reaches 0, no further data is received until `update_window()` is called.
73 For HTTP/2, this only controls stream windows; connection window is controlled
74 by `conn_manual_window_management`. Default is False.
75
76 initial_window_size (Optional[int]): The starting size of each stream's flow-control
77 window. Required if `manual_window_management` is True, ignored otherwise.
78 For HTTP/2, this becomes the `INITIAL_WINDOW_SIZE` setting and can be overridden
79 by `initial_settings`. Must be <= 2^31-1 or connection fails. If set to 0 with
80 `manual_window_management` True, streams start with zero window.
81 Required if manual_window_management is True, ignored otherwise.
82
83 Returns:
84 AIOHttpClientConnectionUnified: A new unified HTTP client connection.
85 """
86 future = cls._generic_new(
87 host_name,
88 port,
89 bootstrap,
90 socket_options,
91 tls_connection_options,
92 proxy_options,
93 asyncio_connection=True,
94 manual_window_management=manual_window_management,
95 initial_window_size=initial_window_size)
96 return await asyncio.wrap_future(future)
97
98 async def close(self) -> None:
99 """Close the connection asynchronously.
100
101 Shutdown is asynchronous. This call has no effect if the connection is already
102 closing.
103
104 Returns:
105 None: When shutdown is complete.
106 """
107 _awscrt.http_connection_close(self._binding)
108 await asyncio.wrap_future(self.shutdown_future)
109
110 def request(self,
111 request: 'HttpRequest',
112 request_body_generator: AsyncIterator[bytes] = None,
113 loop: Optional[asyncio.AbstractEventLoop] = None) -> 'AIOHttpClientStreamUnified':
114 """Create `AIOHttpClientStreamUnified` to carry out the request/response exchange.
115
116 Args:
117 request (HttpRequest): Definition for outgoing request.
118 request_body_generator (AsyncIterator[bytes], optional): Async iterator providing chunks of the request body.
119 If provided, the body will be sent incrementally as chunks become available.
120 loop (Optional[asyncio.AbstractEventLoop]): Event loop to use for async operations.
121 If None, the current event loop is used.
122
123 Returns:
124 AIOHttpClientStreamUnified: Stream for the HTTP request/response exchange.
125 """
126 return AIOHttpClientStreamUnified(self, request, request_body_generator, loop)
127
128
129 class AIOHttpClientConnection(AIOHttpClientConnectionUnified):
130 """
131 An async HTTP/1.1 only client connection.
132
133 Use `AIOHttpClientConnection.new()` to establish a new connection.
134 """
135
136 @classmethod
137 async def new(cls,
138 host_name: str,
139 port: int,
140 bootstrap: Optional[ClientBootstrap] = None,
141 socket_options: Optional[SocketOptions] = None,
142 tls_connection_options: Optional[TlsConnectionOptions] = None,
143 proxy_options: Optional[HttpProxyOptions] = None,
144 manual_window_management: bool = False,
145 initial_window_size: Optional[int] = None,
146 read_buffer_capacity: Optional[int] = None) -> "AIOHttpClientConnection":
147 """
148 Asynchronously establish a new AIOHttpClientConnection.
149
150 Args:
151 host_name (str): Connect to host.
152
153 port (int): Connect to port.
154
155 bootstrap (Optional [ClientBootstrap]): Client bootstrap to use when initiating socket connection.
156 If None is provided, the default singleton is used.
157
158 socket_options (Optional[SocketOptions]): Optional socket options.
159 If None is provided, then default options are used.
160
161 tls_connection_options (Optional[TlsConnectionOptions]): Optional TLS
162 connection options. If None is provided, then the connection will
163 be attempted over plain-text.
164
165 proxy_options (Optional[HttpProxyOptions]): Optional proxy options.
166 If None is provided then a proxy is not used.
167
168 manual_window_management (bool): If True, enables manual flow control window management.
169 Default is False.
170
171 initial_window_size (Optional[int]): Initial window size for flow control.
172 Required if manual_window_management is True, ignored otherwise.
173
174 read_buffer_capacity (Optional[int]): Capacity in bytes of the HTTP/1.1 connection's
175 read buffer. The buffer grows when the flow-control window of the incoming stream
176 reaches zero. Ignored if `manual_window_management` is False. A capacity that is
177 too small may hinder throughput. A capacity that is too large may waste memory
178 without improving throughput. If None or zero, a default value is used.
179
180 Returns:
181 AIOHttpClientConnection: A new HTTP client connection.
182 """
183 future = cls._generic_new(
184 host_name,
185 port,
186 bootstrap,
187 socket_options,
188 tls_connection_options,
189 proxy_options,
190 expected_version=HttpVersion.Http1_1,
191 asyncio_connection=True,
192 manual_window_management=manual_window_management,
193 initial_window_size=initial_window_size,
194 read_buffer_capacity=read_buffer_capacity)
195 return await asyncio.wrap_future(future)
196
197 def request(self,
198 request: 'HttpRequest',
199 request_body_generator: AsyncIterator[bytes] = None,
200 loop: Optional[asyncio.AbstractEventLoop] = None) -> 'AIOHttpClientStream':
201 """Create `AIOHttpClientStream` to carry out the request/response exchange.
202
203 Args:
204 request (HttpRequest): Definition for outgoing request.
205 request_body_generator (AsyncIterator[bytes], optional): Async iterator providing chunks of the request body.
206 Not supported for HTTP/1.1 connections yet, use the request's body_stream instead.
207 loop (Optional[asyncio.AbstractEventLoop]): Event loop to use for async operations.
208 If None, the current event loop is used.
209
210 Returns:
211 AIOHttpClientStream: Stream for the HTTP request/response exchange.
212 """
213 return AIOHttpClientStream(self, request, loop)
214
215
216 class AIOHttp2ClientConnection(AIOHttpClientConnectionUnified):
217 """
218 An async HTTP/2 only client connection.
219
220 Use `AIOHttp2ClientConnection.new()` to establish a new connection.
221 """
222
223 @classmethod
224 async def new(cls,
225 host_name: str,
226 port: int,
227 bootstrap: Optional[ClientBootstrap] = None,
228 socket_options: Optional[SocketOptions] = None,
229 tls_connection_options: Optional[TlsConnectionOptions] = None,
230 proxy_options: Optional[HttpProxyOptions] = None,
231 initial_settings: Optional[List[Http2Setting]] = None,
232 on_remote_settings_changed: Optional[Callable[[List[Http2Setting]], None]] = None,
233 manual_window_management: bool = False,
234 initial_window_size: Optional[int] = None,
235 conn_manual_window_management: bool = False,
236 conn_window_size_threshold: Optional[int] = None,
237 stream_window_size_threshold: Optional[int] = None) -> "AIOHttp2ClientConnection":
238 """
239 Asynchronously establish an HTTP/2 client connection.
240 Notes: to set up the connection, the server must support HTTP/2 and TlsConnectionOptions
241
242 This class extends AIOHttpClientConnection with HTTP/2 specific functionality.
243
244 HTTP/2 specific args:
245 initial_settings (List[Http2Setting]): The initial settings to change for the connection.
246
247 on_remote_settings_changed: Optional callback invoked once the remote peer changes its settings.
248 And the settings are acknowledged by the local connection.
249 The function should take the following arguments and return nothing:
250
251 * `settings` (List[Http2Setting]): List of settings that were changed.
252
253 manual_window_management (bool): If True, enables manual flow control window management.
254 Default is False.
255
256 initial_window_size (Optional[int]): Initial window size for flow control.
257 Required if manual_window_management is True, ignored otherwise.
258
259 conn_manual_window_management (bool): If True, enables manual connection-level flow control
260 for the entire HTTP/2 connection. When enabled, the connection's flow-control window
261 shrinks as body data is received across all streams. The initial connection window is
262 65,535 bytes. When the window reaches 0, all streams stop receiving data until
263 `update_window()` is called to increment the connection's window.
264 Note: Padding in DATA frames counts against the window, but window updates for padding
265 are sent automatically even in manual mode. Default is False.
266
267 conn_window_size_threshold (Optional[int]): Threshold for sending connection-level WINDOW_UPDATE
268 frames. Ignored if `conn_manual_window_management` is False. When the connection's window
269 is above this threshold, WINDOW_UPDATE frames are batched. When it drops below, the update
270 is sent. Default is 32,767 (half of the initial 65,535 window).
271
272 stream_window_size_threshold (Optional[int]): Threshold for sending stream-level WINDOW_UPDATE
273 frames. Ignored if `manual_window_management` is False. When a stream's window is above
274 this threshold, WINDOW_UPDATE frames are batched. When it drops below, the update is sent.
275 Default is half of `initial_window_size`.
276 """
277 future = cls._generic_new(
278 host_name,
279 port,
280 bootstrap,
281 socket_options,
282 tls_connection_options,
283 proxy_options,
284 expected_version=HttpVersion.Http2,
285 initial_settings=initial_settings,
286 on_remote_settings_changed=on_remote_settings_changed,
287 asyncio_connection=True,
288 manual_window_management=manual_window_management,
289 initial_window_size=initial_window_size,
290 conn_manual_window_management=conn_manual_window_management,
291 conn_window_size_threshold=conn_window_size_threshold,
292 stream_window_size_threshold=stream_window_size_threshold)
293 return await asyncio.wrap_future(future)
294
295 def request(self,
296 request: 'HttpRequest',
297 request_body_generator: AsyncIterator[bytes] = None,
298 loop: Optional[asyncio.AbstractEventLoop] = None) -> 'AIOHttp2ClientStream':
299 """Create `AIOHttp2ClientStream` to carry out the request/response exchange.
300
301 Args:
302 request (HttpRequest): Definition for outgoing request.
303 request_body_generator (AsyncIterator[bytes], optional): Async iterator providing chunks of the request body.
304 If provided, the body will be sent incrementally as chunks become available from the iterator.
305 loop (Optional[asyncio.AbstractEventLoop]): Event loop to use for async operations.
306 If None, the current event loop is used.
307
308 Returns:
309 AIOHttp2ClientStream: Stream for the HTTP/2 request/response exchange.
310 """
311 return AIOHttp2ClientStream(self, request, request_body_generator, loop)
312
313 def update_window(self, increment_size: int) -> None:
314 """
315 Update the connection's flow control window.
316
317 Args:
318 increment_size (int): Number of bytes to increment the window by.
319 """
320 _awscrt.http2_connection_update_window(self._binding, increment_size)
321
322
323 class AIOHttpClientStreamUnified(HttpClientStreamBase):
324 __slots__ = (
325 '_response_status_future',
326 '_response_headers_future',
327 '_chunk_futures',
328 '_received_chunks',
329 '_completion_future',
330 '_stream_completed',
331 '_status_code',
332 '_loop',
333 '_deque_lock')
334
335 def __init__(self,
336 connection: AIOHttpClientConnection,
337 request: HttpRequest,
338 request_body_generator: AsyncIterator[bytes] = None,
339 loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
340
341 # Initialize the parent class
342 http2_manual_write = request_body_generator is not None and connection.version is HttpVersion.Http2
343 super()._init_common(connection, request, http2_manual_write=http2_manual_write)
344
345 # Attach the event loop for async operations
346 if loop is None:
347 # Use the current event loop if none is provided
348 loop = asyncio.get_event_loop()
349 elif not isinstance(loop, asyncio.AbstractEventLoop):
350 raise TypeError("loop must be an instance of asyncio.AbstractEventLoop")
351 self._loop = loop
352
353 # Lock to protect check-then-act sequences on deques for thread safety in free-threaded Python
354 self._deque_lock = threading.Lock()
355 self._chunk_futures = deque()
356 self._received_chunks = deque()
357 self._stream_completed = False
358
359 # Create futures for async operations
360 self._completion_future = Future()
361 self._remote_completion_future = Future()
362 self._response_status_future = Future()
363 self._response_headers_future = Future()
364 self._status_code = None
365
366 self._request_body_generator = request_body_generator
367 if self._request_body_generator is not None:
368 self._writer = self._loop.create_task(self._set_request_body_generator(self._request_body_generator))
369
370 # Activate the stream immediately
371 _awscrt.http_client_stream_activate(self)
372
373 def _on_response(self, status_code: int, name_value_pairs: List[Tuple[str, str]]) -> None:
374 self._status_code = status_code
375 # invoked from the C thread, so we need to schedule the result setting on the event loop
376 self._response_status_future.set_result(status_code)
377 self._response_headers_future.set_result(name_value_pairs)
378
379 def _on_body(self, chunk: bytes) -> None:
380 """Process body chunk - called from C thread."""
381 with self._deque_lock:
382 if self._chunk_futures:
383 future = self._chunk_futures.popleft()
384 else:
385 self._received_chunks.append(chunk)
386 return
387
388 # Set result outside lock (Future is thread-safe)
389 future.set_result(chunk)
390
391 def _resolve_pending_chunk_futures(self) -> None:
392 """Helper to resolve all pending chunk futures with empty bytes.
393
394 This indicates end of stream to any waiting get_next_response_chunk() calls.
395 Must be called when either the stream completes or remote peer sends END_STREAM.
396 """
397 # Resolve all pending chunk futures with lock protection
398 with self._deque_lock:
399 pending_futures = list(self._chunk_futures)
400 self._chunk_futures.clear()
401
402 # Set results outside lock (Future is thread-safe)
403 for future in pending_futures:
404 future.set_result(b"")
405
406 def _on_complete(self, error_code: int) -> None:
407 """Set the completion status of the stream."""
408 if error_code == 0:
409 self._completion_future.set_result(self._status_code)
410 else:
411 self._completion_future.set_exception(awscrt.exceptions.from_code(error_code))
412
413 self._resolve_pending_chunk_futures()
414
415 def _on_h2_remote_end_stream(self) -> None:
416 """Called when the remote peer has finished sending (HTTP/2 only)."""
417 self._remote_completion_future.set_result(None)
418 self._resolve_pending_chunk_futures()
419
420 async def _set_request_body_generator(self, body_iterator: AsyncIterator[bytes]):
421 ...
422
423 async def get_response_status_code(self) -> int:
424 """Get the response status code asynchronously.
425
426 Returns:
427 int: The response status code.
428 """
429 return await asyncio.wrap_future(self._response_status_future, loop=self._loop)
430
431 async def get_response_headers(self) -> List[Tuple[str, str]]:
432 """Get the response headers asynchronously.
433
434 Returns:
435 List[Tuple[str, str]]: The response headers as a list of (name, value) tuples.
436 """
437 return await asyncio.wrap_future(self._response_headers_future, loop=self._loop)
438
439 async def get_next_response_chunk(self) -> bytes:
440 """Get the next chunk from the response body.
441
442 Returns:
443 bytes: The next chunk of data from the response body.
444 Returns empty bytes when the stream is completed and no more chunks are left.
445 """
446 with self._deque_lock:
447 if self._received_chunks:
448 return self._received_chunks.popleft()
449 elif self._completion_future.done() or self._remote_completion_future.done():
450 return b""
451 else:
452 future = Future()
453 self._chunk_futures.append(future)
454
455 # Await outside lock
456 return await asyncio.wrap_future(future, loop=self._loop)
457
458 async def wait_for_completion(self) -> int:
459 """Wait asynchronously for the stream to complete.
460
461 Returns:
462 int: The response status code.
463 """
464 return await asyncio.wrap_future(self._completion_future, loop=self._loop)
465
466
467 class AIOHttpClientStream(AIOHttpClientStreamUnified):
468 """Async HTTP stream that sends a request and receives a response.
469
470 Create an AIOHttpClientStream with `AIOHttpClientConnection.request()`.
471
472 Attributes:
473 connection (AIOHttpClientConnection): This stream's connection.
474
475 completion_future (asyncio.Future): Future that will contain
476 the response status code (int) when the request/response exchange
477 completes. If the exchange fails to complete, the Future will
478 contain an exception indicating why it failed.
479
480 Notes:
481 All async method on a stream (await stream.next(), etc.) must be performed in the
482 thread that owns the event loop used to create the stream
483 """
484
485 def __init__(self, connection: AIOHttpClientConnection, request: HttpRequest,
486 loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
487 """Initialize an HTTP client stream.
488
489 Args:
490 connection (AIOHttpClientConnection): The connection to send the request on.
491 request (HttpRequest): The HTTP request to send.
492 loop (Optional[asyncio.AbstractEventLoop]): Event loop to use for async operations.
493 If None, the current event loop is used.
494 """
495 super().__init__(connection, request, loop=loop)
496
497
498 class AIOHttp2ClientStream(AIOHttpClientStreamUnified):
499 """HTTP/2 stream that sends a request and receives a response.
500
501 Create an AIOHttp2ClientStream with `AIOHttp2ClientConnection.request()`.
502 """
503
504 def __init__(self,
505 connection: AIOHttpClientConnection,
506 request: HttpRequest,
507 request_body_generator: AsyncIterator[bytes] = None,
508 loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
509 super().__init__(connection, request, request_body_generator=request_body_generator, loop=loop)
510
511 async def _write_data(self, body, end_stream):
512 future = Future()
513 body_stream = InputStream.wrap(body, allow_none=True)
514
515 def on_write_complete(error_code: int) -> None:
516 if future.cancelled():
517 # the future was cancelled, so we don't need to set the result or exception
518 return
519 if error_code:
520 future.set_exception(awscrt.exceptions.from_code(error_code))
521 else:
522 future.set_result(None)
523
524 _awscrt.http2_client_stream_write_data(self, body_stream, end_stream, on_write_complete)
525 await asyncio.wrap_future(future, loop=self._loop)
526
527 async def _set_request_body_generator(self, body_iterator: AsyncIterator[bytes]):
528 try:
529 async for chunk in body_iterator:
530 await self._write_data(BytesIO(chunk), False)
531 finally:
532 await self._write_data(None, True)