Source code for multistorageclient.client.composite

  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 logging
 17from collections.abc import Iterator, Sequence
 18from typing import IO, Any
 19
 20from ..config import StorageClientConfig
 21from ..constants import MEMORY_LOAD_LIMIT
 22from ..file import ObjectFile, PosixFile
 23from ..types import (
 24    BatchTransferCallback,
 25    ExecutionMode,
 26    MetadataProvider,
 27    ObjectMetadata,
 28    PatternList,
 29    Range,
 30    SignerType,
 31    SourceVersionCheckMode,
 32    StreamingWriterOptions,
 33    SuffixRange,
 34    SymlinkHandling,
 35    SyncResult,
 36)
 37from ..utils import PatternMatcher, _invoke_batch_transfer
 38from .single import SingleStorageClient
 39from .types import AbstractStorageClient
 40
 41logger = logging.getLogger(__name__)
 42
 43
[docs] 44class CompositeStorageClient(AbstractStorageClient): 45 """ 46 READ-ONLY storage client for multi-backend configurations. 47 48 Routes read operations to child SingleStorageClient instances based on 49 metadata provider's routing information (ResolvedPath.profile). 50 51 Write operations raise NotImplementedError with clear error messages. 52 """ 53 54 _metadata_provider: MetadataProvider 55 56 def __init__(self, config: StorageClientConfig): 57 """ 58 Initialize a composite storage client. 59 60 :param config: Storage client configuration with storage_provider_profiles set 61 :raises ValueError: If config doesn't have storage_provider_profiles 62 """ 63 config = config._current_process_config() 64 if not config.storage_provider_profiles: 65 raise ValueError( 66 "CompositeStorageClient requires storage_provider_profiles. " 67 "Use SingleStorageClient for single-backend configurations." 68 ) 69 70 if config.metadata_provider is None: 71 raise ValueError("CompositeStorageClient requires a metadata_provider for routing decisions.") 72 73 self._config = config 74 self._profile = config.profile 75 self._metadata_provider = config.metadata_provider 76 self._metadata_provider_lock = None 77 self._storage_provider = config.storage_provider 78 self._credentials_provider = config.credentials_provider 79 self._retry_config = config.retry_config 80 self._cache_manager = config.cache_manager 81 self._replica_manager = None 82 83 self._child_clients: dict[str, SingleStorageClient] = {} 84 self._child_profile_names = config.storage_provider_profiles 85 86 for name in self._child_profile_names: 87 self._child_clients[name] = SingleStorageClient(config._related_config(name)) 88 89 def _ensure_current_process(self) -> None: 90 if self._config._inherited_reference: 91 fresh = CompositeStorageClient(self._config._current_process_config()) 92 object.__setattr__(self, "__dict__", vars(fresh)) 93 94 @property 95 def profile(self) -> str: 96 """ 97 :return: The profile name of the storage client. 98 """ 99 return self._profile 100 101 @property 102 def replicas(self) -> list[AbstractStorageClient]: 103 """ 104 :return: List of replica storage clients (empty list for CompositeStorageClient). 105 """ 106 return [] 107
[docs] 108 def is_default_profile(self) -> bool: 109 return self._config.profile == "__filesystem__"
110 111 def _is_rust_client_enabled(self) -> bool: 112 """ 113 Check if Rust client is enabled for all child storage clients. 114 115 When all child backends are Rust-enabled, MSC can use single-process 116 multi-threaded mode instead of multi-process mode, as Rust handles 117 parallelism internally via async I/O without Python GIL contention. 118 119 :return: True if all child clients are Rust-enabled, False otherwise. 120 """ 121 return all(client._is_rust_client_enabled() for client in self._child_clients.values()) 122 123 def _is_posix_file_storage_provider(self) -> bool: 124 """ 125 Check if using POSIX file storage provider. 126 127 :return: False - composite client doesn't have a single storage provider. 128 """ 129 return False 130
[docs] 131 def get_posix_path(self, path: str) -> str | None: 132 """ 133 Get the POSIX filesystem path for a given logical path. 134 135 :param path: The logical path to resolve. 136 :return: None - composite client doesn't support POSIX path resolution. 137 """ 138 return None
139 140 def _get_child_client(self, profile: str | None) -> SingleStorageClient: 141 """ 142 Get the child client for the specified profile. 143 144 :param profile: Profile name from ResolvedPath 145 :return: Child SingleStorageClient instance 146 :raises ValueError: If profile is None or not found 147 """ 148 if profile is None: 149 raise ValueError( 150 "CompositeStorageClient requires profile from ResolvedPath for routing. " 151 "Metadata provider must return ResolvedPath with profile set." 152 ) 153 154 if profile not in self._child_clients: 155 raise ValueError( 156 f"Profile '{profile}' not found in composite client. " 157 f"Available profiles: {list(self._child_clients.keys())}" 158 ) 159 160 return self._child_clients[profile] 161 162 def _resolve_child(self, path: str) -> tuple[SingleStorageClient, str]: 163 resolved = self._metadata_provider.realpath(path) 164 if not resolved.exists: 165 raise FileNotFoundError(f"Path '{path}' not found") 166 return self._get_child_client(resolved.profile), resolved.physical_path 167
[docs] 168 def read( 169 self, 170 path: str, 171 byte_range: Range | SuffixRange | None = None, 172 check_source_version: SourceVersionCheckMode = SourceVersionCheckMode.INHERIT, 173 ) -> bytes: 174 self._ensure_current_process() 175 child, physical_path = self._resolve_child(path) 176 return child.read(physical_path, byte_range, check_source_version)
177
[docs] 178 def open( 179 self, 180 path: str, 181 mode: str = "rb", 182 buffering: int = -1, 183 encoding: str | None = None, 184 disable_read_cache: bool = False, 185 memory_load_limit: int = MEMORY_LOAD_LIMIT, 186 atomic: bool = True, 187 check_source_version: SourceVersionCheckMode = SourceVersionCheckMode.INHERIT, 188 attributes: dict[str, Any] | None = None, 189 prefetch_file: bool | None = None, 190 writer_options: StreamingWriterOptions | None = None, 191 ) -> PosixFile | ObjectFile: 192 """ 193 Open a file for reading or writing. 194 195 :param path: The logical path of the object to open. 196 :param mode: The file mode. Supported modes: "r", "rb", "w", "wb", "a", "ab". 197 :param buffering: The buffering mode. Only applies to PosixFile. 198 :param encoding: The encoding to use for text files. 199 :param disable_read_cache: When set to ``True``, disables caching for file content. 200 This parameter is only applicable to ObjectFile when the mode is "r" or "rb". 201 :param memory_load_limit: Size limit in bytes for loading files into memory. Defaults to 512MB. 202 This parameter is only applicable to ObjectFile when the mode is "r" or "rb". Defaults to 512MB. 203 :param atomic: When set to ``True``, file will be written atomically (rename upon close). 204 This parameter is only applicable to PosixFile in write mode. 205 :param check_source_version: Whether to check the source version of cached objects. 206 :param attributes: Attributes to add to the file. 207 This parameter is only applicable when the mode is "w" or "wb" or "a" or "ab". Defaults to None. 208 :param prefetch_file: Whether to prefetch the file content. 209 This parameter is only applicable to ObjectFile when the mode is "r" or "rb". 210 If None, inherits from cache configuration. 211 :param writer_options: Stream the object through a bounded multipart upload instead of buffering it in memory. 212 Only valid with mode ``"wb"`` on a storage provider that supports streaming writes. 213 :return: A file-like object (PosixFile or ObjectFile) for the specified path. 214 :raises FileNotFoundError: If the file does not exist (read mode). 215 :raises ValueError: If ``writer_options`` is set with a mode other than ``"wb"``. 216 :raises NotImplementedError: If the operation is not supported (e.g., write on CompositeStorageClient). 217 """ 218 self._ensure_open_mode(mode) 219 if writer_options is not None and mode != "wb": 220 raise ValueError(f'writer_options requires mode "wb", got {mode!r}.') 221 self._ensure_current_process() 222 if mode not in ["r", "rb"]: 223 raise NotImplementedError( 224 f"CompositeStorageClient only supports read mode (got '{mode}'). " 225 "Write operations are not implemented for multi-location datasets." 226 ) 227 228 child, physical_path = self._resolve_child(path) 229 return child.open( 230 physical_path, 231 mode=mode, 232 buffering=buffering, 233 encoding=encoding, 234 disable_read_cache=disable_read_cache, 235 memory_load_limit=memory_load_limit, 236 atomic=atomic, 237 check_source_version=check_source_version, 238 attributes=attributes, 239 prefetch_file=prefetch_file, 240 writer_options=writer_options, 241 )
242
[docs] 243 def download_file(self, remote_path: str, local_path: str | IO, metadata: ObjectMetadata | None = None) -> None: 244 self._ensure_current_process() 245 child, physical_path = self._resolve_child(remote_path) 246 child.download_file(physical_path, local_path, metadata)
247
[docs] 248 def download_files( 249 self, 250 remote_paths: Sequence[str], 251 local_paths: Sequence[str], 252 metadata: Sequence[ObjectMetadata | None] | None = None, 253 max_workers: int = 16, 254 transfer_callback: BatchTransferCallback | None = None, 255 ) -> None: 256 self._ensure_current_process() 257 if len(remote_paths) != len(local_paths): 258 raise ValueError("remote_paths and local_paths must have the same length") 259 260 groups: dict[SingleStorageClient, tuple[list[str], list[str], list[ObjectMetadata | None]]] = {} 261 for i, (remote_path, local_path) in enumerate(zip(remote_paths, local_paths)): 262 child, physical_path = self._resolve_child(remote_path) 263 if child not in groups: 264 groups[child] = ([], [], []) 265 paths, destinations, entries = groups[child] 266 paths.append(physical_path) 267 destinations.append(local_path) 268 entries.append(metadata[i] if metadata is not None else None) 269 270 for child, (physical_paths, group_local_paths, group_metadata) in groups.items(): 271 has_any_metadata = any(m is not None for m in group_metadata) 272 _invoke_batch_transfer( 273 child.download_files, 274 physical_paths, 275 group_local_paths, 276 group_metadata if has_any_metadata else None, 277 max_workers, 278 transfer_callback=transfer_callback, 279 )
280
[docs] 281 def glob( 282 self, 283 pattern: str, 284 include_url_prefix: bool = False, 285 attribute_filter_expression: str | None = None, 286 ) -> list[str]: 287 self._ensure_current_process() 288 results = self._metadata_provider.glob( 289 pattern, 290 attribute_filter_expression=attribute_filter_expression, 291 ) 292 293 if include_url_prefix: 294 results = [self.url(path) for path in results] 295 296 return results
297
[docs] 298 def list_recursive( 299 self, 300 path: str = "", 301 start_after: str | None = None, 302 end_at: str | None = None, 303 max_workers: int = 32, 304 look_ahead: int = 2, 305 include_url_prefix: bool = False, 306 patterns: PatternList | None = None, 307 symlink_handling: SymlinkHandling = SymlinkHandling.FOLLOW, 308 ) -> Iterator[ObjectMetadata]: 309 self._ensure_current_process() 310 yield from self.list( 311 path=path, 312 start_after=start_after, 313 end_at=end_at, 314 include_directories=False, 315 include_url_prefix=include_url_prefix, 316 patterns=patterns, 317 symlink_handling=symlink_handling, 318 )
319
[docs] 320 def is_file(self, path: str) -> bool: 321 self._ensure_current_process() 322 resolved = self._metadata_provider.realpath(path) 323 return resolved.exists
324
[docs] 325 def is_empty(self, path: str) -> bool: 326 self._ensure_current_process() 327 objects = self._metadata_provider.list_objects(path) 328 329 try: 330 return next(objects) is None 331 except StopIteration: 332 pass 333 334 return True
335
[docs] 336 def info(self, path: str, strict: bool = True) -> ObjectMetadata: 337 self._ensure_current_process() 338 return self._metadata_provider.get_object_metadata(path, include_pending=not strict)
339
[docs] 340 def write( 341 self, 342 path: str, 343 body: bytes, 344 attributes: dict[str, Any] | None = None, 345 ) -> None: 346 """Write operations not supported in read-only mode.""" 347 self._ensure_writable() 348 raise NotImplementedError( 349 "CompositeStorageClient is read-only. " 350 "Write operations are not implemented for multi-location datasets. " 351 "Use a single-location dataset for write operations." 352 )
353
[docs] 354 def delete(self, path: str, recursive: bool = False) -> None: 355 """Delete operations not supported in read-only mode.""" 356 self._ensure_writable() 357 raise NotImplementedError( 358 "CompositeStorageClient is read-only. Delete operations are not implemented for multi-location datasets." 359 )
360
[docs] 361 def delete_many(self, paths: Sequence[str]) -> None: 362 """Delete operations not supported in read-only mode.""" 363 self._ensure_writable() 364 raise NotImplementedError( 365 "CompositeStorageClient is read-only. Delete operations are not implemented for multi-location datasets." 366 )
367
[docs] 368 def copy(self, src_path: str, dest_path: str) -> None: 369 """Copy operations not supported in read-only mode.""" 370 self._ensure_writable() 371 raise NotImplementedError( 372 "CompositeStorageClient is read-only. Copy operations are not implemented for multi-location datasets." 373 )
374 381
[docs] 382 def upload_file( 383 self, 384 remote_path: str, 385 local_path: str | IO, 386 attributes: dict[str, Any] | None = None, 387 ) -> None: 388 """Upload operations not supported in read-only mode.""" 389 self._ensure_writable() 390 raise NotImplementedError( 391 "CompositeStorageClient is read-only. Upload operations are not implemented for multi-location datasets." 392 )
393
[docs] 394 def upload_files( 395 self, 396 remote_paths: Sequence[str], 397 local_paths: Sequence[str], 398 attributes: Sequence[dict[str, Any] | None] | None = None, 399 max_workers: int = 16, 400 transfer_callback: BatchTransferCallback | None = None, 401 ) -> None: 402 """Upload operations not supported in read-only mode.""" 403 self._ensure_writable() 404 raise NotImplementedError( 405 "CompositeStorageClient is read-only. Upload operations are not implemented for multi-location datasets." 406 )
407
[docs] 408 def commit_metadata(self, prefix: str | None = None) -> None: 409 """No-op for read-only client.""" 410 self._ensure_writable()
411
[docs] 412 def sync_from( 413 self, 414 source_client: AbstractStorageClient, 415 source_path: str = "", 416 target_path: str = "", 417 delete_unmatched_files: bool = False, 418 description: str = "Syncing", 419 num_worker_processes: int | None = None, 420 execution_mode: ExecutionMode = ExecutionMode.LOCAL, 421 patterns: PatternList | None = None, 422 preserve_source_attributes: bool = False, 423 source_files: list[str] | None = None, 424 ignore_hidden: bool = True, 425 commit_metadata: bool = True, 426 dryrun: bool = False, 427 dryrun_output_path: str | None = None, 428 symlink_handling: SymlinkHandling = SymlinkHandling.FOLLOW, 429 ) -> SyncResult: 430 self._ensure_writable() 431 raise NotImplementedError( 432 "CompositeStorageClient cannot be used as sync target (write operation). " 433 "Use CompositeStorageClient as source only, or use a single-location dataset as target." 434 )
435
[docs] 436 def sync_replicas( 437 self, 438 source_path: str, 439 replica_indices: Sequence[int] | None = None, 440 delete_unmatched_files: bool = False, 441 description: str = "Syncing replica", 442 num_worker_processes: int | None = None, 443 execution_mode: ExecutionMode = ExecutionMode.LOCAL, 444 patterns: PatternList | None = None, 445 ignore_hidden: bool = True, 446 symlink_handling: SymlinkHandling = SymlinkHandling.FOLLOW, 447 ) -> None: 448 """No-op for read-only client.""" 449 self._ensure_writable()
450
[docs] 451 def list( 452 self, 453 path: str = "", 454 start_after: str | None = None, 455 end_at: str | None = None, 456 include_directories: bool = False, 457 include_url_prefix: bool = False, 458 attribute_filter_expression: str | None = None, 459 show_attributes: bool = False, 460 patterns: PatternList | None = None, 461 symlink_handling: SymlinkHandling = SymlinkHandling.FOLLOW, 462 ) -> Iterator[ObjectMetadata]: 463 # Apply patterns to the objects 464 self._ensure_current_process() 465 pattern_matcher = PatternMatcher(patterns) if patterns else None 466 467 # Delegate to metadata provider (always present for CompositeStorageClient) 468 objects = self._metadata_provider.list_objects( 469 path, 470 start_after=start_after, 471 end_at=end_at, 472 include_directories=include_directories, 473 attribute_filter_expression=attribute_filter_expression, 474 show_attributes=show_attributes, 475 ) 476 for obj in self._process_local_listing(objects): 477 # Skip objects that do not match the patterns 478 if pattern_matcher and not pattern_matcher.should_include_file(obj.key): 479 continue 480 481 if include_url_prefix: 482 # Return a copy: the object is owned by the metadata provider and must not be mutated. 483 obj = obj.replace(key=self.url(obj.key)) 484 485 yield obj
486
[docs] 487 def generate_presigned_url( 488 self, 489 path: str, 490 *, 491 method: str = "GET", 492 signer_type: SignerType | None = None, 493 signer_options: dict[str, Any] | None = None, 494 ) -> str: 495 self._ensure_signing_method(method) 496 self._ensure_current_process() 497 child, physical_path = self._resolve_child(path) 498 return child.generate_presigned_url( 499 physical_path, method=method, signer_type=signer_type, signer_options=signer_options 500 )
501 502 def __getstate__(self) -> dict[str, Any]: 503 """Support for pickling.""" 504 return {"_config": self._config} 505 506 def __setstate__(self, state: dict[str, Any]) -> None: 507 """Support for unpickling - reinitialize from config.""" 508 config = state["_config"] 509 self.__init__(config)