Source code for multistorageclient.providers.s8k

  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 mimetypes
 17from typing import IO
 18
 19from ..types import StreamingObjectWriter, StreamingWriterOptions
 20from .s3 import S3StorageProvider
 21
 22PROVIDER = "s8k"
 23
 24
[docs] 25class S8KStorageProvider(S3StorageProvider): 26 """ 27 A concrete implementation of the :py:class:`multistorageclient.types.StorageProvider` for interacting with SwiftStack. 28 29 This provider extends S3StorageProvider with SwiftStack-specific features: 30 31 - Legacy retry mode for handling HTTP 429 errors 32 - Optional content type inference from file extensions 33 34 :param infer_content_type: When True, automatically infers MIME types from file extensions during upload operations. 35 For example, ``.wav`` files are uploaded with ``Content-Type: audio/x-wav``, enabling browsers to play 36 media files inline rather than downloading them. Uses Python's built-in ``mimetypes`` module for inference. 37 Default is False. Only affects write operations (``upload_file``, ``write``, ``put_object``). 38 39 .. note:: 40 This provider inherits all parameters from :py:class:`multistorageclient.providers.s3.S3StorageProvider`. 41 See the S3 provider documentation for additional configuration options like ``region_name``, ``endpoint_url``, 42 ``base_path``, ``credentials_provider``, ``multipart_threshold``, ``max_concurrency``, etc. 43 44 Example: 45 .. code-block:: yaml 46 47 profiles: 48 my-s8k-profile: 49 storage_provider: 50 type: s8k 51 options: 52 base_path: my-bucket 53 region_name: us-east-1 54 endpoint_url: https://s8k.example.com 55 infer_content_type: true # Enable MIME type inference 56 """ 57 58 def __init__(self, *args, **kwargs): 59 # Extract the infer_content_type option before passing to parent 60 self._infer_content_type = kwargs.pop("infer_content_type", False) 61 62 # "legacy" retry mode is required for SwiftStack (retry on HTTP 429 errors) 63 kwargs["retries"] = kwargs.get("retries", {}) | {"mode": "legacy"} 64 65 super().__init__(*args, **kwargs) 66 67 # override the provider name from "s3" 68 self._provider_name = PROVIDER 69 70 def _guess_content_type(self, file_path: str) -> str | None: 71 """ 72 Guess the content type based on the file extension using Python's mimetypes module. 73 74 This method mimics the behavior of python-swiftclient, which automatically infers 75 MIME types from file extensions (e.g., .wav → audio/x-wav). 76 77 :param file_path: The path or key of the file (can be local path or remote key). 78 :return: The guessed MIME type, or None if inference is disabled or type cannot be determined. 79 """ 80 if not self._infer_content_type: 81 return None 82 83 # Use mimetypes to guess the content type based on file extension 84 content_type, _ = mimetypes.guess_type(file_path) 85 return content_type 86 87 def _open_streaming_writer( 88 self, path: str, attributes: dict[str, str] | None, options: StreamingWriterOptions 89 ) -> StreamingObjectWriter: 90 if self._infer_content_type: 91 raise NotImplementedError("Streaming writes cannot be combined with infer_content_type.") 92 return super()._open_streaming_writer(path, attributes, options) 93 94 def _put_object( 95 self, 96 path: str, 97 body: bytes, 98 if_match: str | None = None, 99 if_none_match: str | None = None, 100 attributes: dict[str, str] | None = None, 101 content_type: str | None = None, 102 ) -> int: 103 """ 104 Uploads an object with optional content type inference. 105 106 Infers the content type from the file extension if enabled and not explicitly provided. 107 108 :param path: The S3 path where the object will be uploaded. 109 :param body: The content of the object as bytes. 110 :param if_match: Optional If-Match header value. 111 :param if_none_match: Optional If-None-Match header value. 112 :param attributes: Optional attributes to attach to the object. 113 :param content_type: Optional explicit Content-Type. If not provided, will be inferred if enabled. 114 """ 115 # Infer content type from the path if not explicitly provided 116 if content_type is None: 117 content_type = self._guess_content_type(path) 118 119 # Delegate to parent with inferred or explicit content_type 120 return super()._put_object(path, body, if_match, if_none_match, attributes, content_type) 121 122 def _upload_file( 123 self, 124 remote_path: str, 125 f: str | IO, 126 attributes: dict[str, str] | None = None, 127 content_type: str | None = None, 128 ) -> int: 129 """ 130 Uploads a file with optional content type inference. 131 132 Infers the content type from the file extension if enabled and not explicitly provided. 133 134 :param remote_path: The remote path where the file will be uploaded. 135 :param f: The source file to upload (file path or file object). 136 :param attributes: Optional attributes to attach to the file. 137 :param content_type: Optional explicit Content-Type. If not provided, will be inferred if enabled. 138 """ 139 # Infer content type if not explicitly provided 140 if content_type is None: 141 # For file paths, infer from the local file path 142 # For file objects, infer from the remote path (destination key) 143 if isinstance(f, str): 144 content_type = self._guess_content_type(f) 145 else: 146 content_type = self._guess_content_type(remote_path) 147 148 # Delegate to parent with inferred or explicit content_type 149 return super()._upload_file(remote_path, f, attributes, content_type)