Debian Codegraph @

awscrt/s3.py

raw symbols SCIP
1 """
2 S3 client
3 """
4
5 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6 # SPDX-License-Identifier: Apache-2.0.
7
8 import _awscrt
9 from concurrent.futures import Future
10 from awscrt import NativeResource
11 from awscrt.http import HttpRequest
12 from awscrt.io import ClientBootstrap, TlsConnectionOptions
13 from awscrt.auth import AwsCredentialsProvider, AwsSignatureType, AwsSignedBodyHeaderType, AwsSignedBodyValue, \
14 AwsSigningAlgorithm, AwsSigningConfig
15 import awscrt.exceptions
16 import threading
17 from dataclasses import dataclass
18 from typing import List, Optional, Tuple, Sequence
19 from enum import IntEnum
20
21
22 class CrossProcessLock(NativeResource):
23 """
24 Class representing an exclusive cross-process lock, scoped by `lock_scope_name`
25
26 Recommended usage is to either explicitly call acquire() followed by release() when the lock is no longer required, or use this in a 'with' statement.
27
28 acquire() will throw a RuntimeError with AWS_MUTEX_CALLER_NOT_OWNER as the error code, if the lock could not be acquired.
29
30 If the lock has not been explicitly released when the process exits, it will be released by the operating system.
31
32 Keyword Args:
33 lock_scope_name (str): Unique string identifying the caller holding the lock.
34 """
35
36 def __init__(self, lock_scope_name):
37 super().__init__()
38 self._binding = _awscrt.s3_cross_process_lock_new(lock_scope_name)
39
40 def acquire(self):
41 _awscrt.s3_cross_process_lock_acquire(self._binding)
42
43 def __enter__(self):
44 self.acquire()
45 return self
46
47 def release(self):
48 _awscrt.s3_cross_process_lock_release(self._binding)
49
50 def __exit__(self, exc_type, exc_value, exc_tb):
51 self.release()
52
53
54 class S3RequestType(IntEnum):
55 """The type of the AWS S3 request"""
56
57 DEFAULT = 0
58 """
59 Default type, for all S3 request types other than
60 :attr:`~S3RequestType.GET_OBJECT`/:attr:`~S3RequestType.PUT_OBJECT`.
61 """
62
63 GET_OBJECT = 1
64 """
65 Get Object S3 request
66 """
67
68 PUT_OBJECT = 2
69 """
70 Put Object S3 request
71 """
72
73
74 class S3RequestTlsMode(IntEnum):
75 """TLS mode for S3 request"""
76
77 ENABLED = 0
78 """
79 Enable TLS for S3 request.
80 """
81
82 DISABLED = 1
83 """
84 Disable TLS for S3 request.
85 """
86
87
88 class S3ChecksumAlgorithm(IntEnum):
89 """
90 Checksum algorithm used to verify object integrity.
91 https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html
92 """
93
94 CRC32C = 1
95 """CRC32C"""
96
97 CRC32 = 2
98 """CRC32"""
99
100 SHA1 = 3
101 """SHA-1"""
102
103 SHA256 = 4
104 """SHA-256"""
105
106 CRC64NVME = 5
107 """CRC64NVME"""
108
109 SHA512 = 6,
110 """SHA512"""
111
112 XXHASH64 = 7,
113 """XXHASH64"""
114
115 XXHASH3 = 8,
116 """XXHASH3"""
117
118 XXHASH128 = 9,
119 """XXHASH128"""
120
121
122 class S3ChecksumLocation(IntEnum):
123 """Where to put the checksum."""
124
125 HEADER = 1
126 """
127 Add checksum as a request header field.
128 The checksum is calculated before any part of the request is sent to the server.
129 """
130
131 TRAILER = 2
132 """
133 Add checksum as a request trailer field.
134 The checksum is calculated as the body is streamed to the server, then
135 added as a trailer field. This may be more efficient than HEADER, but
136 can only be used with "streaming" requests that support it.
137 """
138
139
140 @dataclass
141 class S3ChecksumConfig:
142 """Configures how the S3Client calculates and verifies checksums."""
143
144 algorithm: Optional[S3ChecksumAlgorithm] = None
145 """
146 If set, the S3Client will calculate a checksum using this algorithm
147 and add it to the request. If you set this, you must also set `location`.
148 """
149
150 location: Optional[S3ChecksumLocation] = None
151 """Where to put the request checksum."""
152
153 validate_response: bool = False
154 """Whether to retrieve and validate response checksums."""
155
156
157 @dataclass
158 class S3FileIoOptions:
159 """
160 WARNING: experimental/unstable, the default behavior is subjected to change in the future.
161 Controls how client performance file I/O operations.
162 Only applies to the file based workload.
163 Notes: only applies when `send_filepath` is set from the request.
164 """
165
166 should_stream: bool = False
167 """
168 Skip buffering the part in memory before sending the request.
169
170 Default to false on small objects, and true when the object size exceed a certain threshold.
171 """
172
173 disk_throughput_gbps: (Optional[float]) = 0.0
174 """
175 The estimated disk throughput. Only be applied when `streaming_upload` is true.
176 in gigabits per second (Gbps).
177
178 Notes: There are possibilities that cannot reach the all available disk throughput:
179 1. Disk is busy with other applications
180 2. OS Cache may cap the throughput, use `direct_io` to get around this.
181
182 Default to `throughput_target_gbps`.
183 """
184
185 direct_io: bool = False
186 """
187 Enable direct IO to bypass the OS cache. Helpful when the disk I/O outperforms the kernel cache.
188
189 - Currently only Linux supports direct I/O. On unsupported platforms, the request transparently
190 falls back to buffered I/O and a warning is logged.
191 - Supported for both upload (send_filepath) and download (recv_filepath).
192 - This is a BEST-EFFORT optimization. The request transparently falls back to
193 buffered I/O (logging a warning) when direct io write fails.
194 - Check NOTES for O_DIRECT for additional info https://man7.org/linux/man-pages/man2/openat.2.html
195
196 In summary, O_DIRECT is a potentially powerful tool that should be used with caution.
197 """
198
199
200 class S3Client(NativeResource):
201 """S3 client
202
203 Keyword Args:
204 bootstrap (Optional [ClientBootstrap]): Client bootstrap to use when initiating socket connection.
205 If None is provided, the default singleton is used.
206
207 region (str): Region that the S3 bucket lives in.
208
209 tls_mode (Optional[S3RequestTlsMode]): How TLS should be used while performing the request
210
211 If this is :attr:`S3RequestTlsMode.ENABLED`:
212 If `tls_connection_options` is set, then those TLS options will be used
213 If `tls_connection_options` is unset, then default TLS options will be used
214
215 If this is :attr:`S3RequestTlsMode.DISABLED`:
216 No TLS options will be used, regardless of `tls_connection_options` value.
217
218 signing_config (Optional[AwsSigningConfig]): Configuration for signing of the client.
219 Use :func:`create_default_s3_signing_config()` to create the default config.
220
221 If not set, a default config will be used with anonymous credentials and skip signing the request.
222
223 If set:
224 Credentials provider is required. Other configs are all optional, and will be default to what
225 needs to sign the request for S3, only overrides when Non-zero/Not-empty is set.
226
227 S3 Client will derive the right config for signing process based on this.
228
229 Notes:
230
231 1. For SIGV4_S3EXPRESS, S3 client will use the credentials in the config to derive the S3 Express
232 credentials that are used in the signing process.
233 2. Client may make modifications to signing config before passing it on to signer.
234
235 credential_provider (Optional[AwsCredentialsProvider]): Deprecated, prefer `signing_config` instead.
236 Credentials providers source the :class:`~awscrt.auth.AwsCredentials` needed to sign an authenticated AWS request.
237 If None is provided, the request will not be signed.
238
239 tls_connection_options (Optional[TlsConnectionOptions]): Optional TLS Options to be used
240 for each connection, unless `tls_mode` is :attr:`S3RequestTlsMode.DISABLED`
241
242 part_size (Optional[int]): Size, in bytes, of parts that files will be downloaded or uploaded in.
243 If not set, a dynamic default part size will be used based on the throughput target, memory_limit_in_bytes.
244 Note: for :attr:`S3RequestType.PUT_OBJECT` request, client will adjust the part size to meet the service limits.
245 (max number of parts per upload is 10,000, minimum upload part size is 5 MiB)
246
247 multipart_upload_threshold (Optional[int]): The size threshold in bytes, for when to use multipart uploads.
248 This only affects :attr:`S3RequestType.PUT_OBJECT` request.
249 Uploads over this size will use the multipart upload strategy.
250 Uploads this size or less will use a single request.
251 If not set, maximal of `part_size` and 5 MiB will be used.
252
253 throughput_target_gbps (Optional[float]): Throughput target in
254 Gigabits per second (Gbps) that we are trying to reach.
255 You can also use `get_recommended_throughput_target_gbps()` to get recommended value for your system.
256 10.0 Gbps by default (may change in future)
257
258 enable_s3express (Optional[bool]): To enable S3 Express support for the client.
259 The typical usage for a S3 Express request is to set this to true and let the request to be
260 signed with `AwsSigningAlgorithm.V4_S3EXPRESS`, either from the client-level `signing_config`
261 or the request-level override.
262
263 memory_limit (Optional[int]): Memory limit, in bytes, of how much memory
264 client can use for buffering data for requests.
265 If not set, client will try to pick up from environment variable before chose the default.
266 Default values scale with target throughput and are currently
267 between 2GiB and 24GiB (may change in future)
268
269 network_interface_names (Optional[Sequence(str)]):
270 **THIS IS AN EXPERIMENTAL AND UNSTABLE API.**
271 A sequence of network interface names. The client will distribute the
272 connections across network interfaces. If any interface name is invalid, goes down,
273 or has any issues like network access, you will see connection failures.
274 This option is only supported on Linux, MacOS, and platforms that have either SO_BINDTODEVICE or IP_BOUND_IF. It
275 is not supported on Windows. `AWS_ERROR_PLATFORM_NOT_SUPPORTED` will be raised on unsupported platforms. On
276 Linux, SO_BINDTODEVICE is used and requires kernel version >= 5.7 or root privileges.
277
278 fio_options (Optional[S3FileIoOptions]):
279 If set, this controls how the client interact with file I/O.
280 If not set, a default options will be created to avoid memory issue based on the size of file.
281 Note: Only applies when the request created with `send_filepath`
282
283 max_active_connections_override (Optional[int]):
284 When set, this will cap the number of active connections for the meta request.
285 When not set, the client will determine this value based on `throughput_target_gbps`. (Recommended)
286 """
287
288 __slots__ = ('shutdown_event', '_region')
289
290 def __init__(
291 self,
292 *,
293 bootstrap=None,
294 region,
295 tls_mode=None,
296 signing_config=None,
297 credential_provider=None,
298 tls_connection_options=None,
299 part_size=None,
300 multipart_upload_threshold=None,
301 throughput_target_gbps=None,
302 enable_s3express=False,
303 memory_limit=None,
304 network_interface_names: Optional[Sequence[str]] = None,
305 fio_options: Optional['S3FileIoOptions'] = None,
306 max_active_connections_override: Optional[int] = None):
307 assert isinstance(bootstrap, ClientBootstrap) or bootstrap is None
308 assert isinstance(region, str)
309 assert isinstance(signing_config, AwsSigningConfig) or signing_config is None
310 assert isinstance(credential_provider, AwsCredentialsProvider) or credential_provider is None
311 assert isinstance(tls_connection_options, TlsConnectionOptions) or tls_connection_options is None
312 assert isinstance(part_size, int) or part_size is None
313 assert isinstance(
314 throughput_target_gbps,
315 int) or isinstance(
316 throughput_target_gbps,
317 float) or throughput_target_gbps is None
318 assert isinstance(enable_s3express, bool) or enable_s3express is None
319 assert isinstance(network_interface_names, Sequence) or network_interface_names is None
320 assert isinstance(fio_options, S3FileIoOptions) or fio_options is None
321 assert isinstance(max_active_connections_override, int) or max_active_connections_override is None
322
323 if credential_provider and signing_config:
324 raise ValueError("'credential_provider' has been deprecated in favor of 'signing_config'. "
325 "Both parameters may not be set.")
326
327 super().__init__()
328
329 shutdown_event = threading.Event()
330
331 def on_shutdown():
332 shutdown_event.set()
333
334 self._region = region
335 self.shutdown_event = shutdown_event
336
337 if not bootstrap:
338 bootstrap = ClientBootstrap.get_or_create_static_default()
339
340 s3_client_core = _S3ClientCore(
341 bootstrap,
342 credential_provider,
343 signing_config,
344 tls_connection_options)
345
346 # C layer uses 0 to indicate defaults
347 if tls_mode is None:
348 tls_mode = 0
349 if part_size is None:
350 part_size = 0
351 if multipart_upload_threshold is None:
352 multipart_upload_threshold = 0
353 if throughput_target_gbps is None:
354 throughput_target_gbps = 0
355 if memory_limit is None:
356 memory_limit = 0
357 if network_interface_names is not None:
358 # ensure this is a list, so it's simpler to process in C
359 if not isinstance(network_interface_names, list):
360 network_interface_names = list(network_interface_names)
361 if max_active_connections_override is None:
362 max_active_connections_override = 0
363 fio_options_set = False
364 should_stream = False
365 disk_throughput_gbps = 0.0
366 direct_io = False
367 if fio_options is not None:
368 fio_options_set = True
369 should_stream = fio_options.should_stream
370 disk_throughput_gbps = fio_options.disk_throughput_gbps
371 direct_io = fio_options.direct_io
372
373 self._binding = _awscrt.s3_client_new(
374 bootstrap,
375 signing_config,
376 credential_provider,
377 tls_connection_options,
378 on_shutdown,
379 region,
380 tls_mode,
381 part_size,
382 multipart_upload_threshold,
383 throughput_target_gbps,
384 enable_s3express,
385 memory_limit,
386 network_interface_names,
387 fio_options_set,
388 should_stream,
389 disk_throughput_gbps,
390 direct_io,
391 max_active_connections_override,
392 s3_client_core)
393
394 def make_request(
395 self,
396 *,
397 type,
398 request,
399 operation_name=None,
400 recv_filepath=None,
401 send_filepath=None,
402 signing_config=None,
403 credential_provider=None,
404 checksum_config=None,
405 part_size=None,
406 multipart_upload_threshold=None,
407 fio_options=None,
408 max_active_connections_override=None,
409 on_headers=None,
410 on_body=None,
411 on_done=None,
412 on_progress=None):
413 """Create the Request to the the S3 server,
414 :attr:`~S3RequestType.GET_OBJECT`/:attr:`~S3RequestType.PUT_OBJECT` requests are split it into multi-part
415 requests under the hood for acceleration.
416
417 Keyword Args:
418 type (S3RequestType): The type of S3 request passed in,
419 :attr:`~S3RequestType.GET_OBJECT`/:attr:`~S3RequestType.PUT_OBJECT` can be accelerated
420
421 request (HttpRequest): The overall outgoing API request for S3 operation.
422 If the request body is a file, set send_filepath for better performance.
423
424 operation_name(Optional[str]): S3 operation name (e.g. "CreateBucket").
425 This MUST be set when `type` is :attr:`~S3RequestType.DEFAULT`.
426 It is ignored for other types, since the operation is implicitly known.
427 See `S3 API documentation
428 <https://docs.aws.amazon.com/AmazonS3/latest/API/API_Operations_Amazon_Simple_Storage_Service.html>`_
429 for the canonical list of names.
430
431 This name is used to fill out details in metrics and error reports.
432 It also drives some operation-specific behavior.
433 If you pass the wrong name, you risk getting the wrong behavior.
434
435 For example, every operation except "GetObject" has its response checked
436 for error, even if the HTTP status-code was 200 OK
437 (see `knowledge center <https://repost.aws/knowledge-center/s3-resolve-200-internalerror>`_).
438 If you used the :attr:`~S3RequestType.DEFAULT` type to do
439 `GetObject <https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html>`_,
440 but mis-named it "Download", and the object looked like XML with an error code,
441 then the request would fail. You risk logging the full response body,
442 and leaking sensitive data.
443
444 recv_filepath (Optional[str]): Optional file path. If set, the
445 response body is written directly to a file and the
446 `on_body` callback is not invoked. This should give better
447 performance than writing to file from the `on_body` callback.
448
449 send_filepath (Optional[str]): Optional file path. If set, the
450 request body is read directly from a file and the
451 request's `body_stream` is ignored. This should give better
452 performance than reading a file from a stream.
453
454 signing_config (Optional[AwsSigningConfig]): Configuration for signing of the request to override the configuration from client.
455 Use :func:`create_default_s3_signing_config()` to create the default config.
456
457 If None is provided, the client configuration will be used.
458
459 If set:
460 All fields are optional. The credentials will be resolve from client if not set.
461 S3 Client will derive the right config for signing process based on this.
462
463 Notes:
464
465 1. For SIGV4_S3EXPRESS, S3 client will use the credentials in the config to derive the S3 Express
466 credentials that are used in the signing process.
467 2. Client may make modifications to signing config before passing it on to signer.
468
469 credential_provider (Optional[AwsCredentialsProvider]): Deprecated, prefer `signing_config` instead.
470 Credentials providers source the :class:`~awscrt.auth.AwsCredentials` needed to sign an authenticated AWS request, for this request only.
471 If None is provided, the client configuration will be used.
472
473 checksum_config (Optional[S3ChecksumConfig]): Optional checksum settings.
474
475 part_size (Optional[int]): Size, in bytes, of parts that files will be downloaded or uploaded in.
476 If not set, the part size configured for the client will be used, which defaults to a dynamic value based on
477 the throughput target, memory_limit_in_bytes and the requested object size.
478 Note: for :attr:`S3RequestType.PUT_OBJECT` request, client will adjust the part size to meet the service limits.
479 (max number of parts per upload is 10,000, minimum upload part size is 5 MiB)
480
481 multipart_upload_threshold (Optional[int]): The size threshold in bytes, for when to use multipart uploads.
482 This only affects :attr:`S3RequestType.PUT_OBJECT` request.
483 Uploads over this size will use the multipart upload strategy.
484 Uploads this size or less will use a single request.
485 If set, this should be at least `part_size`.
486 If not set, `part_size` adjusted by client will be used as the threshold.
487 If both `part_size` and `multipart_upload_threshold` are not set,
488 the values from `aws_s3_client_config` are used.
489
490 fio_options (Optional[S3FileIoOptions]):
491 If set, this overrides the client fio_options to control how this request interact with file I/O.
492 If not set, a default options will be created to avoid memory issue based on the size of file.
493 Note: Only applies when the request created with `send_filepath`
494
495 max_active_connections_override (Optional[int]):
496 When set, this will cap the number of active connections for the meta request.
497 When not set, the client will determine it based on client side settings. (Recommended)
498
499 on_headers: Optional callback invoked as the response received, and even the API request
500 has been split into multiple parts, this callback will only be invoked once as
501 it's just making one API request to S3.
502 The function should take the following arguments and return nothing:
503
504 * `status_code` (int): Response status code.
505
506 * `headers` (List[Tuple[str, str]]): Response headers as a
507 list of (name,value) pairs.
508
509 * `**kwargs` (dict): Forward-compatibility kwargs.
510
511 on_body: Optional callback invoked 0+ times as the response body received from S3 server.
512 If simply writing to a file, use `recv_filepath` instead of `on_body` for better performance.
513 The function should take the following arguments and return nothing:
514
515 * `chunk` (buffer): Response body data (not necessarily
516 a whole "chunk" of chunked encoding).
517
518 * `offset` (int): The offset of the chunk started in the whole body.
519
520 * `**kwargs` (dict): Forward-compatibility kwargs.
521
522 on_done: Optional callback invoked when the request has finished the job.
523 The function should take the following arguments and return nothing:
524
525 * `error` (Optional[Exception]): None if the request was
526 successfully sent and valid response received, or an Exception
527 if it failed.
528
529 * `error_headers` (Optional[List[Tuple[str, str]]]): If request
530 failed because server side sent an unsuccessful response, the headers
531 of the response is provided here. Else None will be returned.
532
533 * `error_body` (Optional[bytes]): If request failed because server
534 side sent an unsuccessful response, the body of the response is
535 provided here. Else None will be returned.
536
537 * `error_operation_name` (Optional[str]): If request failed
538 because server side sent and unsuccessful response, this
539 is the name of the S3 operation it was responding to.
540 For example, if a :attr:`~S3RequestType.PUT_OBJECT` fails
541 this could be "PutObject", "CreateMultipartUpload", "UploadPart",
542 "CompleteMultipartUpload", or others. For :attr:`~S3RequestType.DEFAULT`,
543 this is the `operation_name` passed to :meth:`S3Client.make_request()`.
544 This will be None if the request failed for another reason,
545 or the S3 operation name is unknown.
546
547 * `status_code` (Optional[int]): HTTP response status code (if available).
548 If request failed because server side sent an unsuccessful response,
549 this is its status code. If the operation was successful,
550 this is the final response's status code. If the operation
551 failed for another reason, None is returned.
552
553 * `did_validate_checksum` (bool):
554 Was the server side checksum compared against a calculated checksum of the response body.
555 This may be false even if :attr:`S3ChecksumConfig.validate_response` was set because
556 the object was uploaded without a checksum, or downloaded differently from how it's uploaded.
557
558 * `checksum_validation_algorithm` (Optional[S3ChecksumAlgorithm]): The checksum algorithm used to validate the response.
559
560 * `**kwargs` (dict): Forward-compatibility kwargs.
561
562 on_progress: Optional callback invoked when part of the transfer is done to report the progress.
563 The function should take the following arguments and return nothing:
564
565 * `progress` (int): Number of bytes of data that just get transferred
566
567 * `**kwargs` (dict): Forward-compatibility kwargs.
568
569 Returns:
570 S3Request
571 """
572 return S3Request(
573 client=self,
574 type=type,
575 request=request,
576 operation_name=operation_name,
577 recv_filepath=recv_filepath,
578 send_filepath=send_filepath,
579 signing_config=signing_config,
580 credential_provider=credential_provider,
581 checksum_config=checksum_config,
582 part_size=part_size,
583 multipart_upload_threshold=multipart_upload_threshold,
584 fio_options=fio_options,
585 max_active_connections_override=max_active_connections_override,
586 on_headers=on_headers,
587 on_body=on_body,
588 on_done=on_done,
589 on_progress=on_progress,
590 region=self._region)
591
592
593 class S3Request(NativeResource):
594 """S3 request
595 Create a new S3Request with :meth:`S3Client.make_request()`
596
597 Attributes:
598 finished_future (concurrent.futures.Future): Future that will
599 resolve when the s3 request has finished successfully.
600 If the error happens, the Future will contain an exception
601 indicating why it failed. Note: Future will set before on_done invoked
602
603 shutdown_event (threading.Event): Signals when underlying threads and
604 structures have all finished shutting down. Shutdown begins when the
605 S3Request object is destroyed.
606 """
607 __slots__ = ('_finished_future', 'shutdown_event')
608
609 def __init__(
610 self,
611 *,
612 client,
613 type,
614 request,
615 operation_name=None,
616 recv_filepath=None,
617 send_filepath=None,
618 signing_config=None,
619 credential_provider=None,
620 checksum_config=None,
621 part_size=None,
622 multipart_upload_threshold=None,
623 fio_options=None,
624 max_active_connections_override=None,
625 on_headers=None,
626 on_body=None,
627 on_done=None,
628 on_progress=None,
629 region=None):
630 assert isinstance(client, S3Client)
631 assert isinstance(request, HttpRequest)
632 assert callable(on_headers) or on_headers is None
633 assert callable(on_body) or on_body is None
634 assert callable(on_done) or on_done is None
635 assert isinstance(part_size, int) or part_size is None
636 assert isinstance(multipart_upload_threshold, int) or multipart_upload_threshold is None
637 assert isinstance(fio_options, S3FileIoOptions) or fio_options is None
638 assert isinstance(max_active_connections_override, int) or max_active_connections_override is None
639
640 if type == S3RequestType.DEFAULT and not operation_name:
641 raise ValueError("'operation_name' must be set when using S3RequestType.DEFAULT")
642
643 super().__init__()
644
645 self._finished_future = Future()
646 self.shutdown_event = threading.Event()
647
648 # C layer uses 0 to indicate defaults
649 if part_size is None:
650 part_size = 0
651 if multipart_upload_threshold is None:
652 multipart_upload_threshold = 0
653 checksum_algorithm = 0
654 checksum_location = 0
655 validate_response_checksum = False
656 if checksum_config is not None:
657 if checksum_config.algorithm is not None:
658 checksum_algorithm = checksum_config.algorithm.value
659 if checksum_config.location is not None:
660 checksum_location = checksum_config.location.value
661 validate_response_checksum = checksum_config.validate_response
662 fio_options_set = False
663 should_stream = False
664 disk_throughput_gbps = 0.0
665 direct_io = False
666 if fio_options is not None:
667 fio_options_set = True
668 should_stream = fio_options.should_stream
669 disk_throughput_gbps = fio_options.disk_throughput_gbps
670 direct_io = fio_options.direct_io
671 if max_active_connections_override is None:
672 max_active_connections_override = 0
673
674 s3_request_core = _S3RequestCore(
675 request,
676 self._finished_future,
677 self.shutdown_event,
678 signing_config,
679 credential_provider,
680 on_headers,
681 on_body,
682 on_done,
683 on_progress)
684
685 self._binding = _awscrt.s3_client_make_meta_request(
686 self,
687 client,
688 request,
689 type,
690 operation_name,
691 signing_config,
692 credential_provider,
693 recv_filepath,
694 send_filepath,
695 region,
696 checksum_algorithm,
697 checksum_location,
698 validate_response_checksum,
699 part_size,
700 multipart_upload_threshold,
701 fio_options_set,
702 should_stream,
703 disk_throughput_gbps,
704 direct_io,
705 max_active_connections_override,
706 s3_request_core)
707
708 @property
709 def finished_future(self):
710 return self._finished_future
711
712 def cancel(self):
713 _awscrt.s3_meta_request_cancel(self)
714
715
716 class S3ResponseError(awscrt.exceptions.AwsCrtError):
717 '''
718 An error response from S3.
719
720 Subclasses :class:`awscrt.exceptions.AwsCrtError`.
721
722 Attributes:
723 status_code (int): HTTP response status code.
724 headers (list[tuple[str, str]]): Headers from HTTP response.
725 body (Optional[bytes]): Body of HTTP response (if any).
726 This is usually XML. It may be None in the case of a HEAD response.
727 operation_name: Name of the S3 operation that failed.
728 For example, if a :attr:`~S3RequestType.PUT_OBJECT` fails
729 this could be "PutObject", "CreateMultipartUpload", "UploadPart",
730 "CompleteMultipartUpload", or others. For :attr:`~S3RequestType.DEFAULT`,
731 this is the `operation_name` passed to :meth:`S3Client.make_request()`.
732 code (int): CRT error code.
733 name (str): CRT error name.
734 message (str): CRT error message.
735 '''
736
737 def __init__(self, *,
738 code: int,
739 name: str,
740 message: str,
741 status_code: List[Tuple[str, str]] = None,
742 headers: List[Tuple[str, str]] = None,
743 body: Optional[bytes] = None,
744 operation_name: Optional[str] = None):
745 super().__init__(code, name, message)
746 self.status_code = status_code
747 self.headers = headers
748 self.body = body
749 self.operation_name = operation_name
750
751
752 class _S3ClientCore:
753 '''
754 Private class to keep all the related Python object alive until C land clean up for S3Client
755 '''
756
757 def __init__(self, bootstrap,
758 credential_provider=None,
759 signing_config=None,
760 tls_connection_options=None):
761 self._bootstrap = bootstrap
762 self._credential_provider = credential_provider
763 self._signing_config = signing_config
764 self._tls_connection_options = tls_connection_options
765
766
767 class _S3RequestCore:
768 '''
769 Private class to keep all the related Python object alive until C land clean up for S3Request
770 '''
771
772 def __init__(
773 self,
774 request,
775 finish_future,
776 shutdown_event,
777 signing_config=None,
778 credential_provider=None,
779 on_headers=None,
780 on_body=None,
781 on_done=None,
782 on_progress=None):
783
784 # Stores exception raised in on_headers or on_body callback so that we can rethrow it in the on_done callback
785 self._python_callback_exception = None
786 self._request = request
787 self._signing_config = signing_config
788 self._credential_provider = credential_provider
789
790 self._on_headers_cb = on_headers
791 self._on_body_cb = on_body
792 self._on_done_cb = on_done
793 self._on_progress_cb = on_progress
794
795 self._finished_future = finish_future
796 self._shutdown_event = shutdown_event
797
798 def _on_headers(self, status_code, headers):
799 if self._on_headers_cb:
800 try:
801 self._on_headers_cb(status_code=status_code, headers=headers)
802 return True
803 except BaseException as e:
804 self._python_callback_exception = e
805 return False
806
807 def _on_body(self, chunk, offset):
808 if self._on_body_cb:
809 try:
810 self._on_body_cb(chunk=chunk, offset=offset)
811 return True
812 except BaseException as e:
813 self._python_callback_exception = e
814 return False
815
816 def _on_shutdown(self):
817 self._shutdown_event.set()
818
819 def _on_finish(
820 self,
821 error_code,
822 status_code,
823 error_headers,
824 error_body,
825 error_operation_name,
826 did_validate_checksum,
827 checksum_validation_algorithm):
828 # If C layer gives status_code 0, that means "unknown"
829 if status_code == 0:
830 status_code = None
831
832 error = None
833 if error_code:
834 error = awscrt.exceptions.from_code(error_code)
835 if isinstance(error, awscrt.exceptions.AwsCrtError):
836 if (error.name == "AWS_ERROR_CRT_CALLBACK_EXCEPTION"
837 and self._python_callback_exception is not None):
838 error = self._python_callback_exception
839 # If the failure was due to a response, make it into an S3ResponseError.
840 # When failure is due to a response, its headers are always included.
841 elif status_code is not None \
842 and error_headers is not None:
843 error = S3ResponseError(
844 code=error.code,
845 name=error.name,
846 message=error.message,
847 status_code=status_code,
848 headers=error_headers,
849 body=error_body,
850 operation_name=error_operation_name)
851 self._finished_future.set_exception(error)
852 else:
853 self._finished_future.set_result(None)
854
855 if checksum_validation_algorithm:
856 checksum_validation_algorithm = S3ChecksumAlgorithm(checksum_validation_algorithm)
857 else:
858 checksum_validation_algorithm = None
859
860 if self._on_done_cb:
861 self._on_done_cb(
862 error=error,
863 error_headers=error_headers,
864 error_body=error_body,
865 error_operation_name=error_operation_name,
866 status_code=status_code,
867 did_validate_checksum=did_validate_checksum,
868 checksum_validation_algorithm=checksum_validation_algorithm)
869
870 def _on_progress(self, progress):
871 if self._on_progress_cb:
872 self._on_progress_cb(progress)
873
874
875 def create_default_s3_signing_config(*, region: str, credential_provider: AwsCredentialsProvider, **kwargs):
876 """Create a default `AwsSigningConfig` for S3 service.
877
878 Attributes:
879 region (str): The region to sign against.
880
881 credential_provider (AwsCredentialsProvider): Credentials provider
882 to fetch signing credentials with.
883
884 `**kwargs`: Forward compatibility kwargs.
885
886 Returns:
887 AwsSigningConfig
888 """
889 return AwsSigningConfig(
890 algorithm=AwsSigningAlgorithm.V4,
891 signature_type=AwsSignatureType.HTTP_REQUEST_HEADERS,
892 service="s3",
893 signed_body_header_type=AwsSignedBodyHeaderType.X_AMZ_CONTENT_SHA_256,
894 signed_body_value=AwsSignedBodyValue.UNSIGNED_PAYLOAD,
895 region=region,
896 credentials_provider=credential_provider,
897 use_double_uri_encode=False,
898 should_normalize_uri_path=False,
899 )
900
901
902 def get_ec2_instance_type():
903 """
904 First this function will check it's running on EC2 via. attempting to read DMI info to avoid making IMDS calls.
905
906 If the function detects it's on EC2, and it was able to detect the instance type without a call to IMDS
907 it will return it.
908
909 Finally, it will call IMDS and return the instance type from there.
910 Note that in the case of the IMDS call, a new client stack is spun up using 1 background thread. The call is made
911 synchronously with a 1 second timeout: It's not cheap. To make this easier, the underlying result is cached
912 internally and will be freed when this module is unloaded is called.
913
914 Returns:
915 A string indicating the instance type or None if it could not be determined.
916 """
917 return _awscrt.s3_get_ec2_instance_type()
918
919
920 def is_optimized_for_system():
921 """
922 Returns:
923 true if the current build of this module has an optimized configuration
924 for the current system.
925 """
926 return _awscrt.s3_is_crt_s3_optimized_for_system()
927
928
929 def get_optimized_platforms():
930 """
931 Returns:
932 A list[str] of platform identifiers, such as EC2 instance types, for which S3 client is pre-optimized
933 and have a recommended throughput_target_gbps. You can use `get_recommended_throughput_target_gbps()`
934 to obtain the recommended throughput_target_gbps for those platforms.
935 """
936 return _awscrt.s3_get_optimized_platforms()
937
938
939 def get_recommended_throughput_target_gbps() -> Optional[float]:
940 """
941 Returns:
942 Recommended throughput, in gigabits per second, based on detected system configuration.
943 If the best throughput configuration is unknown, returns None.
944 Use this as the S3Client's `throughput_target_gbps`.
945 """
946 # Currently the CRT returns 0 if it was unable to make a good guess on configuration. Pre-known configs,
947 # have this value set. Eventually, the CRT will make a full calculation based on NIC and CPU configuration,
948 # but until then handle 0.
949 max_value = _awscrt.s3_get_recommended_throughput_target_gbps()
950 if max_value > 0:
951 return max_value
952 else:
953 return None