| 1 |
""" |
| 2 |
HTTP |
| 3 |
|
| 4 |
All network operations in `awscrt.http` are asynchronous. |
| 5 |
""" |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
import _awscrt |
| 11 |
from concurrent.futures import Future |
| 12 |
from awscrt import NativeResource |
| 13 |
import awscrt.exceptions |
| 14 |
from awscrt.io import ClientBootstrap, InputStream, TlsConnectionOptions, SocketOptions |
| 15 |
from enum import IntEnum |
| 16 |
from typing import List, Tuple, Dict, Optional, Union, Iterator, Callable, Any |
| 17 |
|
| 18 |
|
| 19 |
class HttpVersion(IntEnum): |
| 20 |
"""HTTP protocol version enumeration""" |
| 21 |
Unknown = 0 |
| 22 |
Http1_0 = 1 |
| 23 |
Http1_1 = 2 |
| 24 |
Http2 = 3 |
| 25 |
|
| 26 |
|
| 27 |
class Http2SettingID(IntEnum): |
| 28 |
"""HTTP/2 Predefined settings(RFC-9113 6.5.2).""" |
| 29 |
HEADER_TABLE_SIZE = 1 |
| 30 |
ENABLE_PUSH = 2 |
| 31 |
MAX_CONCURRENT_STREAMS = 3 |
| 32 |
INITIAL_WINDOW_SIZE = 4 |
| 33 |
MAX_FRAME_SIZE = 5 |
| 34 |
MAX_HEADER_LIST_SIZE = 6 |
| 35 |
|
| 36 |
|
| 37 |
class Http2Setting: |
| 38 |
"""HTTP/2 Setting. |
| 39 |
Settings are very complicated in HTTP/2. |
| 40 |
Each end has its own settings, and the local settings cannot be applied |
| 41 |
until the remote end acknowledges it. |
| 42 |
Each end can change its settings at any time, while the order of the settings |
| 43 |
changed may also result in different behavior. |
| 44 |
|
| 45 |
Each setting has its boundary and initial values defined in RFC-9113 6.5.2: |
| 46 |
Initial values are listed below, while the range can be found in VALID_RANGES: |
| 47 |
HEADER_TABLE_SIZE: 4096 |
| 48 |
ENABLE_PUSH: 1 |
| 49 |
MAX_CONCURRENT_STREAMS: 2^32-1 |
| 50 |
INITIAL_WINDOW_SIZE: 2^16-1 |
| 51 |
MAX_FRAME_SIZE: 2^14 |
| 52 |
MAX_HEADER_LIST_SIZE: 2^32-1 |
| 53 |
|
| 54 |
Args: |
| 55 |
id (Http2SettingID): Setting ID. |
| 56 |
value (int): Setting value. |
| 57 |
""" |
| 58 |
VALID_RANGES: Dict[Http2SettingID, Tuple[int, int]] = { |
| 59 |
Http2SettingID.HEADER_TABLE_SIZE: (0, 2**32 - 1), |
| 60 |
Http2SettingID.ENABLE_PUSH: (0, 1), |
| 61 |
Http2SettingID.MAX_CONCURRENT_STREAMS: (0, 2**32 - 1), |
| 62 |
Http2SettingID.INITIAL_WINDOW_SIZE: (0, 2**31 - 1), |
| 63 |
Http2SettingID.MAX_FRAME_SIZE: (2**14, 2**24 - 1), |
| 64 |
Http2SettingID.MAX_HEADER_LIST_SIZE: (0, 2**32 - 1), |
| 65 |
} |
| 66 |
|
| 67 |
def __init__(self, id: Http2SettingID, value: int) -> None: |
| 68 |
assert isinstance(id, Http2SettingID) |
| 69 |
assert isinstance(value, int) |
| 70 |
self.id = id |
| 71 |
|
| 72 |
|
| 73 |
self._validate_setting_value(id, value) |
| 74 |
self.value = value |
| 75 |
|
| 76 |
def _validate_setting_value(self, id: Http2SettingID, value: int) -> None: |
| 77 |
"""Validate that setting value is within its allowed range according to RFC-9113 6.5.2.""" |
| 78 |
min_value, max_value = self.VALID_RANGES[id] |
| 79 |
if not min_value <= value <= max_value: |
| 80 |
setting_name = id.name |
| 81 |
raise ValueError(f"{setting_name} must be between {min_value} and {max_value}, got {value}") |
| 82 |
|
| 83 |
def __str__(self) -> str: |
| 84 |
return self.__class__.__name__ + f"({self.id.name}={self.value})" |
| 85 |
|
| 86 |
|
| 87 |
class HttpConnectionBase(NativeResource): |
| 88 |
"""Base for HTTP connection classes.""" |
| 89 |
|
| 90 |
__slots__ = ('_shutdown_future', '_version') |
| 91 |
|
| 92 |
def __init__(self) -> None: |
| 93 |
super().__init__() |
| 94 |
self._shutdown_future = Future() |
| 95 |
|
| 96 |
@property |
| 97 |
def shutdown_future(self) -> "concurrent.futures.Future": |
| 98 |
""" |
| 99 |
concurrent.futures.Future: Completes when this connection has finished shutting down. |
| 100 |
Future will contain a result of None, or an exception indicating why shutdown occurred. |
| 101 |
Note that the connection may have been garbage-collected before this future completes. |
| 102 |
""" |
| 103 |
return self._shutdown_future |
| 104 |
|
| 105 |
@property |
| 106 |
def version(self) -> HttpVersion: |
| 107 |
"""HttpVersion: Protocol used by this connection""" |
| 108 |
return self._version |
| 109 |
|
| 110 |
def is_open(self) -> bool: |
| 111 |
""" |
| 112 |
Returns: |
| 113 |
bool: True if this connection is open and usable, False otherwise. |
| 114 |
Check :attr:`shutdown_future` to know when the connection is completely |
| 115 |
finished shutting down. |
| 116 |
""" |
| 117 |
return _awscrt.http_connection_is_open(self._binding) |
| 118 |
|
| 119 |
|
| 120 |
class HttpClientConnectionBase(HttpConnectionBase): |
| 121 |
__slots__ = ('_host_name', '_port') |
| 122 |
|
| 123 |
@staticmethod |
| 124 |
def _generic_new( |
| 125 |
host_name: str, |
| 126 |
port: int, |
| 127 |
bootstrap: Optional[ClientBootstrap] = None, |
| 128 |
socket_options: Optional[SocketOptions] = None, |
| 129 |
tls_connection_options: Optional[TlsConnectionOptions] = None, |
| 130 |
proxy_options: Optional['HttpProxyOptions'] = None, |
| 131 |
expected_version: Optional[HttpVersion] = None, |
| 132 |
initial_settings: Optional[List[Http2Setting]] = None, |
| 133 |
on_remote_settings_changed: Optional[Callable[[List[Http2Setting]], None]] = None, |
| 134 |
asyncio_connection=False, |
| 135 |
manual_window_management: bool = False, |
| 136 |
initial_window_size: Optional[int] = None, |
| 137 |
read_buffer_capacity: Optional[int] = None, |
| 138 |
conn_manual_window_management: bool = False, |
| 139 |
conn_window_size_threshold: Optional[int] = None, |
| 140 |
stream_window_size_threshold: Optional[int] = None) -> "concurrent.futures.Future": |
| 141 |
""" |
| 142 |
Initialize the generic part of the HttpClientConnection class. |
| 143 |
""" |
| 144 |
assert isinstance(bootstrap, ClientBootstrap) or bootstrap is None |
| 145 |
assert isinstance(host_name, str) |
| 146 |
assert isinstance(port, int) |
| 147 |
assert isinstance(tls_connection_options, TlsConnectionOptions) or tls_connection_options is None |
| 148 |
assert isinstance(socket_options, SocketOptions) or socket_options is None |
| 149 |
assert isinstance(proxy_options, HttpProxyOptions) or proxy_options is None |
| 150 |
assert not manual_window_management or initial_window_size is not None |
| 151 |
|
| 152 |
future = Future() |
| 153 |
|
| 154 |
try: |
| 155 |
if not socket_options: |
| 156 |
socket_options = SocketOptions() |
| 157 |
|
| 158 |
if not bootstrap: |
| 159 |
bootstrap = ClientBootstrap.get_or_create_static_default() |
| 160 |
|
| 161 |
connection_core = _HttpClientConnectionCore( |
| 162 |
host_name, |
| 163 |
port, |
| 164 |
bootstrap=bootstrap, |
| 165 |
tls_connection_options=tls_connection_options, |
| 166 |
connect_future=future, |
| 167 |
expected_version=expected_version, |
| 168 |
on_remote_settings_changed=on_remote_settings_changed, |
| 169 |
asyncio_connection=asyncio_connection) |
| 170 |
|
| 171 |
_awscrt.http_client_connection_new( |
| 172 |
bootstrap, |
| 173 |
host_name, |
| 174 |
port, |
| 175 |
socket_options, |
| 176 |
tls_connection_options, |
| 177 |
proxy_options, |
| 178 |
initial_settings, |
| 179 |
on_remote_settings_changed, |
| 180 |
connection_core, |
| 181 |
manual_window_management, |
| 182 |
initial_window_size, |
| 183 |
read_buffer_capacity, |
| 184 |
conn_manual_window_management, |
| 185 |
conn_window_size_threshold, |
| 186 |
stream_window_size_threshold) |
| 187 |
|
| 188 |
except Exception as e: |
| 189 |
future.set_exception(e) |
| 190 |
|
| 191 |
return future |
| 192 |
|
| 193 |
@property |
| 194 |
def host_name(self) -> str: |
| 195 |
"""Remote hostname""" |
| 196 |
return self._host_name |
| 197 |
|
| 198 |
@property |
| 199 |
def port(self) -> int: |
| 200 |
"""Remote port""" |
| 201 |
return self._port |
| 202 |
|
| 203 |
|
| 204 |
class HttpClientConnection(HttpClientConnectionBase): |
| 205 |
""" |
| 206 |
An HTTP client connection. |
| 207 |
|
| 208 |
Use :meth:`HttpClientConnection.new()` to establish a new connection. |
| 209 |
""" |
| 210 |
__slots__ = ('_host_name', '_port') |
| 211 |
|
| 212 |
@classmethod |
| 213 |
def new(cls, |
| 214 |
host_name: str, |
| 215 |
port: int, |
| 216 |
bootstrap: Optional[ClientBootstrap] = None, |
| 217 |
socket_options: Optional[SocketOptions] = None, |
| 218 |
tls_connection_options: Optional[TlsConnectionOptions] = None, |
| 219 |
proxy_options: Optional['HttpProxyOptions'] = None, |
| 220 |
manual_window_management: bool = False, |
| 221 |
initial_window_size: Optional[int] = None, |
| 222 |
read_buffer_capacity: Optional[int] = None) -> "concurrent.futures.Future": |
| 223 |
""" |
| 224 |
Asynchronously establish a new HttpClientConnection. |
| 225 |
|
| 226 |
Args: |
| 227 |
host_name (str): Connect to host. |
| 228 |
|
| 229 |
port (int): Connect to port. |
| 230 |
|
| 231 |
bootstrap (Optional [ClientBootstrap]): Client bootstrap to use when initiating socket connection. |
| 232 |
If None is provided, the default singleton is used. |
| 233 |
|
| 234 |
socket_options (Optional[SocketOptions]): Optional socket options. |
| 235 |
If None is provided, then default options are used. |
| 236 |
|
| 237 |
tls_connection_options (Optional[TlsConnectionOptions]): Optional TLS |
| 238 |
connection options. If None is provided, then the connection will |
| 239 |
be attempted over plain-text. |
| 240 |
|
| 241 |
proxy_options (Optional[HttpProxyOptions]): Optional proxy options. |
| 242 |
If None is provided then a proxy is not used. |
| 243 |
|
| 244 |
manual_window_management (bool): Set to True to manually manage the flow-control window |
| 245 |
of each stream. If False, the connection maintains flow-control windows such that |
| 246 |
no back-pressure is applied and data arrives as fast as possible. If True, the |
| 247 |
flow-control window of each stream shrinks as body data is received (headers, |
| 248 |
padding, and other metadata do not affect the window). `initial_window_size` |
| 249 |
determines the starting size of each stream's window. When a stream's window |
| 250 |
reaches 0, no further data is received until `update_window()` is called. |
| 251 |
Default is False. |
| 252 |
|
| 253 |
initial_window_size (Optional[int]): The starting size of each stream's flow-control |
| 254 |
window. Required if `manual_window_management` is True, ignored otherwise. |
| 255 |
Must be <= 2^31-1 or connection fails. If set to 0 with `manual_window_management` |
| 256 |
True, streams start with zero window. |
| 257 |
Required if manual_window_management is True, ignored otherwise. |
| 258 |
|
| 259 |
read_buffer_capacity (Optional[int]): Capacity in bytes of the HTTP/1.1 connection's |
| 260 |
read buffer. The buffer grows when the flow-control window of the incoming stream |
| 261 |
reaches zero. Ignored if `manual_window_management` is False. A capacity that is |
| 262 |
too small may hinder throughput. A capacity that is too large may waste memory |
| 263 |
without improving throughput. If None or zero, a default value is used. |
| 264 |
|
| 265 |
Returns: |
| 266 |
concurrent.futures.Future: A Future which completes when connection succeeds or fails. |
| 267 |
If successful, the Future will contain a new :class:`HttpClientConnection`. |
| 268 |
Otherwise, it will contain an exception. |
| 269 |
""" |
| 270 |
return cls._generic_new( |
| 271 |
host_name, |
| 272 |
port, |
| 273 |
bootstrap, |
| 274 |
socket_options, |
| 275 |
tls_connection_options, |
| 276 |
proxy_options, |
| 277 |
manual_window_management=manual_window_management, |
| 278 |
initial_window_size=initial_window_size, |
| 279 |
read_buffer_capacity=read_buffer_capacity) |
| 280 |
|
| 281 |
def request(self, |
| 282 |
request: 'HttpRequest', |
| 283 |
on_response: Optional[Callable[..., None]] = None, |
| 284 |
on_body: Optional[Callable[..., None]] = None) -> 'HttpClientStream': |
| 285 |
"""Create :class:`HttpClientStream` to carry out the request/response exchange. |
| 286 |
|
| 287 |
NOTE: The HTTP stream sends no data until :meth:`HttpClientStream.activate()` |
| 288 |
is called. Call activate() when you're ready for callbacks and events to fire. |
| 289 |
|
| 290 |
Args: |
| 291 |
request (HttpRequest): Definition for outgoing request. |
| 292 |
|
| 293 |
on_response: Optional callback invoked once main response headers are received. |
| 294 |
The function should take the following arguments and return nothing: |
| 295 |
|
| 296 |
* `http_stream` (:class:`HttpClientStream`): HTTP stream carrying |
| 297 |
out this request/response exchange. |
| 298 |
|
| 299 |
* `status_code` (int): Response status code. |
| 300 |
|
| 301 |
* `headers` (List[Tuple[str, str]]): Response headers as a |
| 302 |
list of (name,value) pairs. |
| 303 |
|
| 304 |
* `**kwargs` (dict): Forward compatibility kwargs. |
| 305 |
|
| 306 |
An exception raise by this function will cause the HTTP stream to end in error. |
| 307 |
This callback is always invoked on the connection's event-loop thread. |
| 308 |
|
| 309 |
on_body: Optional callback invoked 0+ times as response body data is received. |
| 310 |
The function should take the following arguments and return nothing: |
| 311 |
|
| 312 |
* `http_stream` (:class:`HttpClientStream`): HTTP stream carrying |
| 313 |
out this request/response exchange. |
| 314 |
|
| 315 |
* `chunk` (buffer): Response body data (not necessarily |
| 316 |
a whole "chunk" of chunked encoding). |
| 317 |
|
| 318 |
* `**kwargs` (dict): Forward-compatibility kwargs. |
| 319 |
|
| 320 |
An exception raise by this function will cause the HTTP stream to end in error. |
| 321 |
This callback is always invoked on the connection's event-loop thread. |
| 322 |
|
| 323 |
Returns: |
| 324 |
HttpClientStream: |
| 325 |
""" |
| 326 |
return HttpClientStream(self, request, on_response, on_body) |
| 327 |
|
| 328 |
def close(self) -> "concurrent.futures.Future": |
| 329 |
"""Close the connection. |
| 330 |
|
| 331 |
Shutdown is asynchronous. This call has no effect if the connection is already |
| 332 |
closing. |
| 333 |
|
| 334 |
Returns: |
| 335 |
concurrent.futures.Future: This connection's :attr:`shutdown_future`, |
| 336 |
which completes when shutdown has finished. |
| 337 |
""" |
| 338 |
_awscrt.http_connection_close(self._binding) |
| 339 |
return self.shutdown_future |
| 340 |
|
| 341 |
|
| 342 |
class Http2ClientConnection(HttpClientConnectionBase): |
| 343 |
|
| 344 |
@classmethod |
| 345 |
def new(cls, |
| 346 |
host_name: str, |
| 347 |
port: int, |
| 348 |
bootstrap: Optional[ClientBootstrap] = None, |
| 349 |
socket_options: Optional[SocketOptions] = None, |
| 350 |
tls_connection_options: Optional[TlsConnectionOptions] = None, |
| 351 |
proxy_options: Optional['HttpProxyOptions'] = None, |
| 352 |
initial_settings: Optional[List[Http2Setting]] = None, |
| 353 |
on_remote_settings_changed: Optional[Callable[[List[Http2Setting]], |
| 354 |
None]] = None, |
| 355 |
manual_window_management: bool = False, |
| 356 |
initial_window_size: Optional[int] = None, |
| 357 |
conn_manual_window_management: bool = False, |
| 358 |
conn_window_size_threshold: Optional[int] = None, |
| 359 |
stream_window_size_threshold: Optional[int] = None) -> "concurrent.futures.Future": |
| 360 |
""" |
| 361 |
Asynchronously establish an HTTP/2 client connection. |
| 362 |
Notes: to set up the connection, the server must support HTTP/2 and TlsConnectionOptions |
| 363 |
|
| 364 |
This class extends HttpClientConnection with HTTP/2 specific functionality. |
| 365 |
|
| 366 |
HTTP/2 specific args: |
| 367 |
initial_settings (List[Http2Setting]): The initial settings to change for the connection. |
| 368 |
|
| 369 |
on_remote_settings_changed: Optional callback invoked once the remote peer changes its settings. |
| 370 |
And the settings are acknowledged by the local connection. |
| 371 |
The function should take the following arguments and return nothing: |
| 372 |
|
| 373 |
* `settings` (List[Http2Setting]): List of settings that were changed. |
| 374 |
|
| 375 |
manual_window_management (bool): If True, enables manual flow control window management. |
| 376 |
Default is False. |
| 377 |
|
| 378 |
initial_window_size (Optional[int]): Initial window size for flow control. |
| 379 |
Required if manual_window_management is True, ignored otherwise. |
| 380 |
|
| 381 |
conn_manual_window_management (bool): If True, enables manual connection-level flow control |
| 382 |
for the entire HTTP/2 connection. When enabled, the connection's flow-control window |
| 383 |
shrinks as body data is received across all streams. The initial connection window is |
| 384 |
65,535 bytes. When the window reaches 0, all streams stop receiving data until |
| 385 |
`update_window()` is called to increment the connection's window. |
| 386 |
Note: Padding in DATA frames counts against the window, but window updates for padding |
| 387 |
are sent automatically even in manual mode. Default is False. |
| 388 |
|
| 389 |
conn_window_size_threshold (Optional[int]): Threshold for sending connection-level WINDOW_UPDATE |
| 390 |
frames. Ignored if `conn_manual_window_management` is False. When the connection's window |
| 391 |
is above this threshold, WINDOW_UPDATE frames are batched. When it drops below, the update |
| 392 |
is sent. Default is 32,767 (half of the initial 65,535 window). |
| 393 |
|
| 394 |
stream_window_size_threshold (Optional[int]): Threshold for sending stream-level WINDOW_UPDATE |
| 395 |
frames. Ignored if `manual_window_management` is False. When a stream's window is above |
| 396 |
this threshold, WINDOW_UPDATE frames are batched. When it drops below, the update is sent. |
| 397 |
Default is half of `initial_window_size`. |
| 398 |
""" |
| 399 |
return cls._generic_new( |
| 400 |
host_name, |
| 401 |
port, |
| 402 |
bootstrap, |
| 403 |
socket_options, |
| 404 |
tls_connection_options, |
| 405 |
proxy_options, |
| 406 |
HttpVersion.Http2, |
| 407 |
initial_settings, |
| 408 |
on_remote_settings_changed, |
| 409 |
manual_window_management=manual_window_management, |
| 410 |
initial_window_size=initial_window_size, |
| 411 |
conn_manual_window_management=conn_manual_window_management, |
| 412 |
conn_window_size_threshold=conn_window_size_threshold, |
| 413 |
stream_window_size_threshold=stream_window_size_threshold) |
| 414 |
|
| 415 |
def request(self, |
| 416 |
request: 'HttpRequest', |
| 417 |
on_response: Optional[Callable[..., None]] = None, |
| 418 |
on_body: Optional[Callable[..., None]] = None, |
| 419 |
manual_write: bool = False) -> 'Http2ClientStream': |
| 420 |
"""Create `Http2ClientStream` to carry out the request/response exchange. |
| 421 |
|
| 422 |
NOTE: The HTTP stream sends no data until `Http2ClientStream.activate()` |
| 423 |
is called. Call activate() when you're ready for callbacks and events to fire. |
| 424 |
|
| 425 |
Args: |
| 426 |
request (HttpRequest): Definition for outgoing request. |
| 427 |
|
| 428 |
on_response: Optional callback invoked once main response headers are received. |
| 429 |
The function should take the following arguments and return nothing: |
| 430 |
|
| 431 |
* `http_stream` (`Http2ClientStream`): HTTP/2 stream carrying |
| 432 |
out this request/response exchange. |
| 433 |
|
| 434 |
* `status_code` (int): Response status code. |
| 435 |
|
| 436 |
* `headers` (List[Tuple[str, str]]): Response headers as a |
| 437 |
list of (name,value) pairs. |
| 438 |
|
| 439 |
* `**kwargs` (dict): Forward compatibility kwargs. |
| 440 |
|
| 441 |
on_body: Optional callback invoked 0+ times as response body data is received. |
| 442 |
The function should take the following arguments and return nothing: |
| 443 |
|
| 444 |
* `http_stream` (`Http2ClientStream`): HTTP/2 stream carrying |
| 445 |
out this request/response exchange. |
| 446 |
|
| 447 |
* `chunk` (buffer): Response body data (not necessarily |
| 448 |
a whole "chunk" of chunked encoding). |
| 449 |
|
| 450 |
* `**kwargs` (dict): Forward-compatibility kwargs. |
| 451 |
|
| 452 |
manual_write (bool): If True, enables manual data writing on the stream. |
| 453 |
This allows calling `write_data()` to stream the request body in chunks. |
| 454 |
Note: In the asyncio version, this is replaced by the async_body parameter. |
| 455 |
|
| 456 |
Returns: |
| 457 |
Http2ClientStream: Stream for the HTTP/2 request/response exchange. |
| 458 |
""" |
| 459 |
return Http2ClientStream(self, request, on_response, on_body, manual_write) |
| 460 |
|
| 461 |
def close(self) -> "concurrent.futures.Future": |
| 462 |
"""Close the connection. |
| 463 |
|
| 464 |
Shutdown is asynchronous. This call has no effect if the connection is already |
| 465 |
closing. |
| 466 |
|
| 467 |
Returns: |
| 468 |
concurrent.futures.Future: This connection's :attr:`shutdown_future`, |
| 469 |
which completes when shutdown has finished. |
| 470 |
""" |
| 471 |
_awscrt.http_connection_close(self._binding) |
| 472 |
return self.shutdown_future |
| 473 |
|
| 474 |
def update_window(self, increment_size: int) -> None: |
| 475 |
""" |
| 476 |
Update the connection's flow control window. |
| 477 |
|
| 478 |
Args: |
| 479 |
increment_size (int): Number of bytes to increment the window by. |
| 480 |
""" |
| 481 |
_awscrt.http2_connection_update_window(self._binding, increment_size) |
| 482 |
|
| 483 |
|
| 484 |
class HttpStreamBase(NativeResource): |
| 485 |
"""Base for HTTP stream classes. |
| 486 |
|
| 487 |
Attributes: |
| 488 |
connection: The HTTP connection this stream belongs to. |
| 489 |
completion_future: Future that completes when the operation finishes. |
| 490 |
""" |
| 491 |
__slots__ = ('_connection', '_completion_future', '_on_body_cb') |
| 492 |
|
| 493 |
def __init__(self, connection, on_body: Optional[Callable[..., None]] = None) -> None: |
| 494 |
super().__init__() |
| 495 |
self._connection = connection |
| 496 |
self._completion_future = Future() |
| 497 |
self._on_body_cb: Optional[Callable[..., None]] = on_body |
| 498 |
|
| 499 |
@property |
| 500 |
def connection(self) -> HttpConnectionBase: |
| 501 |
return self._connection |
| 502 |
|
| 503 |
@property |
| 504 |
def completion_future(self) -> "concurrent.futures.Future": |
| 505 |
return self._completion_future |
| 506 |
|
| 507 |
def _on_body(self, chunk: bytes) -> None: |
| 508 |
if self._on_body_cb: |
| 509 |
self._on_body_cb(http_stream=self, chunk=chunk) |
| 510 |
|
| 511 |
|
| 512 |
class HttpClientStreamBase(HttpStreamBase): |
| 513 |
"""Base for HTTP client stream classes. |
| 514 |
|
| 515 |
Attributes: |
| 516 |
connection: This stream's connection. |
| 517 |
|
| 518 |
completion_future: Future that completes when |
| 519 |
the request/response exchange is finished. |
| 520 |
""" |
| 521 |
|
| 522 |
__slots__ = ('_response_status_code', '_on_response_cb', '_on_body_cb', '_request', '_version') |
| 523 |
|
| 524 |
def _init_common(self, |
| 525 |
connection: HttpClientConnectionBase, |
| 526 |
request: 'HttpRequest', |
| 527 |
on_response: Optional[Callable[..., None]] = None, |
| 528 |
on_body: Optional[Callable[..., None]] = None, |
| 529 |
http2_manual_write: bool = False) -> None: |
| 530 |
assert isinstance(connection, HttpClientConnectionBase) |
| 531 |
assert isinstance(request, HttpRequest) |
| 532 |
assert callable(on_response) or on_response is None |
| 533 |
assert callable(on_body) or on_body is None |
| 534 |
|
| 535 |
super().__init__(connection, on_body) |
| 536 |
|
| 537 |
self._on_response_cb: Optional[Callable[..., None]] = on_response |
| 538 |
self._response_status_code: Optional[int] = None |
| 539 |
|
| 540 |
|
| 541 |
self._request = request |
| 542 |
self._version = connection.version |
| 543 |
self._binding = _awscrt.http_client_stream_new(self, connection, request, http2_manual_write) |
| 544 |
|
| 545 |
@property |
| 546 |
def version(self) -> HttpVersion: |
| 547 |
"""HttpVersion: Protocol used by this stream""" |
| 548 |
return self._version |
| 549 |
|
| 550 |
@property |
| 551 |
def response_status_code(self) -> Optional[int]: |
| 552 |
"""int: The response status code. |
| 553 |
|
| 554 |
This is None until a response arrives.""" |
| 555 |
return self._response_status_code |
| 556 |
|
| 557 |
def _on_response(self, status_code: int, name_value_pairs: List[Tuple[str, str]]) -> None: |
| 558 |
self._response_status_code = status_code |
| 559 |
|
| 560 |
if self._on_response_cb: |
| 561 |
self._on_response_cb(http_stream=self, status_code=status_code, headers=name_value_pairs) |
| 562 |
|
| 563 |
def _on_complete(self, error_code: int) -> None: |
| 564 |
|
| 565 |
self._request = None |
| 566 |
|
| 567 |
if error_code == 0: |
| 568 |
self._completion_future.set_result(self._response_status_code) |
| 569 |
else: |
| 570 |
self._completion_future.set_exception(awscrt.exceptions.from_code(error_code)) |
| 571 |
|
| 572 |
def _on_h2_remote_end_stream(self) -> None: |
| 573 |
"""Called when remote peer sends END_STREAM (HTTP/2 only). |
| 574 |
|
| 575 |
This callback is only invoked for HTTP/2 connections. HTTP/1.x streams |
| 576 |
will never receive this callback. Base implementation does nothing. |
| 577 |
""" |
| 578 |
pass |
| 579 |
|
| 580 |
def update_window(self, increment_size: int) -> None: |
| 581 |
""" |
| 582 |
Update the stream's flow control window. |
| 583 |
|
| 584 |
Args: |
| 585 |
increment_size (int): Number of bytes to increment the window by. |
| 586 |
""" |
| 587 |
_awscrt.http_stream_update_window(self, increment_size) |
| 588 |
|
| 589 |
|
| 590 |
class HttpClientStream(HttpClientStreamBase): |
| 591 |
"""HTTP stream that sends a request and receives a response. |
| 592 |
|
| 593 |
Create an HttpClientStream with :meth:`HttpClientConnection.request()`. |
| 594 |
|
| 595 |
NOTE: The HTTP stream sends no data until :meth:`HttpClientStream.activate()` |
| 596 |
is called. Call activate() when you're ready for callbacks and events to fire. |
| 597 |
|
| 598 |
Attributes: |
| 599 |
connection (HttpClientConnection): This stream's connection. |
| 600 |
|
| 601 |
completion_future (concurrent.futures.Future): Future that will contain |
| 602 |
the response status code (int) when the request/response exchange |
| 603 |
completes. If the exchange fails to complete, the Future will |
| 604 |
contain an exception indicating why it failed. |
| 605 |
""" |
| 606 |
|
| 607 |
def __init__(self, |
| 608 |
connection: HttpClientConnection, |
| 609 |
request: 'HttpRequest', |
| 610 |
on_response: Optional[Callable[..., None]] = None, |
| 611 |
on_body: Optional[Callable[..., None]] = None) -> None: |
| 612 |
self._init_common(connection, request, on_response, on_body) |
| 613 |
|
| 614 |
def activate(self) -> None: |
| 615 |
"""Begin sending the request. |
| 616 |
|
| 617 |
The HTTP stream does nothing until this is called. Call activate() when you |
| 618 |
are ready for its callbacks and events to fire. |
| 619 |
""" |
| 620 |
_awscrt.http_client_stream_activate(self) |
| 621 |
|
| 622 |
|
| 623 |
class Http2ClientStream(HttpClientStreamBase): |
| 624 |
__slots__ = ('_remote_end_stream_future',) |
| 625 |
|
| 626 |
def __init__(self, |
| 627 |
connection: HttpClientConnection, |
| 628 |
request: 'HttpRequest', |
| 629 |
on_response: Optional[Callable[..., None]] = None, |
| 630 |
on_body: Optional[Callable[..., None]] = None, |
| 631 |
manual_write: bool = False) -> None: |
| 632 |
self._remote_end_stream_future = Future() |
| 633 |
self._init_common(connection, request, on_response, on_body, manual_write) |
| 634 |
|
| 635 |
@property |
| 636 |
def remote_end_stream_future(self) -> "concurrent.futures.Future": |
| 637 |
""" |
| 638 |
concurrent.futures.Future: Future that completes when the remote peer has finished |
| 639 |
sending (HTTP/2 only). This occurs when the server sends an END_STREAM flag. |
| 640 |
|
| 641 |
The future will contain a result of None on success, or an exception if the stream |
| 642 |
encounters an error before END_STREAM is received (e.g., RST_STREAM). |
| 643 |
|
| 644 |
This is different from `completion_future` which completes when both the |
| 645 |
client and server have finished (bidirectional stream closure). |
| 646 |
|
| 647 |
Note: This future only applies to HTTP/2 connections. It will complete when the |
| 648 |
server sends END_STREAM, which may occur before the client finishes sending. |
| 649 |
In case of stream completed without END_STREAM received, this future will complete |
| 650 |
with exception. |
| 651 |
""" |
| 652 |
return self._remote_end_stream_future |
| 653 |
|
| 654 |
def _on_h2_remote_end_stream(self) -> None: |
| 655 |
"""Internal callback when remote peer sends END_STREAM (HTTP/2 only).""" |
| 656 |
if not self._remote_end_stream_future.done(): |
| 657 |
self._remote_end_stream_future.set_result(None) |
| 658 |
|
| 659 |
def _on_complete(self, error_code: int) -> None: |
| 660 |
|
| 661 |
self._request = None |
| 662 |
|
| 663 |
|
| 664 |
if not self._remote_end_stream_future.done(): |
| 665 |
|
| 666 |
|
| 667 |
self._remote_end_stream_future.set_exception( |
| 668 |
RuntimeError("Stream completed without receiving remote END_STREAM")) |
| 669 |
|
| 670 |
if error_code == 0: |
| 671 |
self._completion_future.set_result(self._response_status_code) |
| 672 |
else: |
| 673 |
self._completion_future.set_exception(awscrt.exceptions.from_code(error_code)) |
| 674 |
|
| 675 |
def activate(self) -> None: |
| 676 |
"""Begin sending the request. |
| 677 |
|
| 678 |
The HTTP stream does nothing until this is called. Call activate() when you |
| 679 |
are ready for its callbacks and events to fire. |
| 680 |
""" |
| 681 |
_awscrt.http_client_stream_activate(self) |
| 682 |
|
| 683 |
def write_data(self, |
| 684 |
data_stream: Union[InputStream, Any], |
| 685 |
end_stream: bool = False) -> "concurrent.futures.Future": |
| 686 |
"""Write a chunk of data to the request body stream. |
| 687 |
|
| 688 |
This method is only available when the stream was created with |
| 689 |
manual_write=True. This allows incremental writing of request data. |
| 690 |
|
| 691 |
Note: In the asyncio version, this is replaced by the request_body_generator parameter |
| 692 |
which accepts an async generator. |
| 693 |
|
| 694 |
Args: |
| 695 |
data_stream (Union[InputStream, Any]): Data to write. If not an InputStream, |
| 696 |
it will be wrapped in one. Can be None to send an empty chunk. |
| 697 |
|
| 698 |
end_stream (bool): True to indicate this is the last chunk and no more data |
| 699 |
will be sent. False if more chunks will follow. |
| 700 |
|
| 701 |
Returns: |
| 702 |
concurrent.futures.Future: Future that completes when the write operation |
| 703 |
is done. The future will contain None on success, or an exception on failure. |
| 704 |
""" |
| 705 |
future = Future() |
| 706 |
body_stream = InputStream.wrap(data_stream, allow_none=True) |
| 707 |
|
| 708 |
def on_write_complete(error_code: int) -> None: |
| 709 |
if future.cancelled(): |
| 710 |
|
| 711 |
return |
| 712 |
if error_code: |
| 713 |
future.set_exception(awscrt.exceptions.from_code(error_code)) |
| 714 |
else: |
| 715 |
future.set_result(None) |
| 716 |
|
| 717 |
_awscrt.http2_client_stream_write_data(self, body_stream, end_stream, on_write_complete) |
| 718 |
return future |
| 719 |
|
| 720 |
|
| 721 |
class HttpMessageBase(NativeResource): |
| 722 |
""" |
| 723 |
Base for HttpRequest and HttpResponse classes. |
| 724 |
""" |
| 725 |
__slots__ = ('_headers', '_body_stream') |
| 726 |
|
| 727 |
def __init__(self, binding: Any, headers: 'HttpHeaders', |
| 728 |
body_stream: Optional[Union[InputStream, Any]] = None) -> None: |
| 729 |
assert isinstance(headers, HttpHeaders) |
| 730 |
|
| 731 |
super().__init__() |
| 732 |
self._binding = binding |
| 733 |
self._headers = headers |
| 734 |
self._body_stream: Optional[InputStream] = None |
| 735 |
|
| 736 |
if body_stream: |
| 737 |
self.body_stream = body_stream |
| 738 |
|
| 739 |
@property |
| 740 |
def headers(self) -> 'HttpHeaders': |
| 741 |
"""HttpHeaders: Headers to send.""" |
| 742 |
return self._headers |
| 743 |
|
| 744 |
@property |
| 745 |
def body_stream(self) -> Optional[InputStream]: |
| 746 |
return self._body_stream |
| 747 |
|
| 748 |
@body_stream.setter |
| 749 |
def body_stream(self, stream: Union[InputStream, Any]) -> None: |
| 750 |
self._body_stream = InputStream.wrap(stream) |
| 751 |
_awscrt.http_message_set_body_stream(self._binding, self._body_stream) |
| 752 |
|
| 753 |
|
| 754 |
class HttpRequest(HttpMessageBase): |
| 755 |
""" |
| 756 |
Definition for an outgoing HTTP request. |
| 757 |
|
| 758 |
The request may be transformed (ex: signing the request) before its data is eventually sent. |
| 759 |
|
| 760 |
Args: |
| 761 |
method (str): HTTP request method (verb). Default value is "GET". |
| 762 |
path (str): HTTP path-and-query value. Default value is "/". |
| 763 |
headers (Optional[HttpHeaders]): Optional headers. If None specified, |
| 764 |
an empty :class:`HttpHeaders` is created. |
| 765 |
body_stream(Optional[Union[InputStream, io.IOBase]]): Optional body as binary stream. |
| 766 |
""" |
| 767 |
|
| 768 |
__slots__ = () |
| 769 |
|
| 770 |
def __init__(self, |
| 771 |
method: str = 'GET', |
| 772 |
path: str = '/', |
| 773 |
headers: Optional['HttpHeaders'] = None, |
| 774 |
body_stream: Optional[Union[InputStream, Any]] = None) -> None: |
| 775 |
assert isinstance(headers, HttpHeaders) or headers is None |
| 776 |
|
| 777 |
if headers is None: |
| 778 |
headers = HttpHeaders() |
| 779 |
|
| 780 |
binding = _awscrt.http_message_new_request(headers) |
| 781 |
super().__init__(binding, headers, body_stream) |
| 782 |
self.method = method |
| 783 |
self.path = path |
| 784 |
|
| 785 |
@classmethod |
| 786 |
def _from_bindings(cls, request_binding: Any, headers_binding: Any) -> 'HttpRequest': |
| 787 |
"""Construct HttpRequest and its HttpHeaders from pre-existing native objects""" |
| 788 |
|
| 789 |
|
| 790 |
|
| 791 |
request = cls.__new__(cls) |
| 792 |
headers = HttpHeaders._from_binding(headers_binding) |
| 793 |
super(cls, request).__init__(request_binding, headers) |
| 794 |
return request |
| 795 |
|
| 796 |
@property |
| 797 |
def method(self) -> str: |
| 798 |
"""str: HTTP request method (verb).""" |
| 799 |
return _awscrt.http_message_get_request_method(self._binding) |
| 800 |
|
| 801 |
@method.setter |
| 802 |
def method(self, method: str) -> None: |
| 803 |
_awscrt.http_message_set_request_method(self._binding, method) |
| 804 |
|
| 805 |
@property |
| 806 |
def path(self) -> str: |
| 807 |
"""str: HTTP path-and-query value.""" |
| 808 |
return _awscrt.http_message_get_request_path(self._binding) |
| 809 |
|
| 810 |
@path.setter |
| 811 |
def path(self, path: str) -> None: |
| 812 |
return _awscrt.http_message_set_request_path(self._binding, path) |
| 813 |
|
| 814 |
|
| 815 |
class HttpHeaders(NativeResource): |
| 816 |
""" |
| 817 |
Collection of HTTP headers. |
| 818 |
|
| 819 |
A given header name may have multiple values. |
| 820 |
Header names are always treated in a case-insensitive manner. |
| 821 |
HttpHeaders can be iterated over as (name,value) pairs. |
| 822 |
|
| 823 |
Args: |
| 824 |
name_value_pairs (Optional[List[Tuple[str, str]]]): Construct from a |
| 825 |
collection of (name,value) pairs. |
| 826 |
""" |
| 827 |
|
| 828 |
__slots__ = () |
| 829 |
|
| 830 |
def __init__(self, name_value_pairs: Optional[List[Tuple[str, str]]] = None) -> None: |
| 831 |
super().__init__() |
| 832 |
self._binding = _awscrt.http_headers_new() |
| 833 |
if name_value_pairs: |
| 834 |
self.add_pairs(name_value_pairs) |
| 835 |
|
| 836 |
@classmethod |
| 837 |
def _from_binding(cls, binding: Any) -> 'HttpHeaders': |
| 838 |
"""Construct from a pre-existing native object""" |
| 839 |
headers = cls.__new__(cls) |
| 840 |
super(cls, headers).__init__() |
| 841 |
headers._binding = binding |
| 842 |
return headers |
| 843 |
|
| 844 |
def add(self, name: str, value: str) -> None: |
| 845 |
""" |
| 846 |
Add a name-value pair. |
| 847 |
|
| 848 |
Args: |
| 849 |
name (str): Name. |
| 850 |
value (str): Value. |
| 851 |
""" |
| 852 |
assert isinstance(name, str) |
| 853 |
assert isinstance(value, str) |
| 854 |
_awscrt.http_headers_add(self._binding, name, value) |
| 855 |
|
| 856 |
def add_pairs(self, name_value_pairs: List[Tuple[str, str]]) -> None: |
| 857 |
""" |
| 858 |
Add list of (name,value) pairs. |
| 859 |
|
| 860 |
Args: |
| 861 |
name_value_pairs (List[Tuple[str, str]]): List of (name,value) pairs. |
| 862 |
""" |
| 863 |
_awscrt.http_headers_add_pairs(self._binding, name_value_pairs) |
| 864 |
|
| 865 |
def set(self, name: str, value: str) -> None: |
| 866 |
""" |
| 867 |
Set a name-value pair, any existing values for the name are removed. |
| 868 |
|
| 869 |
Args: |
| 870 |
name (str): Name. |
| 871 |
value (str): Value. |
| 872 |
""" |
| 873 |
assert isinstance(name, str) |
| 874 |
assert isinstance(value, str) |
| 875 |
_awscrt.http_headers_set(self._binding, name, value) |
| 876 |
|
| 877 |
def get_values(self, name: str) -> Iterator[str]: |
| 878 |
""" |
| 879 |
Return an iterator over the values for this name. |
| 880 |
|
| 881 |
Args: |
| 882 |
name (str): Name. |
| 883 |
|
| 884 |
Returns: |
| 885 |
Iterator[str]: Iterator over values for this header name |
| 886 |
""" |
| 887 |
assert isinstance(name, str) |
| 888 |
name = name.lower() |
| 889 |
for i in range(_awscrt.http_headers_count(self._binding)): |
| 890 |
name_i, value_i = _awscrt.http_headers_get_index(self._binding, i) |
| 891 |
if name_i.lower() == name: |
| 892 |
yield value_i |
| 893 |
|
| 894 |
def get(self, name: str, default: Optional[str] = None) -> Optional[str]: |
| 895 |
""" |
| 896 |
Get the first value for this name, ignoring any additional values. |
| 897 |
Returns `default` if no values exist. |
| 898 |
|
| 899 |
Args: |
| 900 |
name (str): Name. |
| 901 |
default (Optional[str]): If `name` not found, this value is returned. |
| 902 |
Defaults to None. |
| 903 |
Returns: |
| 904 |
Optional[str]: Header value or default |
| 905 |
""" |
| 906 |
assert isinstance(name, str) |
| 907 |
return _awscrt.http_headers_get(self._binding, name, default) |
| 908 |
|
| 909 |
def remove(self, name: str) -> None: |
| 910 |
""" |
| 911 |
Remove all values for this name. |
| 912 |
Raises a KeyError if name not found. |
| 913 |
|
| 914 |
Args: |
| 915 |
name (str): Header name. |
| 916 |
""" |
| 917 |
assert isinstance(name, str) |
| 918 |
_awscrt.http_headers_remove(self._binding, name) |
| 919 |
|
| 920 |
def remove_value(self, name: str, value: str) -> None: |
| 921 |
""" |
| 922 |
Remove a specific value for this name. |
| 923 |
Raises a ValueError if value not found. |
| 924 |
|
| 925 |
Args: |
| 926 |
name (str): Name. |
| 927 |
value (str): Value. |
| 928 |
""" |
| 929 |
assert isinstance(name, str) |
| 930 |
assert isinstance(value, str) |
| 931 |
_awscrt.http_headers_remove_value(self._binding, name, value) |
| 932 |
|
| 933 |
def clear(self) -> None: |
| 934 |
""" |
| 935 |
Clear all headers. |
| 936 |
""" |
| 937 |
_awscrt.http_headers_clear(self._binding) |
| 938 |
|
| 939 |
def __iter__(self) -> Iterator[Tuple[str, str]]: |
| 940 |
""" |
| 941 |
Iterate over all (name,value) pairs. |
| 942 |
""" |
| 943 |
for i in range(_awscrt.http_headers_count(self._binding)): |
| 944 |
yield _awscrt.http_headers_get_index(self._binding, i) |
| 945 |
|
| 946 |
def __str__(self) -> str: |
| 947 |
return self.__class__.__name__ + "(" + str([pair for pair in self]) + ")" |
| 948 |
|
| 949 |
|
| 950 |
class HttpProxyConnectionType(IntEnum): |
| 951 |
"""Proxy connection type enumeration""" |
| 952 |
Legacy = 0 |
| 953 |
""" |
| 954 |
Use the old connection establishment logic that would use: |
| 955 |
|
| 956 |
1. Forwarding if not using TLS |
| 957 |
2. Tunneling if using TLS |
| 958 |
""" |
| 959 |
|
| 960 |
Forwarding = 1 |
| 961 |
""" |
| 962 |
Establish a request forwarding connection to the proxy. |
| 963 |
|
| 964 |
In this case, TLS is not a valid option. |
| 965 |
""" |
| 966 |
|
| 967 |
Tunneling = 2 |
| 968 |
"""Establish a tunneling connection through the proxy to the ultimate endpoint.""" |
| 969 |
|
| 970 |
|
| 971 |
class HttpProxyAuthenticationType(IntEnum): |
| 972 |
"""Proxy authentication type enumeration.""" |
| 973 |
Nothing = 0 |
| 974 |
"""No authentication""" |
| 975 |
|
| 976 |
Basic = 1 |
| 977 |
"""Username and password""" |
| 978 |
|
| 979 |
|
| 980 |
class HttpProxyOptions: |
| 981 |
""" |
| 982 |
Proxy options for HTTP clients. |
| 983 |
|
| 984 |
Args: |
| 985 |
host_name (str): Name of the proxy server to connect through. |
| 986 |
|
| 987 |
port (int): Port number of the proxy server to connect through. |
| 988 |
|
| 989 |
tls_connection_options (Optional[TlsConnectionOptions]): Optional |
| 990 |
`TlsConnectionOptions` for the Local to Proxy connection. |
| 991 |
Must be distinct from the `TlsConnectionOptions` |
| 992 |
provided to the HTTP connection. |
| 993 |
|
| 994 |
auth_type (HttpProxyAuthenticationType): Type of proxy authentication to use. |
| 995 |
Default is :const:`HttpProxyAuthenticationType.Nothing`. |
| 996 |
|
| 997 |
auth_username (Optional[str]): Username to use when `auth_type` is |
| 998 |
:const:`HttpProxyAuthenticationType.Basic`. |
| 999 |
|
| 1000 |
auth_password (Optional[str]): Username to use when `auth_type` is |
| 1001 |
:const:`HttpProxyAuthenticationType.Basic`. |
| 1002 |
|
| 1003 |
connection_type (Optional[HttpProxyConnectionType): Type of proxy connection to make. |
| 1004 |
Default is :const:`HttpProxyConnectionType.Legacy`. |
| 1005 |
|
| 1006 |
|
| 1007 |
Attributes: |
| 1008 |
host_name (str): Name of the proxy server to connect through. |
| 1009 |
|
| 1010 |
port (int): Port number of the proxy server to connect through. |
| 1011 |
|
| 1012 |
tls_connection_options (Optional[TlsConnectionOptions]): Optional |
| 1013 |
`TlsConnectionOptions` for the Local to Proxy connection. |
| 1014 |
Must be distinct from the `TlsConnectionOptions` |
| 1015 |
provided to the HTTP connection. |
| 1016 |
|
| 1017 |
auth_type (HttpProxyAuthenticationType): Type of proxy authentication to use. |
| 1018 |
|
| 1019 |
auth_username (Optional[str]): Username to use when `auth_type` is |
| 1020 |
:const:`HttpProxyAuthenticationType.Basic`. |
| 1021 |
|
| 1022 |
auth_password (Optional[str]): Username to use when `auth_type` is |
| 1023 |
:const:`HttpProxyAuthenticationType.Basic`. |
| 1024 |
|
| 1025 |
connection_type (HttpProxyConnectionType): Type of proxy connection to make. |
| 1026 |
|
| 1027 |
""" |
| 1028 |
|
| 1029 |
def __init__(self, |
| 1030 |
host_name: str, |
| 1031 |
port: int, |
| 1032 |
tls_connection_options: Optional[TlsConnectionOptions] = None, |
| 1033 |
auth_type: HttpProxyAuthenticationType = HttpProxyAuthenticationType.Nothing, |
| 1034 |
auth_username: Optional[str] = None, |
| 1035 |
auth_password: Optional[str] = None, |
| 1036 |
connection_type: HttpProxyConnectionType = HttpProxyConnectionType.Legacy) -> None: |
| 1037 |
self.host_name = host_name |
| 1038 |
self.port = port |
| 1039 |
self.tls_connection_options = tls_connection_options |
| 1040 |
self.auth_type = auth_type |
| 1041 |
self.auth_username = auth_username |
| 1042 |
self.auth_password = auth_password |
| 1043 |
self.connection_type = connection_type |
| 1044 |
|
| 1045 |
|
| 1046 |
class _HttpClientConnectionCore: |
| 1047 |
''' |
| 1048 |
Private class to keep all the related Python object alive until C land clean up for HttpClientConnection |
| 1049 |
''' |
| 1050 |
|
| 1051 |
def __init__( |
| 1052 |
self, |
| 1053 |
host_name: str, |
| 1054 |
port: int, |
| 1055 |
bootstrap: Optional[ClientBootstrap] = None, |
| 1056 |
tls_connection_options: Optional[TlsConnectionOptions] = None, |
| 1057 |
connect_future: Optional[Future] = None, |
| 1058 |
expected_version: Optional[HttpVersion] = None, |
| 1059 |
on_remote_settings_changed: Optional[Callable[[List[Http2Setting]], None]] = None, |
| 1060 |
asyncio_connection=False) -> None: |
| 1061 |
self._shutdown_future = None |
| 1062 |
self._host_name = host_name |
| 1063 |
self._port = port |
| 1064 |
self._bootstrap = bootstrap |
| 1065 |
self._tls_connection_options = tls_connection_options |
| 1066 |
self._connect_future = connect_future |
| 1067 |
self._expected_version = expected_version |
| 1068 |
self._on_remote_settings_changed_from_user = on_remote_settings_changed |
| 1069 |
self._asyncio_connection = asyncio_connection |
| 1070 |
|
| 1071 |
def _on_connection_setup(self, binding: Any, error_code: int, http_version: HttpVersion) -> None: |
| 1072 |
if self._connect_future is None: |
| 1073 |
return |
| 1074 |
if error_code != 0: |
| 1075 |
self._connect_future.set_exception(awscrt.exceptions.from_code(error_code)) |
| 1076 |
return |
| 1077 |
if self._expected_version and self._expected_version != http_version: |
| 1078 |
|
| 1079 |
|
| 1080 |
self._connect_future.set_exception(awscrt.exceptions.from_code(2060)) |
| 1081 |
return |
| 1082 |
if self._asyncio_connection: |
| 1083 |
|
| 1084 |
from awscrt.aio.http import AIOHttpClientConnection, AIOHttp2ClientConnection |
| 1085 |
if http_version == HttpVersion.Http2: |
| 1086 |
connection = AIOHttp2ClientConnection() |
| 1087 |
else: |
| 1088 |
connection = AIOHttpClientConnection() |
| 1089 |
else: |
| 1090 |
if http_version == HttpVersion.Http2: |
| 1091 |
connection = Http2ClientConnection() |
| 1092 |
else: |
| 1093 |
connection = HttpClientConnection() |
| 1094 |
|
| 1095 |
connection._host_name = self._host_name |
| 1096 |
connection._port = self._port |
| 1097 |
|
| 1098 |
connection._binding = binding |
| 1099 |
connection._version = HttpVersion(http_version) |
| 1100 |
self._shutdown_future = connection.shutdown_future |
| 1101 |
self._connect_future.set_result(connection) |
| 1102 |
|
| 1103 |
self._connect_future = None |
| 1104 |
|
| 1105 |
def _on_shutdown(self, error_code: int) -> None: |
| 1106 |
if self._shutdown_future is None: |
| 1107 |
|
| 1108 |
return |
| 1109 |
if error_code: |
| 1110 |
self._shutdown_future.set_exception(awscrt.exceptions.from_code(error_code)) |
| 1111 |
else: |
| 1112 |
self._shutdown_future.set_result(None) |
| 1113 |
|
| 1114 |
def _on_remote_settings_changed(self, native_settings: List[Tuple[int, int]]) -> None: |
| 1115 |
if self._on_remote_settings_changed_from_user: |
| 1116 |
|
| 1117 |
settings = [Http2Setting(Http2SettingID(id), value) for id, value in native_settings] |
| 1118 |
self._on_remote_settings_changed_from_user(settings) |