Source code for multistorageclient.providers.s3

   1# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
   2# SPDX-License-Identifier: Apache-2.0
   3#
   4# Licensed under the Apache License, Version 2.0 (the "License");
   5# you may not use this file except in compliance with the License.
   6# You may obtain a copy of the License at
   7#
   8# http://www.apache.org/licenses/LICENSE-2.0
   9#
  10# Unless required by applicable law or agreed to in writing, software
  11# distributed under the License is distributed on an "AS IS" BASIS,
  12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13# See the License for the specific language governing permissions and
  14# limitations under the License.
  15
  16import functools
  17import io
  18import logging
  19import os
  20import tempfile
  21import threading
  22from collections.abc import Callable, Iterator
  23from typing import IO, Any, TypeVar
  24
  25import boto3
  26import botocore
  27from boto3.exceptions import S3UploadFailedError
  28from boto3.s3.transfer import TransferConfig
  29from botocore.credentials import RefreshableCredentials
  30from botocore.exceptions import ClientError, IncompleteReadError, ReadTimeoutError, ResponseStreamingError
  31from botocore.session import get_session
  32from dateutil.parser import parse as dateutil_parse
  33
  34from multistorageclient_rust import RustClient, RustClientError, RustRetryableError
  35
  36from ..constants import DEFAULT_CONNECT_TIMEOUT, DEFAULT_MAX_POOL_CONNECTIONS, DEFAULT_READ_TIMEOUT
  37from ..rust_utils import parse_retry_config, run_async_rust_client_method
  38from ..signers import CloudFrontURLSigner, URLSigner
  39from ..telemetry import Telemetry
  40from ..types import (
  41    AWARE_DATETIME_MIN,
  42    Credentials,
  43    CredentialsProvider,
  44    ObjectMetadata,
  45    PreconditionFailedError,
  46    Range,
  47    RetryableError,
  48    SignerType,
  49    StreamingObjectWriter,
  50    StreamingWriterOptions,
  51    SuffixRange,
  52    SymlinkHandling,
  53)
  54from ..utils import (
  55    _decode_buffer,
  56    safe_makedirs,
  57    split_path,
  58    validate_attributes,
  59)
  60from .base import BaseStorageProvider, _translate_iterator_errors
  61from .rust_streaming import RustStreamingWriter
  62
  63logger = logging.getLogger(__name__)
  64
  65_T = TypeVar("_T")
  66
  67MiB = 1024 * 1024
  68
  69# Python and Rust share the same multipart_threshold to keep the code simple.
  70MULTIPART_THRESHOLD = 64 * MiB
  71MULTIPART_CHUNKSIZE = 32 * MiB
  72IO_CHUNKSIZE = 32 * MiB
  73PYTHON_MAX_CONCURRENCY = 8
  74MAX_POOL_CONNECTIONS = DEFAULT_MAX_POOL_CONNECTIONS
  75
  76PROVIDER = "s3"
  77
  78EXPRESS_ONEZONE_STORAGE_CLASS = "EXPRESS_ONEZONE"
  79
  80# Source: https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html
  81SUPPORTED_CHECKSUM_ALGORITHMS = frozenset({"CRC32", "CRC32C", "SHA1", "SHA256", "CRC64NVME"})
  82
  83
[docs] 84class StaticS3CredentialsProvider(CredentialsProvider): 85 """ 86 A concrete implementation of the :py:class:`multistorageclient.types.CredentialsProvider` that provides static S3 credentials. 87 """ 88 89 _access_key: str 90 _secret_key: str 91 _session_token: str | None 92 93 def __init__(self, access_key: str, secret_key: str, session_token: str | None = None): 94 """ 95 Initializes the :py:class:`StaticS3CredentialsProvider` with the provided access key, secret key, and optional 96 session token. 97 98 :param access_key: The access key for S3 authentication. 99 :param secret_key: The secret key for S3 authentication. 100 :param session_token: An optional session token for temporary credentials. 101 """ 102 self._access_key = access_key 103 self._secret_key = secret_key 104 self._session_token = session_token 105
[docs] 106 def get_credentials(self) -> Credentials: 107 return Credentials( 108 access_key=self._access_key, 109 secret_key=self._secret_key, 110 token=self._session_token, 111 expiration=None, 112 )
113
[docs] 114 def refresh_credentials(self) -> None: 115 pass
116 117 118DEFAULT_PRESIGN_EXPIRES_IN = 3600 119 120_S3_METHOD_MAPPING: dict[str, str] = { 121 "GET": "get_object", 122 "PUT": "put_object", 123} 124 125
[docs] 126class S3URLSigner(URLSigner): 127 """Generates pre-signed URLs using the boto3 S3 client. 128 129 When the underlying credentials are temporary (STS, IAM role, EC2 instance 130 profile), the effective URL lifetime is the **shorter** of ``expires_in`` 131 and the remaining credential lifetime — boto3 will not warn if the 132 credential expires before ``expires_in``. 133 134 See https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html 135 """ 136 137 def __init__(self, s3_client: Any, bucket: str, expires_in: int = DEFAULT_PRESIGN_EXPIRES_IN) -> None: 138 self._s3_client = s3_client 139 self._bucket = bucket 140 self._expires_in = expires_in 141
[docs] 142 def generate_presigned_url(self, path: str, *, method: str = "GET") -> str: 143 client_method = _S3_METHOD_MAPPING.get(method.upper()) 144 if client_method is None: 145 raise ValueError(f"Unsupported method for S3 presigning: {method!r}") 146 return self._s3_client.generate_presigned_url( 147 ClientMethod=client_method, 148 Params={"Bucket": self._bucket, "Key": path}, 149 ExpiresIn=self._expires_in, 150 )
151 152
[docs] 153class S3StorageProvider(BaseStorageProvider): 154 """ 155 A concrete implementation of the :py:class:`multistorageclient.types.StorageProvider` for interacting with Amazon S3 or S3-compatible object stores. 156 """ 157 158 def __init__( 159 self, 160 region_name: str = "", 161 endpoint_url: str = "", 162 base_path: str = "", 163 credentials_provider: CredentialsProvider | None = None, 164 profile_name: str | None = None, 165 config_dict: dict[str, Any] | None = None, 166 telemetry_provider: Callable[[], Telemetry] | None = None, 167 verify: bool | str | None = None, 168 **kwargs: Any, 169 ) -> None: 170 """ 171 Initializes the :py:class:`S3StorageProvider` with the region, endpoint URL, and optional credentials provider. 172 173 :param region_name: The AWS region where the S3 bucket is located. 174 :param endpoint_url: The custom endpoint URL for the S3 service. 175 :param base_path: The root prefix path within the S3 bucket where all operations will be scoped. 176 :param credentials_provider: The provider to retrieve S3 credentials. 177 :param profile_name: AWS shared configuration + credentials files profile. For :py:class:`boto3.session.Session`. Ignored if ``credentials_provider`` is set. 178 :param config_dict: Resolved MSC config. 179 :param telemetry_provider: A function that provides a telemetry instance. 180 :param verify: Controls SSL certificate verification. 181 Can be ``True`` (verify using system CA bundle, default), ``False`` (skip verification), or a string path to a custom CA certificate bundle. 182 :param request_checksum_calculation: For :py:class:`botocore.config.Config`. 183 When the underlying S3 client should calculate request checksums. 184 :param response_checksum_validation: For :py:class:`botocore.config.Config`. 185 When the underlying S3 client should validate response checksums. 186 :param max_pool_connections: For :py:class:`botocore.config.Config`. 187 The maximum number of connections to keep in a connection pool. 188 :param connect_timeout: For :py:class:`botocore.config.Config`. 189 The time in seconds till a timeout exception is thrown when attempting to make a connection. 190 :param read_timeout: For :py:class:`botocore.config.Config`. 191 The time in seconds till a timeout exception is thrown when attempting to read from a connection. 192 :param retries: For :py:class:`botocore.config.Config`. 193 A dictionary for configuration related to retry behavior. 194 :param s3: For :py:class:`botocore.config.Config`. 195 A dictionary of S3 specific configurations. 196 :param checksum_algorithm: Upload-only object integrity algorithm. 197 One of ``"CRC32"``, ``"CRC32C"``, ``"SHA1"``, ``"SHA256"``, ``"CRC64NVME"`` (case-insensitive). 198 When ``rust_client`` is enabled, only ``"SHA256"`` is accepted. 199 :param multipart_threshold: For :py:class:`boto3.s3.transfer.TransferConfig`. 200 The transfer size threshold for which multipart uploads, downloads, and copies will automatically be triggered. 201 :param max_concurrency: For :py:class:`boto3.s3.transfer.TransferConfig`. 202 The maximum number of threads that will be making requests to perform a transfer. 203 If ``use_threads`` is set to ``False``, the value provided is ignored as the transfer will only ever use the current thread. 204 :param multipart_chunksize: For :py:class:`boto3.s3.transfer.TransferConfig`. 205 The partition size of each part for a multipart transfer. 206 :param io_chunksize: For :py:class:`boto3.s3.transfer.TransferConfig`. 207 The max size of each chunk in the ``io`` queue. Currently, this is the size used when read is called on the downloaded stream as well. 208 Note: This value is ignored when resolved transfer manager type is CRTTransferManager. 209 """ 210 super().__init__( 211 base_path=base_path, 212 provider_name=PROVIDER, 213 config_dict=config_dict, 214 telemetry_provider=telemetry_provider, 215 ) 216 217 self._region_name = region_name 218 self._endpoint_url = endpoint_url 219 self._credentials_provider = credentials_provider 220 self._profile_name = profile_name 221 self._verify = verify 222 223 self._signature_version = kwargs.get("signature_version", "s3v4") 224 self._boto3_client: Any = None 225 self._s3_client_lock = threading.Lock() 226 self._s3_client_pid = os.getpid() 227 self._s3_client_options: dict[str, Any] = { 228 "request_checksum_calculation": kwargs.get("request_checksum_calculation"), 229 "response_checksum_validation": kwargs.get("response_checksum_validation"), 230 "max_pool_connections": kwargs.get("max_pool_connections", MAX_POOL_CONNECTIONS), 231 "connect_timeout": kwargs.get("connect_timeout", DEFAULT_CONNECT_TIMEOUT), 232 "read_timeout": kwargs.get("read_timeout", DEFAULT_READ_TIMEOUT), 233 "retries": kwargs.get("retries"), 234 "s3": kwargs.get("s3"), 235 } 236 if "rust_client" not in kwargs: 237 self._s3_client = self._create_s3_client(**self._s3_client_options) 238 self._transfer_config = TransferConfig( 239 multipart_threshold=int(kwargs.get("multipart_threshold", MULTIPART_THRESHOLD)), 240 max_concurrency=int(kwargs.get("max_concurrency", PYTHON_MAX_CONCURRENCY)), 241 multipart_chunksize=int(kwargs.get("multipart_chunksize", MULTIPART_CHUNKSIZE)), 242 io_chunksize=int(kwargs.get("io_chunksize", IO_CHUNKSIZE)), 243 use_threads=True, 244 ) 245 self._multipart_threshold = self._transfer_config.multipart_threshold 246 247 self._signer_cache: dict[tuple, URLSigner] = {} 248 249 self._checksum_algorithm: str | None = self._validate_checksum_algorithm(kwargs.get("checksum_algorithm")) 250 251 self._rust_client = None 252 self._rust_bucket: str | None = None 253 if "rust_client" in kwargs: 254 # Inherit the rust client options from the kwargs 255 rust_client_options = kwargs["rust_client"] 256 if "max_pool_connections" in kwargs: 257 rust_client_options["max_pool_connections"] = kwargs["max_pool_connections"] 258 if "max_concurrency" in kwargs: 259 rust_client_options["max_concurrency"] = kwargs["max_concurrency"] 260 if "multipart_chunksize" in kwargs: 261 rust_client_options["multipart_chunksize"] = kwargs["multipart_chunksize"] 262 if "read_timeout" in kwargs: 263 rust_client_options["read_timeout"] = kwargs["read_timeout"] 264 if "connect_timeout" in kwargs: 265 rust_client_options["connect_timeout"] = kwargs["connect_timeout"] 266 if "checksum_algorithm" in kwargs: 267 rust_client_options["checksum_algorithm"] = kwargs["checksum_algorithm"] 268 if self._signature_version == "UNSIGNED": 269 rust_client_options["skip_signature"] = True 270 271 # Rust client only supports SHA256 today (object_store limitation). 272 rust_checksum = rust_client_options.get("checksum_algorithm") 273 if rust_checksum is not None: 274 if str(rust_checksum).upper() != "SHA256": 275 raise ValueError( 276 f"Rust client only supports checksum_algorithm='SHA256' today " 277 f"(object_store limitation), got '{rust_checksum!r}'. " 278 f"Disable rust_client or use SHA256." 279 ) 280 rust_client_options["checksum_algorithm"] = "sha256" 281 self._rust_client = self._create_rust_client(rust_client_options) 282 283 @property 284 def _s3_client(self) -> Any: 285 if self._boto3_client is None: 286 if self._s3_client_pid != os.getpid(): 287 # A forked child cannot release a lock held by another parent thread. 288 self._s3_client_lock = threading.Lock() 289 self._s3_client_pid = os.getpid() 290 # Rust-only reads avoid loading a separate set of botocore models per backend. 291 with self._s3_client_lock: 292 if self._boto3_client is None: 293 self._boto3_client = self._create_s3_client(**self._s3_client_options) 294 return self._boto3_client 295 296 @_s3_client.setter 297 def _s3_client(self, client: Any) -> None: 298 self._boto3_client = client 299 300 @staticmethod 301 def _validate_checksum_algorithm(value: str | None) -> str | None: 302 """ 303 Normalizes the optional ``checksum_algorithm`` to uppercase, or returns ``None`` if disabled. 304 """ 305 if value is None: 306 return None 307 if not isinstance(value, str) or not value: 308 raise ValueError( 309 f"checksum_algorithm must be one of {sorted(SUPPORTED_CHECKSUM_ALGORITHMS)} or None, got {value!r}." 310 ) 311 normalized = value.upper() 312 if normalized not in SUPPORTED_CHECKSUM_ALGORITHMS: 313 raise ValueError( 314 f"Unsupported checksum_algorithm '{value}'. Supported: {sorted(SUPPORTED_CHECKSUM_ALGORITHMS)}." 315 ) 316 return normalized 317 318 def _open_streaming_writer( 319 self, path: str, attributes: dict[str, str] | None, options: StreamingWriterOptions 320 ) -> StreamingObjectWriter: 321 if self._rust_client is None: 322 raise NotImplementedError("Streaming writes require the Rust client (rust_client in the profile options).") 323 rust_client = self._rust_client 324 bucket, key = split_path(path) 325 if self._is_directory_bucket(bucket): 326 raise NotImplementedError(f"Streaming writes do not support S3 directory bucket {bucket}.") 327 if bucket != self._rust_bucket or not RustClient.supports_path(key): 328 raise NotImplementedError( 329 f"Streaming writes cannot represent {bucket}/{key} with the configured Rust client." 330 ) 331 validated_attributes = validate_attributes(attributes) 332 rust_attributes = {"attributes": validated_attributes} if validated_attributes else {} 333 native = self._translate_errors( 334 lambda: rust_client.open_streaming_writer( 335 key, 336 part_size=options.part_size_bytes, 337 max_inflight_parts=options.max_inflight_parts, 338 max_object_size=options.max_object_size_bytes, 339 **rust_attributes, 340 ), 341 operation="PUT", 342 bucket=bucket, 343 key=key, 344 ) 345 return RustStreamingWriter( 346 native, 347 translate_errors=functools.partial(self._translate_errors, operation="PUT", bucket=bucket, key=key), 348 emit_write_metrics=functools.partial(self._emit_metrics, BaseStorageProvider._Operation.WRITE), 349 ) 350 351 def _is_directory_bucket(self, bucket: str) -> bool: 352 """ 353 Determines if the bucket is a directory bucket based on bucket name. 354 """ 355 # S3 Express buckets have a specific naming convention 356 return "--x-s3" in bucket 357 358 def _create_s3_client( 359 self, 360 request_checksum_calculation: str | None = None, 361 response_checksum_validation: str | None = None, 362 max_pool_connections: int = MAX_POOL_CONNECTIONS, 363 connect_timeout: float | None = None, 364 read_timeout: float | None = None, 365 retries: dict[str, Any] | None = None, 366 s3: dict[str, Any] | None = None, 367 ): 368 """ 369 Creates and configures the boto3 S3 client, using refreshable credentials if possible. 370 371 :param request_checksum_calculation: For :py:class:`botocore.config.Config`. When the underlying S3 client should calculate request checksums. See the equivalent option in the `AWS configuration file <https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html#using-a-configuration-file>`_. 372 :param response_checksum_validation: For :py:class:`botocore.config.Config`. When the underlying S3 client should validate response checksums. See the equivalent option in the `AWS configuration file <https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html#using-a-configuration-file>`_. 373 :param max_pool_connections: For :py:class:`botocore.config.Config`. The maximum number of connections to keep in a connection pool. 374 :param connect_timeout: For :py:class:`botocore.config.Config`. The time in seconds till a timeout exception is thrown when attempting to make a connection. 375 :param read_timeout: For :py:class:`botocore.config.Config`. The time in seconds till a timeout exception is thrown when attempting to read from a connection. 376 :param retries: For :py:class:`botocore.config.Config`. A dictionary for configuration related to retry behavior. 377 :param s3: For :py:class:`botocore.config.Config`. A dictionary of S3 specific configurations. 378 379 :return: The configured S3 client. 380 """ 381 options = { 382 # https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html 383 "config": boto3.session.Config( # pyright: ignore [reportAttributeAccessIssue] 384 max_pool_connections=max_pool_connections, 385 connect_timeout=connect_timeout, 386 read_timeout=read_timeout, 387 retries=retries or {"mode": "standard"}, 388 request_checksum_calculation=request_checksum_calculation, 389 response_checksum_validation=response_checksum_validation, 390 s3=s3, 391 ), 392 } 393 394 if self._region_name: 395 options["region_name"] = self._region_name 396 397 if self._endpoint_url: 398 options["endpoint_url"] = self._endpoint_url 399 400 if self._verify is not None: 401 options["verify"] = self._verify 402 403 if self._signature_version: 404 signature_config = botocore.config.Config( # pyright: ignore[reportAttributeAccessIssue] 405 signature_version=botocore.UNSIGNED 406 if self._signature_version == "UNSIGNED" 407 else self._signature_version 408 ) 409 options["config"] = options["config"].merge(signature_config) 410 411 if self._credentials_provider: 412 creds = self._fetch_credentials() 413 if creds.get("expiry_time"): 414 # Use RefreshableCredentials if expiry_time provided. 415 refreshable_credentials = RefreshableCredentials.create_from_metadata( 416 metadata=creds, refresh_using=self._fetch_credentials, method="custom-refresh" 417 ) 418 419 botocore_session = get_session() 420 botocore_session._credentials = refreshable_credentials 421 422 boto3_session = boto3.Session(botocore_session=botocore_session) 423 424 return boto3_session.client("s3", **options) 425 else: 426 # Add static credentials to the options dictionary 427 options["aws_access_key_id"] = creds["access_key"] 428 options["aws_secret_access_key"] = creds["secret_key"] 429 if creds["token"]: 430 options["aws_session_token"] = creds["token"] 431 432 # Fallback to standard credential chain. 433 session = boto3.Session(profile_name=self._profile_name) 434 return session.client("s3", **options) 435 436 def _create_rust_client(self, rust_client_options: dict[str, Any] | None = None): 437 """ 438 Creates and configures the rust client, using refreshable credentials if possible. 439 """ 440 configs = dict(rust_client_options) if rust_client_options else {} 441 442 # Extract and parse retry configuration 443 retry_config = parse_retry_config(configs) 444 445 if self._region_name and "region_name" not in configs: 446 configs["region_name"] = self._region_name 447 448 if self._endpoint_url and "endpoint_url" not in configs: 449 configs["endpoint_url"] = self._endpoint_url 450 451 if self._profile_name and "profile_name" not in configs: 452 configs["profile_name"] = self._profile_name 453 454 # If the user specifies a bucket, use it. Otherwise, use the base path. 455 if "bucket" not in configs: 456 bucket, _ = split_path(self._base_path) 457 configs["bucket"] = bucket 458 self._rust_bucket = configs["bucket"] 459 460 if "max_pool_connections" not in configs: 461 configs["max_pool_connections"] = MAX_POOL_CONNECTIONS 462 463 return RustClient( 464 provider=PROVIDER, 465 configs=configs, 466 credentials_provider=self._credentials_provider, 467 retry=retry_config, 468 ) 469 470 def _fetch_credentials(self) -> dict: 471 """ 472 Refreshes the S3 client if the current credentials are expired. 473 """ 474 if not self._credentials_provider: 475 raise RuntimeError("Cannot fetch credentials if no credential provider configured.") 476 self._credentials_provider.refresh_credentials() 477 credentials = self._credentials_provider.get_credentials() 478 return { 479 "access_key": credentials.access_key, 480 "secret_key": credentials.secret_key, 481 "token": credentials.token, 482 "expiry_time": credentials.expiration, 483 } 484 485 def _translate_errors( 486 self, 487 func: Callable[[], _T], 488 operation: str, 489 bucket: str, 490 key: str, 491 ) -> _T: 492 """ 493 Translates errors like timeouts and client errors. 494 495 :param func: The function that performs the actual S3 operation. 496 :param operation: The type of operation being performed (e.g., "PUT", "GET", "DELETE"). 497 :param bucket: The name of the S3 bucket involved in the operation. 498 :param key: The key of the object within the S3 bucket. 499 500 :return: The result of the S3 operation, typically the return value of the `func` callable. 501 """ 502 try: 503 return func() 504 except ClientError as error: 505 status_code = error.response["ResponseMetadata"]["HTTPStatusCode"] 506 request_id = error.response["ResponseMetadata"].get("RequestId") 507 host_id = error.response["ResponseMetadata"].get("HostId") 508 error_code = error.response["Error"]["Code"] 509 error_info = f"request_id: {request_id}, host_id: {host_id}, status_code: {status_code}" 510 511 if status_code == 404: 512 if error_code == "NoSuchUpload": 513 error_message = error.response["Error"]["Message"] 514 raise RetryableError(f"Multipart upload failed for {bucket}/{key}: {error_message}") from error 515 raise FileNotFoundError(f"Object {bucket}/{key} does not exist. {error_info}") # pylint: disable=raise-missing-from 516 elif status_code == 403: 517 raise PermissionError( 518 f"Permission denied to {operation} object(s) at {bucket}/{key}. {error_info}" 519 ) from error 520 elif status_code == 412: # Precondition Failed 521 raise PreconditionFailedError( 522 f"ETag mismatch for {operation} operation on {bucket}/{key}. {error_info}" 523 ) from error 524 elif status_code == 429: 525 raise RetryableError( 526 f"Too many request to {operation} object(s) at {bucket}/{key}. {error_info}" 527 ) from error 528 elif status_code == 503: 529 raise RetryableError( 530 f"Service unavailable when {operation} object(s) at {bucket}/{key}. {error_info}" 531 ) from error 532 elif status_code == 501: 533 raise NotImplementedError( 534 f"Operation {operation} not implemented for object(s) at {bucket}/{key}. {error_info}" 535 ) from error 536 elif status_code == 408: 537 # 408 Request Timeout is from Google Cloud Storage 538 raise RetryableError( 539 f"Request timeout when {operation} object(s) at {bucket}/{key}. {error_info}" 540 ) from error 541 else: 542 raise RuntimeError( 543 f"Failed to {operation} object(s) at {bucket}/{key}. {error_info}, " 544 f"error_type: {type(error).__name__}" 545 ) from error 546 except RustClientError as error: 547 message = error.args[0] 548 status_code = error.args[1] 549 if status_code == 404: 550 raise FileNotFoundError(f"Object {bucket}/{key} does not exist. {message}") from error 551 elif status_code == 403: 552 raise PermissionError( 553 f"Permission denied to {operation} object(s) at {bucket}/{key}. {message}" 554 ) from error 555 else: 556 raise RetryableError( 557 f"Failed to {operation} object(s) at {bucket}/{key}. {message}. status_code: {status_code}" 558 ) from error 559 except (ReadTimeoutError, IncompleteReadError, ResponseStreamingError) as error: 560 raise RetryableError( 561 f"Failed to {operation} object(s) at {bucket}/{key} due to network timeout or incomplete read. " 562 f"error_type: {type(error).__name__}" 563 ) from error 564 except RustRetryableError as error: 565 raise RetryableError( 566 f"Failed to {operation} object(s) at {bucket}/{key} due to retryable error from Rust. " 567 f"error_type: {type(error).__name__}" 568 ) from error 569 except Exception as error: 570 if ( 571 isinstance(error, S3UploadFailedError) 572 and isinstance(error.__context__, ClientError) 573 and error.__context__.response["ResponseMetadata"]["HTTPStatusCode"] == 403 574 ): 575 raise PermissionError( 576 f"Permission denied to {operation} object(s) at {bucket}/{key}. {error}" 577 ) from error 578 raise RuntimeError( 579 f"Failed to {operation} object(s) at {bucket}/{key}, error type: {type(error).__name__}, error: {error}" 580 ) from error 581 582 def _put_object( 583 self, 584 path: str, 585 body: bytes, 586 if_match: str | None = None, 587 if_none_match: str | None = None, 588 attributes: dict[str, str] | None = None, 589 content_type: str | None = None, 590 ) -> int: 591 """ 592 Uploads an object to the specified S3 path. 593 594 :param path: The S3 path where the object will be uploaded. 595 :param body: The content of the object as bytes. 596 :param if_match: Optional If-Match header value. Use "*" to only upload if the object doesn't exist. 597 :param if_none_match: Optional If-None-Match header value. Use "*" to only upload if the object doesn't exist. 598 :param attributes: Optional attributes to attach to the object. 599 :param content_type: Optional Content-Type header value. 600 """ 601 bucket, key = split_path(path) 602 603 def _invoke_api() -> int: 604 kwargs = {"Bucket": bucket, "Key": key, "Body": body} 605 if content_type: 606 kwargs["ContentType"] = content_type 607 if self._is_directory_bucket(bucket): 608 kwargs["StorageClass"] = EXPRESS_ONEZONE_STORAGE_CLASS 609 if if_match: 610 kwargs["IfMatch"] = if_match 611 if if_none_match: 612 kwargs["IfNoneMatch"] = if_none_match 613 validated_attributes = validate_attributes(attributes) 614 if validated_attributes: 615 kwargs["Metadata"] = validated_attributes 616 617 # TODO(NGCDP-5804): Add support to update ContentType header in Rust client 618 rust_unsupported_feature_keys = {"StorageClass", "IfMatch", "IfNoneMatch", "ContentType"} 619 if ( 620 self._rust_client 621 # Rust client doesn't support creating objects with trailing /, see https://github.com/apache/arrow-rs/issues/7026 622 and not path.endswith("/") 623 and all(key not in kwargs for key in rust_unsupported_feature_keys) 624 ): 625 rust_attributes = {"attributes": validated_attributes} if validated_attributes else {} 626 run_async_rust_client_method(self._rust_client, "put", key, body, **rust_attributes) 627 else: 628 if self._checksum_algorithm: 629 kwargs["ChecksumAlgorithm"] = self._checksum_algorithm 630 self._s3_client.put_object(**kwargs) 631 632 return len(body) 633 634 return self._translate_errors(_invoke_api, operation="PUT", bucket=bucket, key=key) 635 636 def _supports_suffix_range(self) -> bool: 637 return self._rust_client is None 638 639 def _get_object(self, path: str, byte_range: Range | SuffixRange | None = None) -> bytes: 640 bucket, key = split_path(path) 641 642 if isinstance(byte_range, SuffixRange): 643 suffix_range = byte_range 644 645 def _invoke_suffix_api() -> bytes | None: 646 try: 647 response = self._s3_client.get_object(Bucket=bucket, Key=key, Range=f"bytes=-{suffix_range.size}") 648 except ClientError as error: 649 # Raised for empty objects, or by servers without suffix range support. 650 if error.response["ResponseMetadata"]["HTTPStatusCode"] == 416: 651 return None 652 raise 653 # Servers may ignore the range and return the whole object. 654 return response["Body"].read()[-suffix_range.size :] 655 656 return self._get_object_suffix( 657 path, 658 suffix_range, 659 lambda: self._translate_errors(_invoke_suffix_api, operation="GET", bucket=bucket, key=key), 660 ) 661 662 def _invoke_api() -> bytes: 663 if byte_range: 664 bytes_range = f"bytes={byte_range.offset}-{byte_range.offset + byte_range.size - 1}" 665 if self._rust_client: 666 response = run_async_rust_client_method( 667 self._rust_client, 668 "get", 669 key, 670 byte_range, 671 ) 672 return response 673 else: 674 response = self._s3_client.get_object(Bucket=bucket, Key=key, Range=bytes_range) 675 else: 676 if self._rust_client: 677 response = run_async_rust_client_method(self._rust_client, "get", key) 678 return response 679 else: 680 response = self._s3_client.get_object(Bucket=bucket, Key=key) 681 682 return response["Body"].read() 683 684 return self._translate_errors(_invoke_api, operation="GET", bucket=bucket, key=key) 685 686 def _copy_object(self, src_path: str, dest_path: str) -> int: 687 src_bucket, src_key = split_path(src_path) 688 dest_bucket, dest_key = split_path(dest_path) 689 690 src_object = self._get_object_metadata(src_path) 691 692 def _invoke_api() -> int: 693 self._s3_client.copy( 694 CopySource={"Bucket": src_bucket, "Key": src_key}, 695 Bucket=dest_bucket, 696 Key=dest_key, 697 Config=self._transfer_config, 698 ) 699 700 return src_object.content_length 701 702 return self._translate_errors(_invoke_api, operation="COPY", bucket=dest_bucket, key=dest_key) 703 704 def _delete_object(self, path: str, if_match: str | None = None) -> None: 705 bucket, key = split_path(path) 706 707 def _invoke_api() -> None: 708 # Delete conditionally when if_match (etag) is provided; otherwise delete unconditionally 709 if if_match: 710 self._s3_client.delete_object(Bucket=bucket, Key=key, IfMatch=if_match) 711 else: 712 self._s3_client.delete_object(Bucket=bucket, Key=key) 713 714 return self._translate_errors(_invoke_api, operation="DELETE", bucket=bucket, key=key) 715 716 def _delete_objects(self, paths: list[str]) -> None: 717 if not paths: 718 return 719 720 by_bucket: dict[str, list[str]] = {} 721 for p in paths: 722 bucket, key = split_path(p) 723 by_bucket.setdefault(bucket, []).append(key) 724 725 S3_BATCH_LIMIT = 1000 726 727 def _invoke_api() -> None: 728 all_errors: list[str] = [] 729 for bucket, keys in by_bucket.items(): 730 for i in range(0, len(keys), S3_BATCH_LIMIT): 731 chunk = keys[i : i + S3_BATCH_LIMIT] 732 response = self._s3_client.delete_objects( 733 Bucket=bucket, Delete={"Objects": [{"Key": k} for k in chunk]} 734 ) 735 errors = response.get("Errors") or [] 736 for e in errors: 737 all_errors.append(f"{bucket}/{e.get('Key', '?')}: {e.get('Code', '')} {e.get('Message', '')}") 738 if all_errors: 739 raise RuntimeError(f"DeleteObjects reported errors: {'; '.join(all_errors)}") 740 741 bucket_desc = "(" + "|".join(by_bucket) + ")" 742 key_desc = "(" + "|".join(str(len(keys)) for keys in by_bucket.values()) + " keys)" 743 self._translate_errors(_invoke_api, operation="DELETE_MANY", bucket=bucket_desc, key=key_desc) 744 745 def _can_use_rust_metadata(self, bucket: str, key: str) -> bool: 746 # S3 keys must retain segments that the Rust store rejects or strips. 747 return ( 748 self._rust_client is not None 749 and self._verify is None 750 and bucket == self._rust_bucket 751 and not self._is_directory_bucket(bucket) 752 and RustClient.supports_path(key) 753 ) 754 755 def _is_dir(self, path: str) -> bool: 756 # Ensure the path ends with '/' to mimic a directory 757 path = self._append_delimiter(path) 758 759 bucket, key = split_path(path) 760 761 def _invoke_api() -> bool: 762 if self._can_use_rust_metadata(bucket, key.removesuffix("/")): 763 try: 764 return run_async_rust_client_method(self._rust_client, "is_dir", key) 765 except ValueError: 766 # A valid prefix can contain children whose keys Rust cannot represent. 767 pass 768 # List objects with the given prefix 769 response = self._s3_client.list_objects_v2(Bucket=bucket, Prefix=key, MaxKeys=1, Delimiter="/") 770 771 # Check if there are any contents or common prefixes 772 return bool(response.get("Contents", []) or response.get("CommonPrefixes", [])) 773 774 return self._translate_errors(_invoke_api, operation="LIST", bucket=bucket, key=key) 775 776 def _make_symlink(self, path: str, target: str) -> None: 777 bucket, key = split_path(path) 778 target_bucket, target_key = split_path(target) 779 if bucket != target_bucket: 780 raise ValueError(f"Cannot create cross-bucket symlink: '{bucket}' -> '{target_bucket}'.") 781 relative_target = ObjectMetadata.encode_symlink_target(key, target_key) 782 783 def _invoke_api() -> None: 784 self._s3_client.put_object( 785 Bucket=bucket, 786 Key=key, 787 Body=b"", 788 Metadata={"msc-symlink-target": relative_target}, 789 ) 790 791 self._translate_errors(_invoke_api, operation="PUT", bucket=bucket, key=key) 792 793 def _get_object_metadata(self, path: str, strict: bool = True) -> ObjectMetadata: 794 bucket, key = split_path(path) 795 if path.endswith("/") or (bucket and not key): 796 # If path ends with "/" or empty key name is provided, then assume it's a "directory", 797 # which metadata is not guaranteed to exist for cases such as 798 # "virtual prefix" that was never explicitly created. 799 if self._is_dir(path): 800 return ObjectMetadata( 801 key=path, 802 type="directory", 803 content_length=0, 804 last_modified=AWARE_DATETIME_MIN, 805 ) 806 else: 807 raise FileNotFoundError(f"Directory {path} does not exist.") 808 else: 809 810 def _invoke_api() -> ObjectMetadata: 811 if self._can_use_rust_metadata(bucket, key): 812 result = run_async_rust_client_method(self._rust_client, "head", key) 813 object_metadata = result.object_metadata 814 return ObjectMetadata( 815 key=path, 816 type="file", 817 content_length=object_metadata.content_length, 818 content_type=result.content_type, 819 last_modified=dateutil_parse(object_metadata.last_modified), 820 etag=object_metadata.etag.strip('"') if object_metadata.etag is not None else None, 821 storage_class=result.storage_class, 822 metadata=result.metadata, 823 symlink_target=result.metadata.get("msc-symlink-target"), 824 ) 825 response = self._s3_client.head_object(Bucket=bucket, Key=key) 826 user_metadata = response.get("Metadata") 827 symlink_target = user_metadata.get("msc-symlink-target") if user_metadata else None 828 829 return ObjectMetadata( 830 key=path, 831 type="file", 832 content_length=response["ContentLength"], 833 content_type=response.get("ContentType"), 834 last_modified=response.get("LastModified", AWARE_DATETIME_MIN), 835 etag=response["ETag"].strip('"') if "ETag" in response else None, 836 storage_class=response.get("StorageClass"), 837 metadata=user_metadata, 838 symlink_target=symlink_target, 839 ) 840 841 try: 842 return self._translate_errors(_invoke_api, operation="HEAD", bucket=bucket, key=key) 843 except FileNotFoundError: 844 if strict: 845 # If the object does not exist on the given path, we will append a trailing slash and 846 # check if the path is a directory. 847 path = self._append_delimiter(path) 848 if self._is_dir(path): 849 return ObjectMetadata( 850 key=path, 851 type="directory", 852 content_length=0, 853 last_modified=AWARE_DATETIME_MIN, 854 ) 855 raise 856 857 def _list_objects( 858 self, 859 path: str, 860 start_after: str | None = None, 861 end_at: str | None = None, 862 include_directories: bool = False, 863 symlink_handling: SymlinkHandling = SymlinkHandling.FOLLOW, 864 ) -> Iterator[ObjectMetadata]: 865 bucket, prefix = split_path(path) 866 867 # Get the prefix of the start_after and end_at paths relative to the bucket. 868 if start_after: 869 _, start_after = split_path(start_after) 870 if end_at: 871 _, end_at = split_path(end_at) 872 873 def _invoke_api() -> Iterator[ObjectMetadata]: 874 paginator = self._s3_client.get_paginator("list_objects_v2") 875 if include_directories: 876 page_iterator = paginator.paginate( 877 Bucket=bucket, Prefix=prefix, Delimiter="/", StartAfter=(start_after or "") 878 ) 879 else: 880 page_iterator = paginator.paginate(Bucket=bucket, Prefix=prefix, StartAfter=(start_after or "")) 881 882 for page in page_iterator: 883 # A page holds both CommonPrefixes and Contents for the same key window, so a prefix past 884 # end_at must not stop the listing before the page's objects have been processed. 885 past_end_at = False 886 for item in page.get("CommonPrefixes", []): 887 prefix_key = item["Prefix"].rstrip("/") 888 # Filter by start_after and end_at - S3's StartAfter doesn't filter CommonPrefixes 889 if (start_after is None or start_after < prefix_key) and (end_at is None or prefix_key <= end_at): 890 yield ObjectMetadata( 891 key=os.path.join(bucket, prefix_key), 892 type="directory", 893 content_length=0, 894 last_modified=AWARE_DATETIME_MIN, 895 ) 896 elif end_at is not None and end_at < prefix_key: 897 past_end_at = True 898 break 899 900 # S3 guarantees lexicographical order for general purpose buckets (for 901 # normal S3) but not directory buckets (for S3 Express One Zone). 902 for response_object in page.get("Contents", []): 903 key = response_object["Key"] 904 if end_at is None or key <= end_at: 905 if key.endswith("/"): 906 if include_directories: 907 yield ObjectMetadata( 908 key=os.path.join(bucket, key.rstrip("/")), 909 type="directory", 910 content_length=0, 911 last_modified=response_object["LastModified"], 912 ) 913 else: 914 symlink_target = None 915 if response_object.get("Size", 0) == 0: 916 try: 917 meta = self._get_object_metadata(os.path.join(bucket, key)) 918 symlink_target = meta.symlink_target 919 except Exception: 920 symlink_target = None 921 yield ObjectMetadata( 922 key=os.path.join(bucket, key), 923 type="file", 924 content_length=response_object["Size"], 925 last_modified=response_object["LastModified"], 926 etag=response_object["ETag"].strip('"'), 927 storage_class=response_object.get("StorageClass"), 928 symlink_target=symlink_target, 929 ) 930 else: 931 return 932 933 if past_end_at: 934 return 935 936 return _translate_iterator_errors( 937 _invoke_api(), lambda f: self._translate_errors(f, operation="LIST", bucket=bucket, key=prefix) 938 ) 939 940 @property 941 def supports_parallel_listing(self) -> bool: 942 """ 943 S3 supports parallel listing via delimiter-based prefix discovery. 944 945 Note: Directory bucket handling is done in list_objects_recursive(). 946 """ 947 return True 948
[docs] 949 def list_objects_recursive( 950 self, 951 path: str = "", 952 start_after: str | None = None, 953 end_at: str | None = None, 954 max_workers: int = 32, 955 look_ahead: int = 2, 956 symlink_handling: SymlinkHandling = SymlinkHandling.FOLLOW, 957 ) -> Iterator[ObjectMetadata]: 958 """ 959 List all objects recursively using parallel prefix discovery for improved performance. 960 961 For S3, uses the Rust client's list_recursive when available for maximum performance. 962 Falls back to Python implementation otherwise. 963 964 Returns files only (no directories), in lexicographic order. 965 966 :param symlink_handling: How to handle symbolic links during listing. 967 """ 968 if (start_after is not None) and (end_at is not None) and not (start_after < end_at): 969 raise ValueError(f"start_after ({start_after}) must be before end_at ({end_at})!") 970 971 full_path = self._prepend_base_path(path) 972 bucket, _ = split_path(full_path) 973 974 if self._is_directory_bucket(bucket): 975 yield from self.list_objects( 976 path, start_after, end_at, include_directories=False, symlink_handling=symlink_handling 977 ) 978 return 979 980 if self._rust_client: 981 yield from self._emit_metrics( 982 operation=BaseStorageProvider._Operation.LIST, 983 f=lambda: self._list_objects_recursive_rust(path, full_path, bucket, start_after, end_at, max_workers), 984 ) 985 else: 986 yield from super().list_objects_recursive( 987 path, start_after, end_at, max_workers, look_ahead, symlink_handling 988 )
989 990 def _list_objects_recursive_rust( 991 self, 992 path: str, 993 full_path: str, 994 bucket: str, 995 start_after: str | None, 996 end_at: str | None, 997 max_workers: int, 998 ) -> Iterator[ObjectMetadata]: 999 """ 1000 Use Rust client's list_recursive for parallel listing. 1001 1002 The Rust client already handles parallel listing internally. 1003 Returns files only in lexicographic order. 1004 """ 1005 _, prefix = split_path(full_path) 1006 1007 def _invoke_api() -> Iterator[ObjectMetadata]: 1008 result = run_async_rust_client_method( 1009 self._rust_client, 1010 "list_recursive", 1011 [prefix] if prefix else [""], 1012 max_concurrency=max_workers, 1013 ) 1014 1015 start_after_full = self._prepend_base_path(start_after) if start_after else None 1016 end_at_full = self._prepend_base_path(end_at) if end_at else None 1017 1018 for obj in result.objects: 1019 full_key = os.path.join(bucket, obj.key) 1020 1021 if start_after_full and full_key <= start_after_full: 1022 continue 1023 if end_at_full and full_key > end_at_full: 1024 break 1025 1026 relative_key = full_key.removeprefix(self._base_path).lstrip("/") 1027 1028 yield ObjectMetadata( 1029 key=relative_key, 1030 content_length=obj.content_length, 1031 last_modified=dateutil_parse(obj.last_modified), 1032 type="file" if obj.object_type == "object" else obj.object_type, 1033 etag=obj.etag, 1034 ) 1035 1036 yield from _translate_iterator_errors( 1037 _invoke_api(), lambda f: self._translate_errors(f, operation="LIST", bucket=bucket, key=prefix) 1038 ) 1039 1040 def _upload_file( 1041 self, 1042 remote_path: str, 1043 f: str | IO, 1044 attributes: dict[str, str] | None = None, 1045 content_type: str | None = None, 1046 ) -> int: 1047 file_size: int = 0 1048 1049 if isinstance(f, str): 1050 bucket, key = split_path(remote_path) 1051 file_size = os.path.getsize(f) 1052 1053 # Upload small files 1054 if file_size <= self._multipart_threshold: 1055 if self._rust_client and not content_type and not self._is_directory_bucket(bucket): 1056 validated_attributes = validate_attributes(attributes) 1057 rust_attributes = {"attributes": validated_attributes} if validated_attributes else {} 1058 self._translate_errors( 1059 lambda: run_async_rust_client_method(self._rust_client, "upload", f, key, **rust_attributes), 1060 operation="PUT", 1061 bucket=bucket, 1062 key=key, 1063 ) 1064 else: 1065 with open(f, "rb") as fp: 1066 self._put_object(remote_path, fp.read(), attributes=attributes, content_type=content_type) 1067 return file_size 1068 1069 # Upload large files using TransferConfig 1070 def _invoke_api() -> int: 1071 extra_args = {} 1072 if content_type: 1073 extra_args["ContentType"] = content_type 1074 if self._is_directory_bucket(bucket): 1075 extra_args["StorageClass"] = EXPRESS_ONEZONE_STORAGE_CLASS 1076 validated_attributes = validate_attributes(attributes) 1077 if validated_attributes: 1078 extra_args["Metadata"] = validated_attributes 1079 if self._rust_client and "ContentType" not in extra_args and "StorageClass" not in extra_args: 1080 rust_attributes = {"attributes": validated_attributes} if validated_attributes else {} 1081 run_async_rust_client_method( 1082 self._rust_client, "upload_multipart_from_file", f, key, **rust_attributes 1083 ) 1084 else: 1085 if self._checksum_algorithm: 1086 extra_args["ChecksumAlgorithm"] = self._checksum_algorithm 1087 self._s3_client.upload_file( 1088 Filename=f, 1089 Bucket=bucket, 1090 Key=key, 1091 Config=self._transfer_config, 1092 ExtraArgs=extra_args, 1093 ) 1094 1095 return file_size 1096 1097 return self._translate_errors(_invoke_api, operation="PUT", bucket=bucket, key=key) 1098 else: 1099 # Upload small files 1100 f.seek(0, io.SEEK_END) 1101 file_size = f.tell() 1102 f.seek(0) 1103 1104 if file_size <= self._multipart_threshold: 1105 if isinstance(f, io.StringIO): 1106 self._put_object( 1107 remote_path, f.read().encode("utf-8"), attributes=attributes, content_type=content_type 1108 ) 1109 else: 1110 self._put_object(remote_path, f.read(), attributes=attributes, content_type=content_type) 1111 return file_size 1112 1113 # Upload large files using TransferConfig 1114 bucket, key = split_path(remote_path) 1115 1116 def _invoke_api() -> int: 1117 extra_args = {} 1118 if content_type: 1119 extra_args["ContentType"] = content_type 1120 if self._is_directory_bucket(bucket): 1121 extra_args["StorageClass"] = EXPRESS_ONEZONE_STORAGE_CLASS 1122 validated_attributes = validate_attributes(attributes) 1123 if validated_attributes: 1124 extra_args["Metadata"] = validated_attributes 1125 1126 if ( 1127 self._rust_client 1128 and isinstance(f, io.BytesIO) 1129 and "ContentType" not in extra_args 1130 and "StorageClass" not in extra_args 1131 ): 1132 data = f.getbuffer() 1133 rust_attributes = {"attributes": validated_attributes} if validated_attributes else {} 1134 try: 1135 run_async_rust_client_method( 1136 self._rust_client, "upload_multipart_from_bytes", key, data, **rust_attributes 1137 ) 1138 finally: 1139 data.release() 1140 else: 1141 if self._checksum_algorithm: 1142 extra_args["ChecksumAlgorithm"] = self._checksum_algorithm 1143 self._s3_client.upload_fileobj( 1144 Fileobj=f, 1145 Bucket=bucket, 1146 Key=key, 1147 Config=self._transfer_config, 1148 ExtraArgs=extra_args, 1149 ) 1150 1151 return file_size 1152 1153 return self._translate_errors(_invoke_api, operation="PUT", bucket=bucket, key=key) 1154 1155 def _download_file(self, remote_path: str, f: str | IO, metadata: ObjectMetadata | None = None) -> int: 1156 """ 1157 Downloads an object to a local path or file-like object. 1158 1159 Python downloads to paths stage data in a temporary file and replace the destination only after the transfer 1160 succeeds. Transfer or rename failures preserve the existing destination and trigger best-effort cleanup of the 1161 staging file. Cleanup failures are logged without masking the original error. Rust downloads use the Rust 1162 client's destination and resumable state handling. 1163 1164 :param remote_path: The object path to download. 1165 :param f: The destination file path or writable file-like object. 1166 :param metadata: Optional object metadata to avoid an additional lookup. 1167 :return: The downloaded object's content length. 1168 """ 1169 if metadata is None: 1170 metadata = self._get_object_metadata(remote_path) 1171 1172 if isinstance(f, str): 1173 bucket, key = split_path(remote_path) 1174 if os.path.dirname(f): 1175 safe_makedirs(os.path.dirname(f)) 1176 1177 # Download small files 1178 if metadata.content_length <= self._multipart_threshold: 1179 if self._rust_client: 1180 self._translate_errors( 1181 lambda: run_async_rust_client_method(self._rust_client, "download", key, f), 1182 operation="GET", 1183 bucket=bucket, 1184 key=key, 1185 ) 1186 else: 1187 temp_file_path: str | None = None 1188 try: 1189 with tempfile.NamedTemporaryFile( 1190 mode="wb", delete=False, dir=os.path.dirname(f), prefix="." 1191 ) as fp: 1192 temp_file_path = fp.name 1193 fp.write(self._get_object(remote_path)) 1194 os.rename(src=temp_file_path, dst=f) 1195 finally: 1196 if temp_file_path: 1197 try: 1198 os.unlink(temp_file_path) 1199 except FileNotFoundError: 1200 pass 1201 except OSError as error: 1202 logger.warning("Could not remove temporary file %s: %s", temp_file_path, error) 1203 return metadata.content_length 1204 1205 # Download large files using TransferConfig 1206 def _invoke_api() -> int: 1207 if self._rust_client: 1208 run_async_rust_client_method(self._rust_client, "download_multipart_to_file", key, f) 1209 else: 1210 temp_file_path: str | None = None 1211 try: 1212 with tempfile.NamedTemporaryFile( 1213 mode="wb", delete=False, dir=os.path.dirname(f), prefix="." 1214 ) as fp: 1215 temp_file_path = fp.name 1216 self._s3_client.download_fileobj( 1217 Bucket=bucket, 1218 Key=key, 1219 Fileobj=fp, 1220 Config=self._transfer_config, 1221 ) 1222 os.rename(src=temp_file_path, dst=f) 1223 finally: 1224 if temp_file_path: 1225 try: 1226 os.unlink(temp_file_path) 1227 except FileNotFoundError: 1228 pass 1229 except OSError as error: 1230 logger.warning("Could not remove temporary file %s: %s", temp_file_path, error) 1231 1232 return metadata.content_length 1233 1234 return self._translate_errors(_invoke_api, operation="GET", bucket=bucket, key=key) 1235 else: 1236 # Download small files 1237 if metadata.content_length <= self._multipart_threshold: 1238 response = self._get_object(remote_path) 1239 # Decode Python bytes and Rust buffers without an intermediate Python bytes copy. 1240 if isinstance(f, io.StringIO): 1241 f.write(_decode_buffer(response)) 1242 else: 1243 f.write(response) 1244 return metadata.content_length 1245 1246 # Download large files using TransferConfig 1247 bucket, key = split_path(remote_path) 1248 1249 def _invoke_api() -> int: 1250 self._s3_client.download_fileobj( 1251 Bucket=bucket, 1252 Key=key, 1253 Fileobj=f, 1254 Config=self._transfer_config, 1255 ) 1256 1257 return metadata.content_length 1258 1259 return self._translate_errors(_invoke_api, operation="GET", bucket=bucket, key=key) 1260 1261 def _generate_presigned_url( 1262 self, 1263 path: str, 1264 *, 1265 method: str = "GET", 1266 signer_type: SignerType | None = None, 1267 signer_options: dict[str, Any] | None = None, 1268 ) -> str: 1269 options = signer_options or {} 1270 bucket, key = split_path(path) 1271 1272 if signer_type is None or signer_type == SignerType.S3: 1273 expires_in = int(options.get("expires_in", DEFAULT_PRESIGN_EXPIRES_IN)) 1274 cache_key: tuple = (SignerType.S3, bucket, expires_in) 1275 if cache_key not in self._signer_cache: 1276 self._signer_cache[cache_key] = S3URLSigner(self._s3_client, bucket, expires_in=expires_in) 1277 elif signer_type == SignerType.CLOUDFRONT: 1278 cache_key = (SignerType.CLOUDFRONT, frozenset(options.items())) 1279 if cache_key not in self._signer_cache: 1280 self._signer_cache[cache_key] = CloudFrontURLSigner(**options) 1281 else: 1282 raise ValueError(f"Unsupported signer type for S3 provider: {signer_type!r}") 1283 1284 return self._signer_cache[cache_key].generate_presigned_url(key, method=method)