Source code for multistorageclient.client.single

   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 atexit
  17import contextlib
  18import logging
  19import os
  20import threading
  21from collections.abc import Callable, Iterator, Sequence
  22from concurrent.futures import ThreadPoolExecutor, as_completed
  23from datetime import UTC, datetime
  24from io import BytesIO
  25from pathlib import PurePosixPath
  26from typing import IO, Any, cast
  27
  28from ..config import StorageClientConfig
  29from ..constants import DEFAULT_SYNC_BATCH_SIZE, MEMORY_LOAD_LIMIT
  30from ..file import ObjectFile, PosixFile
  31from ..providers.base import BaseStorageProvider
  32from ..providers.posix_file import PosixFileStorageProvider
  33from ..replica_manager import ReplicaManager
  34from ..retry import batch_retry, retry
  35from ..sync import SyncManager
  36from ..types import (
  37    AWARE_DATETIME_MIN,
  38    BatchTransferCallback,
  39    ExecutionMode,
  40    ObjectMetadata,
  41    PatternList,
  42    Range,
  43    Replica,
  44    ResolvedPathState,
  45    SignerType,
  46    SourceVersionCheckMode,
  47    StorageProvider,
  48    StreamingObjectWriter,
  49    StreamingWriterOptions,
  50    SuffixRange,
  51    SymlinkHandling,
  52    SyncResult,
  53)
  54from ..utils import (
  55    NullStorageClient,
  56    PatternMatcher,
  57    _invoke_batch_transfer,
  58    _transfer_notification,
  59    create_attribute_filter_evaluator,
  60    matches_attribute_filter_expression,
  61)
  62from .types import AbstractStorageClient
  63
  64logger = logging.getLogger(__name__)
  65
  66
  67class _RegisteringWriter(StreamingObjectWriter):
  68    """
  69    Registers the object with the metadata provider after the wrapped writer publishes it.
  70
  71    Unlike upload failures, a close that fails in registration can be retried: it registers without publishing
  72    again. Abort after publication does nothing.
  73    """
  74
  75    def __init__(
  76        self, inner: StreamingObjectWriter, register: Callable[[], None], check_before_publish: Callable[[], Any]
  77    ):
  78        self._inner = inner
  79        self._register = register
  80        self._check_before_publish = check_before_publish
  81        self._size: int | None = None
  82        self._registered = False
  83
  84    def write(self, data: Any) -> int:
  85        return self._inner.write(data)
  86
  87    def tell(self) -> int:
  88        return self._inner.tell()
  89
  90    def flush(self) -> None:
  91        self._inner.flush()
  92
  93    def sync(self) -> None:
  94        self._inner.sync()
  95
  96    def close(self) -> int:
  97        if self._size is None:
  98            # Re-check the overwrite policy just before publishing, as buffered writes do at upload time.
  99            try:
 100                self._check_before_publish()
 101            except Exception:
 102                self._inner.abort()
 103                raise
 104            self._size = self._inner.close()
 105        if not self._registered:
 106            self._register()
 107            self._registered = True
 108        return self._size
 109
 110    def abort(self) -> None:
 111        if self._size is None:
 112            self._inner.abort()
 113
 114
[docs] 115class SingleStorageClient(AbstractStorageClient): 116 """ 117 Storage client for single-backend configurations. 118 119 Supports full read and write operations against a single storage provider. 120 """ 121 122 _config: StorageClientConfig 123 _storage_provider: StorageProvider 124 _metadata_provider_lock: "threading.Lock | None" = None 125 _stop_event: threading.Event | None = None 126 _replica_manager: ReplicaManager | None = None 127 128 def __init__(self, config: StorageClientConfig): 129 """ 130 Initialize the :py:class:`SingleStorageClient` with the given configuration. 131 132 :param config: Storage client configuration with storage_provider set 133 :raises ValueError: If config has storage_provider_profiles (multi-backend) 134 """ 135 config = config._current_process_config() 136 self._initialize_providers(config) 137 self._initialize_replicas(config.replicas) 138 139 def _ensure_current_process(self) -> None: 140 if self._config._inherited_reference: 141 config = self._config._current_process_config() 142 fresh = SingleStorageClient(config) 143 if self._replica_manager is None: 144 fresh._replica_manager = None 145 object.__setattr__(self, "__dict__", vars(fresh)) 146 147 def _initialize_providers(self, config: StorageClientConfig) -> None: 148 if config.storage_provider_profiles: 149 raise ValueError( 150 "SingleStorageClient requires storage_provider, not storage_provider_profiles. " 151 "Use CompositeStorageClient for multi-backend configurations." 152 ) 153 154 if config.storage_provider is None: 155 raise ValueError("SingleStorageClient requires storage_provider to be set.") 156 157 self._config = config 158 self._credentials_provider = self._config.credentials_provider 159 self._storage_provider = cast(StorageProvider, self._config.storage_provider) 160 self._metadata_provider = self._config.metadata_provider 161 self._cache_config = self._config.cache_config 162 self._retry_config = self._config.retry_config 163 self._cache_manager = self._config.cache_manager 164 if config.read_only and isinstance(self._storage_provider, PosixFileStorageProvider): 165 self._storage_provider._restrict_to_base_path = True 166 self._autocommit_config = self._config.autocommit_config 167 168 if self._autocommit_config: 169 if self._metadata_provider: 170 logger.debug("Creating auto-commiter thread") 171 172 if self._autocommit_config.interval_minutes: 173 self._stop_event = threading.Event() 174 self._commit_thread = threading.Thread( 175 target=self._committer_thread, 176 daemon=True, 177 args=(self._autocommit_config.interval_minutes, self._stop_event), 178 ) 179 self._commit_thread.start() 180 181 if self._autocommit_config.at_exit: 182 atexit.register(self._commit_on_exit) 183 184 self._metadata_provider_lock = threading.Lock() 185 else: 186 logger.debug("No metadata provider configured, auto-commit will not be enabled") 187 188 def _initialize_replicas(self, replicas: list[Replica]) -> None: 189 """Initialize replica StorageClient instances (facade).""" 190 # Import here to avoid circular dependency 191 from .client import StorageClient as StorageClientFacade 192 193 # Sort replicas by read_priority, the first one is the primary replica. 194 sorted_replicas = sorted(replicas, key=lambda r: r.read_priority) 195 196 replica_clients = [] 197 writable_replica_clients = [] 198 for replica in sorted_replicas: 199 replica_config = self._config._related_config(replica.replica_profile) 200 201 storage_client = StorageClientFacade(config=replica_config) 202 replica_clients.append(storage_client) 203 if not replica.read_only: 204 writable_replica_clients.append(storage_client) 205 206 self._replicas = replica_clients 207 self._writable_replicas = writable_replica_clients 208 self._replica_manager = ReplicaManager(self) if len(self._replicas) > 0 else None 209 210 def _committer_thread(self, commit_interval_minutes: float, stop_event: threading.Event): 211 if not stop_event: 212 raise RuntimeError("Stop event not set") 213 214 while not stop_event.is_set(): 215 # Wait with the ability to exit early 216 if stop_event.wait(timeout=commit_interval_minutes * 60): 217 break 218 logger.debug("Auto-committing to metadata provider") 219 self.commit_metadata() 220 221 def _commit_on_exit(self): 222 logger.debug("Shutting down, committing metadata one last time...") 223 self.commit_metadata() 224 225 def _get_source_version(self, path: str) -> str | None: 226 """ 227 Get etag from metadata provider or storage provider. 228 """ 229 if self._metadata_provider: 230 metadata = self._metadata_provider.get_object_metadata(path) 231 else: 232 metadata = self._storage_provider.get_object_metadata(path) 233 return metadata.etag 234 235 def _is_cache_enabled(self) -> bool: 236 enabled = self._cache_manager is not None and not self._is_posix_file_storage_provider() 237 return enabled 238 239 def _is_posix_file_storage_provider(self) -> bool: 240 """ 241 :return: ``True`` if the storage client is using a POSIX file storage provider, ``False`` otherwise. 242 """ 243 return isinstance(self._storage_provider, PosixFileStorageProvider) 244 245 def _is_rust_client_enabled(self) -> bool: 246 """ 247 :return: ``True`` if the storage provider is using the Rust client, ``False`` otherwise. 248 """ 249 return getattr(self._storage_provider, "_rust_client", None) is not None 250 251 def _get_suffix_object_size(self, physical_path: str) -> int: 252 """ 253 :return: The size of the object at a physical path, following symlinks of the storage provider. 254 """ 255 if isinstance(self._storage_provider, BaseStorageProvider): 256 provider = self._storage_provider 257 _, metadata = provider._resolve_symlink_path(provider._prepend_base_path(physical_path)) 258 return metadata.content_length 259 return self._storage_provider.get_object_metadata(physical_path).content_length 260 261 def _can_read_suffix_range(self) -> bool: 262 """ 263 :return: ``True`` if a suffix range can be passed to the storage provider without knowing the object size. 264 """ 265 return ( 266 isinstance(self._storage_provider, BaseStorageProvider) 267 and not (self._is_cache_enabled() and self._cache_manager) 268 and not self._replica_manager 269 ) 270 271 def _read_from_replica_or_primary(self, path: str) -> bytes: 272 """ 273 Read from replica or primary storage provider. Use BytesIO to avoid creating temporary files. 274 """ 275 if self._replica_manager is None: 276 raise RuntimeError("Replica manager is not initialized") 277 file_obj = BytesIO() 278 self._replica_manager.download_from_replica_or_primary(path, file_obj, self._storage_provider) 279 return file_obj.getvalue() 280 281 def __del__(self): 282 if self._stop_event: 283 self._stop_event.set() 284 if self._commit_thread.is_alive(): 285 self._commit_thread.join(timeout=5.0) 286 287 def __getstate__(self) -> dict[str, Any]: 288 # Replica manager could be disabled if it's set to None in the state. 289 state: dict[str, Any] = {"_config": self._config} 290 if self._replica_manager is None: 291 state["_replica_manager"] = None 292 return state 293 294 def __setstate__(self, state: dict[str, Any]) -> None: 295 config = state["_config"] 296 self._initialize_providers(config) 297 298 # Sync disables replica reads on the source client before dispatching workers. 299 if "_replica_manager" in state and state["_replica_manager"] is None: 300 self._replicas = [] 301 self._writable_replicas = [] 302 self._replica_manager = None 303 else: 304 self._initialize_replicas(config.replicas) 305 306 if self._metadata_provider: 307 self._metadata_provider_lock = threading.Lock() 308 309 @property 310 def profile(self) -> str: 311 """ 312 :return: The profile name of the storage client. 313 """ 314 return self._config.profile 315
[docs] 316 def is_default_profile(self) -> bool: 317 """ 318 :return: ``True`` if the storage client is using the reserved POSIX profile, ``False`` otherwise. 319 """ 320 return self._config.profile == "__filesystem__"
321 322 @property 323 def replicas(self) -> list[AbstractStorageClient]: 324 """ 325 :return: List of replica storage clients, sorted by read priority. 326 """ 327 # Replica clients accept physical paths that bypass a bound reference's metadata inventory. 328 return [] if self._config.read_only else self._replicas 329 330 @property 331 def writable_replicas(self) -> list[AbstractStorageClient]: 332 """:return: Writable replica storage clients, sorted by read priority.""" 333 return self._writable_replicas 334 335 # -- Metadata resolution helpers -- 336 337 def _resolve_read_path(self, logical_path: str) -> str: 338 """ 339 Resolve a logical path to its physical storage path for read operations. 340 341 :param logical_path: The user-facing logical path. 342 :return: The physical storage path. 343 :raises FileNotFoundError: If the file does not exist in the metadata provider. 344 """ 345 if self._metadata_provider is None: 346 raise RuntimeError("Metadata provider is not configured") 347 resolved = self._metadata_provider.realpath(logical_path) 348 if not resolved.exists: 349 raise FileNotFoundError(f"The file at path '{logical_path}' was not found by metadata provider.") 350 return resolved.physical_path 351 352 def _resolve_write_path(self, logical_path: str) -> str: 353 """ 354 Resolve a logical path to its physical storage path for write operations. 355 356 Checks overwrite policy and generates the physical path via the metadata provider. 357 358 :param logical_path: The user-facing logical path. 359 :return: The physical storage path to write to. 360 :raises FileExistsError: If the file exists and overwrites are not allowed. 361 """ 362 if self._metadata_provider is None: 363 raise RuntimeError("Metadata provider is not configured") 364 resolved = self._metadata_provider.realpath(logical_path) 365 if resolved.state in (ResolvedPathState.EXISTS, ResolvedPathState.DELETED): 366 if not self._metadata_provider.allow_overwrites(): 367 raise FileExistsError( 368 f"The file at path '{logical_path}' already exists; " 369 f"overwriting is not allowed when using a metadata provider." 370 ) 371 return self._metadata_provider.generate_physical_path(logical_path, for_overwrite=True).physical_path 372 return self._metadata_provider.generate_physical_path(logical_path, for_overwrite=False).physical_path 373 374 def _register_written_file( 375 self, virtual_path: str, physical_path: str, attributes: dict[str, Any] | None = None 376 ) -> None: 377 """ 378 Register a written file with the metadata provider. 379 380 Fetches metadata from the storage provider, optionally merges custom attributes, 381 and registers the file with the metadata provider. 382 383 Protects metadata provider mutation with ``_metadata_provider_lock`` when configured. 384 385 .. note:: 386 TODO(NGCDP-3016): Handle eventual consistency of Swiftstack, without wait. 387 """ 388 if self._metadata_provider is None: 389 raise RuntimeError("Metadata provider is not configured") 390 obj_metadata = self._storage_provider.get_object_metadata(physical_path) 391 if attributes: 392 obj_metadata.metadata = (obj_metadata.metadata or {}) | attributes 393 with self._metadata_provider_lock or contextlib.nullcontext(): 394 self._metadata_provider.add_file(virtual_path, obj_metadata) 395 396 def _open_streaming_writer( 397 self, path: str, attributes: dict[str, Any] | None, options: StreamingWriterOptions 398 ) -> StreamingObjectWriter: 399 """ 400 Open a streaming writer through the storage provider. 401 402 With a metadata provider, the object is written to its physical path and registered after it is published. 403 404 :param path: The logical path of the object to write. 405 :param attributes: The attributes to add to the object. 406 :param options: The streaming writer options. 407 :return: A writer that publishes (and registers) the object on close. 408 :raises NotImplementedError: If the storage provider does not support streaming writes. 409 """ 410 provider = self._storage_provider 411 if self._metadata_provider: 412 physical_path = self._resolve_write_path(path) 413 # Attributes belong to logical metadata, so physical writes get none and registration stores them. 414 writer = provider.open_streaming_writer(physical_path, None, options) 415 return _RegisteringWriter( 416 writer, 417 register=lambda: self._register_written_file(path, physical_path, attributes), 418 check_before_publish=lambda: self._resolve_write_path(path), 419 ) 420 return provider.open_streaming_writer(path, attributes, options) 421 422 def _register_written_files( 423 self, 424 virtual_paths: Sequence[str], 425 physical_paths: Sequence[str], 426 attributes: Sequence[dict[str, Any] | None] | None = None, 427 max_workers: int = 16, 428 ) -> None: 429 """Register multiple written files with the metadata provider concurrently.""" 430 if not virtual_paths: 431 return 432 433 def _register_one(index: int, virtual_path: str, physical_path: str) -> None: 434 file_attrs = attributes[index] if attributes is not None else None 435 self._register_written_file(virtual_path, physical_path, file_attrs) 436 437 worker_count = max(1, min(len(virtual_paths), max_workers)) 438 with ThreadPoolExecutor(max_workers=worker_count) as executor: 439 future_to_virtual_path = { 440 executor.submit(_register_one, i, virtual_path, physical_path): virtual_path 441 for i, (virtual_path, physical_path) in enumerate(zip(virtual_paths, physical_paths)) 442 } 443 for future in as_completed(future_to_virtual_path): 444 future.result() 445 446 @batch_retry(operation_name="download_files") 447 def _download_files_batch( 448 self, 449 indices: list[int], 450 remote_paths: Sequence[str], 451 local_paths: Sequence[str], 452 metadata: Sequence[ObjectMetadata | None] | None, 453 max_workers: int, 454 transfer_callback: BatchTransferCallback | None = None, 455 ) -> None: 456 """ 457 Execute one provider batch download attempt for the selected item indices. 458 459 The ``@batch_retry`` decorator retries this method with only failed 460 indices when the provider reports item-level retryable failures. 461 462 :param indices: Original batch indices to include in this attempt. 463 :param remote_paths: Remote paths for the full original batch. 464 :param local_paths: Local destination paths for the full original batch. 465 :param metadata: Optional per-file metadata for the full original batch. 466 :param max_workers: Maximum provider workers for this attempt. 467 :param transfer_callback: Optional observer called with source path, destination path, and "started", 468 "completed", or "failed" for each executing attempt. Remote paths may be resolved physical paths. 469 Calls may be concurrent; callback exceptions are logged. 470 """ 471 provider_remote_paths = [remote_paths[index] for index in indices] 472 provider_local_paths = [local_paths[index] for index in indices] 473 provider_metadata = [metadata[index] for index in indices] if metadata is not None else None 474 475 _invoke_batch_transfer( 476 self._storage_provider.download_files, 477 provider_remote_paths, 478 provider_local_paths, 479 provider_metadata, 480 max_workers, 481 transfer_callback=transfer_callback, 482 ) 483 484 @batch_retry(operation_name="upload_files") 485 def _upload_files_batch( 486 self, 487 indices: list[int], 488 local_paths: Sequence[str], 489 remote_paths: Sequence[str], 490 attributes: Sequence[dict[str, Any] | None] | None, 491 max_workers: int, 492 transfer_callback: BatchTransferCallback | None = None, 493 ) -> None: 494 """ 495 Execute one provider batch upload attempt for the selected item indices. 496 497 The ``@batch_retry`` decorator retries this method with only failed 498 indices when the provider reports item-level retryable failures. 499 500 :param indices: Original batch indices to include in this attempt. 501 :param local_paths: Local source paths for the full original batch. 502 :param remote_paths: Provider destination paths for the full original batch. 503 :param attributes: Optional per-file attributes for the full original batch. 504 :param max_workers: Maximum provider workers for this attempt. 505 :param transfer_callback: Optional observer called with source path, destination path, and "started", 506 "completed", or "failed" for each executing attempt. Remote paths may be resolved physical paths. 507 Calls may be concurrent; callback exceptions are logged. 508 """ 509 provider_local_paths = [local_paths[index] for index in indices] 510 provider_remote_paths = [remote_paths[index] for index in indices] 511 provider_attributes = [attributes[index] for index in indices] if attributes is not None else None 512 513 _invoke_batch_transfer( 514 self._storage_provider.upload_files, 515 provider_local_paths, 516 provider_remote_paths, 517 provider_attributes, 518 max_workers, 519 transfer_callback=transfer_callback, 520 ) 521
[docs] 522 @retry 523 def read( 524 self, 525 path: str, 526 byte_range: Range | SuffixRange | None = None, 527 check_source_version: SourceVersionCheckMode = SourceVersionCheckMode.INHERIT, 528 ) -> bytes: 529 """ 530 Read bytes from a file at the specified logical path. 531 532 With the Rust client enabled, the result may be a Rust buffer exposing Python's buffer protocol 533 rather than a Python ``bytes`` instance. Keeping this buffer avoids an additional copy for callers 534 that can consume it directly. Use ``bytes(result)`` when a Python ``bytes`` object is required, 535 or ``str(result, "utf-8")`` to decode text directly from the buffer. 536 537 :param path: The logical path of the object to read. 538 :param byte_range: Optional byte range to read (offset and length), or a suffix range to read the last bytes. 539 :param check_source_version: Whether to check the source version of cached objects. 540 :return: The object content as Python bytes or, with Rust enabled, a buffer supporting Python's buffer protocol. 541 :raises FileNotFoundError: If the file at the specified path does not exist. 542 """ 543 self._ensure_current_process() 544 logical_path = path 545 if self._metadata_provider: 546 path = self._resolve_read_path(path) 547 548 if isinstance(byte_range, SuffixRange): 549 if self._can_read_suffix_range(): 550 return cast(BaseStorageProvider, self._storage_provider).get_object(path, byte_range=byte_range) 551 552 # (the size of the physical object: the path is resolved, symlinks of the storage provider are followed) 553 content_length = self._get_suffix_object_size(path) 554 offset = max(content_length - byte_range.size, 0) 555 if offset >= content_length: 556 return b"" 557 byte_range = Range(offset=offset, size=content_length - offset) 558 559 # Handle caching logic 560 if self._is_cache_enabled() and self._cache_manager: 561 if byte_range: 562 # Range request with cache 563 try: 564 # Fetch metadata for source version checking (if needed) 565 metadata = None 566 source_version = None 567 if check_source_version == SourceVersionCheckMode.ENABLE or ( 568 check_source_version == SourceVersionCheckMode.INHERIT 569 and self._cache_manager.check_source_version() 570 ): 571 metadata = self._storage_provider.get_object_metadata(path) 572 source_version = metadata.etag 573 574 # Optimization: For full-file reads (offset=0, size >= file_size), cache whole file instead of chunking 575 # This avoids creating many small chunks when the user requests the entire file. 576 # Only apply this optimization when metadata is already available (i.e., when version checking is enabled), 577 # to respect the user's choice to disable version checking and avoid extra HEAD requests. 578 if byte_range.offset == 0 and metadata and byte_range.size >= metadata.content_length: 579 full_file_data = self._cache_manager.read(path, source_version) 580 if full_file_data is None: 581 if self._replica_manager: 582 full_file_data = self._read_from_replica_or_primary(path) 583 else: 584 full_file_data = self._storage_provider.get_object(path) 585 self._cache_manager.set(path, full_file_data, source_version) 586 return full_file_data[: metadata.content_length] 587 588 # Use chunk-based caching for partial reads or when optimization doesn't apply 589 data = self._cache_manager.read( 590 key=path, 591 source_version=source_version, 592 byte_range=byte_range, 593 storage_provider=self._storage_provider, 594 source_size=metadata.content_length if metadata else None, 595 check_source_version=check_source_version, 596 ) 597 if data is not None: 598 return data 599 # Fallback (should not normally happen) 600 return self._storage_provider.get_object(path, byte_range=byte_range) 601 except (FileNotFoundError, Exception): 602 # Fall back to direct read if metadata fetching fails 603 return self._storage_provider.get_object(path, byte_range=byte_range) 604 else: 605 # Full file read with cache 606 # Only fetch source version if check_source_version is enabled 607 source_version = None 608 if check_source_version == SourceVersionCheckMode.ENABLE or ( 609 check_source_version == SourceVersionCheckMode.INHERIT 610 and self._cache_manager.check_source_version() 611 ): 612 source_version = self._get_source_version(logical_path) 613 614 data = self._cache_manager.read(path, source_version) 615 if data is None: 616 if self._replica_manager: 617 data = self._read_from_replica_or_primary(path) 618 else: 619 data = self._storage_provider.get_object(path) 620 self._cache_manager.set(path, data, source_version) 621 return data 622 elif self._replica_manager: 623 # No cache, but replicas available 624 data = self._read_from_replica_or_primary(path) 625 if byte_range is not None: 626 return data[byte_range.offset : byte_range.offset + byte_range.size] 627 return data 628 else: 629 # No cache, no replicas - direct storage provider read 630 return self._storage_provider.get_object(path, byte_range=byte_range)
631
[docs] 632 def info(self, path: str, strict: bool = True) -> ObjectMetadata: 633 """ 634 Get metadata for a file at the specified path. 635 636 :param path: The logical path of the object. 637 :param strict: When ``True``, only return committed metadata. When ``False``, include pending changes. 638 :return: ObjectMetadata containing file information (size, last modified, etc.). 639 :raises FileNotFoundError: If the file at the specified path does not exist. 640 """ 641 self._ensure_current_process() 642 if self._config.read_only and self._metadata_provider: 643 return self._metadata_provider.get_object_metadata(path, include_pending=not strict) 644 645 if not path or (path == "." and not self._config.read_only): # empty path or '.' provided by the user 646 if self._is_posix_file_storage_provider(): 647 root = cast(PosixFileStorageProvider, self._storage_provider)._prepend_base_path("") 648 last_modified = datetime.fromtimestamp(os.path.getmtime(root), tz=UTC) 649 else: 650 last_modified = AWARE_DATETIME_MIN 651 return ObjectMetadata(key="", type="directory", content_length=0, last_modified=last_modified) 652 653 if not self._metadata_provider: 654 return self._storage_provider.get_object_metadata(path, strict=strict) 655 656 return self._metadata_provider.get_object_metadata(path, include_pending=not strict)
657
[docs] 658 @retry 659 def download_file(self, remote_path: str, local_path: str | IO, metadata: ObjectMetadata | None = None) -> None: 660 """ 661 Download a remote file to a local path or file-like object. 662 663 :param remote_path: The logical path of the remote file to download. 664 :param local_path: The local file path or file-like object to write to. 665 :param metadata: Optional metadata for this object, as returned by :py:meth:`info`, to avoid a provider lookup. 666 :raises FileNotFoundError: If the remote file does not exist. 667 """ 668 self._ensure_current_process() 669 if self._metadata_provider: 670 physical_path = self._resolve_read_path(remote_path) 671 metadata = self._metadata_provider.get_object_metadata(remote_path) 672 self._storage_provider.download_file(physical_path, local_path, metadata) 673 elif self._replica_manager: 674 self._replica_manager.download_from_replica_or_primary(remote_path, local_path, self._storage_provider) 675 else: 676 self._storage_provider.download_file(remote_path, local_path, metadata)
677
[docs] 678 def download_files( 679 self, 680 remote_paths: Sequence[str], 681 local_paths: Sequence[str], 682 metadata: Sequence[ObjectMetadata | None] | None = None, 683 max_workers: int = 16, 684 transfer_callback: BatchTransferCallback | None = None, 685 ) -> None: 686 """ 687 Download multiple remote files to local paths. 688 689 :param remote_paths: List of logical paths of remote files to download. 690 :param local_paths: List of local file paths to save the downloaded files to. 691 :param metadata: Optional per-file metadata used to decide between regular and multipart download. 692 :param max_workers: Maximum number of concurrent download workers (default: 16). 693 :param transfer_callback: Optional observer called with source path, destination path, and "started", 694 "completed", or "failed" for each executing attempt. Remote paths may be resolved physical paths. 695 Calls may be concurrent; callback exceptions are logged. 696 :raises ValueError: If remote_paths and local_paths have different lengths. 697 :raises FileNotFoundError: If any remote file does not exist. 698 """ 699 self._ensure_current_process() 700 if len(remote_paths) != len(local_paths): 701 raise ValueError("remote_paths and local_paths must have the same length") 702 703 if metadata is not None and len(metadata) != len(remote_paths): 704 raise ValueError("metadata must have the same length as remote_paths and local_paths") 705 706 if self._metadata_provider: 707 physical_paths = [self._resolve_read_path(rp) for rp in remote_paths] 708 self._download_files_batch( 709 list(range(len(remote_paths))), physical_paths, local_paths, metadata, max_workers, transfer_callback 710 ) 711 elif self._replica_manager: 712 for remote_path, local_path in zip(remote_paths, local_paths): 713 with _transfer_notification(transfer_callback, remote_path, local_path): 714 self.download_file(remote_path, local_path) 715 else: 716 self._download_files_batch( 717 list(range(len(remote_paths))), remote_paths, local_paths, metadata, max_workers, transfer_callback 718 )
719
[docs] 720 @retry 721 def upload_file(self, remote_path: str, local_path: str | IO, attributes: dict[str, Any] | None = None) -> None: 722 """ 723 Uploads a file from the local file system to the storage provider. 724 725 :param remote_path: The path where the object will be stored. 726 :param local_path: The source file to upload. This can either be a string representing the local 727 file path, or a file-like object (e.g., an open file handle). 728 :param attributes: The attributes to add to the file if a new file is created. 729 """ 730 self._ensure_writable() 731 virtual_path = remote_path 732 if self._metadata_provider: 733 physical_path = self._resolve_write_path(remote_path) 734 # Attributes belong to logical metadata, so physical writes get none and registration stores them. 735 self._storage_provider.upload_file(physical_path, local_path, attributes=None) 736 self._register_written_file(virtual_path, physical_path, attributes) 737 else: 738 self._storage_provider.upload_file(remote_path, local_path, attributes)
739
[docs] 740 def upload_files( 741 self, 742 remote_paths: Sequence[str], 743 local_paths: Sequence[str], 744 attributes: Sequence[dict[str, Any] | None] | None = None, 745 max_workers: int = 16, 746 transfer_callback: BatchTransferCallback | None = None, 747 ) -> None: 748 """ 749 Upload multiple local files to remote storage. 750 751 :param remote_paths: List of logical paths where the files will be uploaded. 752 :param local_paths: List of local file paths to upload. 753 :param attributes: Optional list of per-file attributes to add. When provided, must have the same length 754 as remote_paths/local_paths. Each element may be ``None`` for files that need no attributes. 755 :param max_workers: Maximum number of concurrent upload workers (default: 16). 756 :param transfer_callback: Optional observer called with source path, destination path, and "started", 757 "completed", or "failed" for each executing attempt. Remote paths may be resolved physical paths. 758 Calls may be concurrent; callback exceptions are logged. 759 :raises ValueError: If remote_paths and local_paths have different lengths. 760 :raises ValueError: If attributes is provided and has a different length than remote_paths. 761 """ 762 self._ensure_writable() 763 if len(remote_paths) != len(local_paths): 764 raise ValueError("remote_paths and local_paths must have the same length") 765 766 if attributes is not None and len(attributes) != len(remote_paths): 767 raise ValueError("attributes must have the same length as remote_paths and local_paths") 768 769 if self._metadata_provider: 770 physical_paths = [self._resolve_write_path(rp) for rp in remote_paths] 771 772 # Attributes belong to logical metadata, so physical writes get none and registration stores them. 773 self._upload_files_batch( 774 list(range(len(remote_paths))), 775 local_paths, 776 physical_paths, 777 None, 778 max_workers, 779 transfer_callback, 780 ) 781 782 self._register_written_files(remote_paths, physical_paths, attributes, max_workers) 783 else: 784 self._upload_files_batch( 785 list(range(len(remote_paths))), local_paths, remote_paths, attributes, max_workers, transfer_callback 786 )
787
[docs] 788 @retry 789 def write(self, path: str, body: bytes, attributes: dict[str, Any] | None = None) -> None: 790 """ 791 Write bytes to a file at the specified path. 792 793 :param path: The logical path where the object will be written. 794 :param body: The content to write as bytes. 795 :param attributes: Optional attributes to add to the file. 796 """ 797 self._ensure_writable() 798 virtual_path = path 799 if self._metadata_provider: 800 physical_path = self._resolve_write_path(path) 801 # Attributes belong to logical metadata, so physical writes get none and registration stores them. 802 self._storage_provider.put_object(physical_path, body, attributes=None) 803 self._register_written_file(virtual_path, physical_path, attributes) 804 else: 805 self._storage_provider.put_object(path, body, attributes=attributes)
806
[docs] 807 def copy(self, src_path: str, dest_path: str) -> None: 808 """ 809 Copy a file from source path to destination path. 810 811 :param src_path: The logical path of the source object. 812 :param dest_path: The logical path where the object will be copied to. 813 :raises FileNotFoundError: If the source file does not exist. 814 """ 815 self._ensure_writable() 816 virtual_dest_path = dest_path 817 if self._metadata_provider: 818 src_path = self._resolve_read_path(src_path) 819 dest_path = self._resolve_write_path(dest_path) 820 self._storage_provider.copy_object(src_path, dest_path) 821 self._register_written_file(virtual_dest_path, dest_path) 822 else: 823 self._storage_provider.copy_object(src_path, dest_path)
824 853
[docs] 854 def delete(self, path: str, recursive: bool = False) -> None: 855 """ 856 Deletes an object at the specified path. 857 858 :param path: The logical path of the object or directory to delete. 859 :param recursive: Whether to delete objects in the path recursively. 860 """ 861 self._ensure_writable() 862 obj_metadata = self.info(path) 863 is_dir = obj_metadata and obj_metadata.type == "directory" 864 is_file = obj_metadata and obj_metadata.type == "file" 865 if recursive and is_dir: 866 self.sync_from( 867 cast(AbstractStorageClient, NullStorageClient()), 868 path, 869 path, 870 delete_unmatched_files=True, 871 ignore_hidden=False, 872 num_worker_processes=1, 873 description="Deleting", 874 ) 875 # If this is a posix storage provider, we need to also delete remaining directory stubs. 876 # TODO: Notify metadata provider of the changes. 877 if self._is_posix_file_storage_provider(): 878 posix_storage_provider = cast(PosixFileStorageProvider, self._storage_provider) 879 posix_storage_provider.rmtree(path) 880 return 881 else: 882 # 1) If path is a file: delete the file 883 # 2) If path is a directory: raise an error to prompt the user to use the recursive flag 884 if is_file: 885 virtual_path = path 886 if self._metadata_provider: 887 resolved = self._metadata_provider.realpath(path) 888 if not resolved.exists: 889 raise FileNotFoundError(f"The file at path '{virtual_path}' was not found.") 890 891 # Check if soft-delete is enabled 892 if not self._metadata_provider.should_use_soft_delete(): 893 # Hard delete: remove both physical file and metadata 894 if obj_metadata.symlink_target: 895 with contextlib.suppress(FileNotFoundError): 896 self._storage_provider.delete_object( 897 getattr(obj_metadata, "physical_path", None) or path 898 ) 899 else: 900 self._storage_provider.delete_object(resolved.physical_path) 901 902 with self._metadata_provider_lock or contextlib.nullcontext(): 903 self._metadata_provider.remove_file(virtual_path) 904 else: 905 self._storage_provider.delete_object(path) 906 907 # Delete the cached file if it exists 908 if self._is_cache_enabled(): 909 if self._cache_manager is None: 910 raise RuntimeError("Cache manager is not initialized") 911 self._cache_manager.delete(virtual_path) 912 913 # Delete from replicas if replica manager exists 914 if self._replica_manager: 915 self._replica_manager.delete_from_replicas(virtual_path) 916 elif is_dir: 917 raise ValueError(f"'{path}' is a directory. Set recursive=True to delete entire directory.") 918 else: 919 raise FileNotFoundError(f"The file at '{path}' was not found.")
920
[docs] 921 @retry 922 def delete_many(self, paths: Sequence[str]) -> None: 923 """ 924 Delete multiple files at the specified paths. Only files are supported; directories are not deleted. 925 926 :param paths: List of logical paths of the files to delete. 927 """ 928 self._ensure_writable() 929 physical_paths_to_delete: list[str] = [] 930 metadata_paths_to_remove: set[str] = set() 931 for path in paths: 932 if self._metadata_provider: 933 resolved = self._metadata_provider.realpath(path) 934 if not resolved.exists: 935 continue 936 metadata_paths_to_remove.add(path) 937 if not self._metadata_provider.should_use_soft_delete(): 938 obj_metadata = self._metadata_provider.get_object_metadata(path) 939 if obj_metadata.symlink_target: 940 physical_paths_to_delete.append(getattr(obj_metadata, "physical_path", None) or path) 941 else: 942 physical_paths_to_delete.append(resolved.physical_path) 943 else: 944 physical_paths_to_delete.append(path) 945 946 if physical_paths_to_delete: 947 self._storage_provider.delete_objects(physical_paths_to_delete) 948 949 for path in paths: 950 virtual_path = path 951 if self._metadata_provider and virtual_path in metadata_paths_to_remove: 952 with self._metadata_provider_lock or contextlib.nullcontext(): 953 self._metadata_provider.remove_file(virtual_path) 954 if self._is_cache_enabled(): 955 if self._cache_manager is None: 956 raise RuntimeError("Cache manager is not initialized") 957 self._cache_manager.delete(virtual_path) 958 if self._replica_manager: 959 self._replica_manager.delete_from_replicas(virtual_path)
960
[docs] 961 def glob( 962 self, 963 pattern: str, 964 include_url_prefix: bool = False, 965 attribute_filter_expression: str | None = None, 966 ) -> list[str]: 967 """ 968 Matches and retrieves a list of object keys in the storage provider that match the specified pattern. 969 970 :param pattern: The pattern to match object keys against, supporting wildcards (e.g., ``*.txt``). 971 :param include_url_prefix: Whether to include the URL prefix ``msc://profile`` in the result. 972 :param attribute_filter_expression: The attribute filter expression to apply to the result. 973 :return: A list of object paths that match the specified pattern. 974 """ 975 self._ensure_current_process() 976 if self._metadata_provider: 977 results = self._metadata_provider.glob(pattern, attribute_filter_expression) 978 else: 979 results = self._storage_provider.glob(pattern, attribute_filter_expression) 980 981 if include_url_prefix: 982 results = [self.url(path) for path in results] 983 984 return results
985 986 def _resolve_single_file( 987 self, 988 path: str, 989 start_after: str | None, 990 end_at: str | None, 991 include_url_prefix: bool, 992 pattern_matcher: PatternMatcher | None, 993 ) -> tuple[ObjectMetadata | None, str | None]: 994 """ 995 Resolve whether ``path`` should be handled as a single-file listing result. 996 997 :param path: Candidate file path or directory prefix to resolve. 998 :param start_after: Exclusive lower bound for file key filtering. 999 :param end_at: Inclusive upper bound for file key filtering. 1000 :param include_url_prefix: Whether to prefix returned keys with ``msc://profile``. 1001 :param pattern_matcher: Optional include/exclude matcher for file keys. 1002 :return: A tuple of ``(single_file, normalized_path)``. Returns file metadata and 1003 the original path when ``path`` resolves to a file that passes filters; 1004 returns ``(None, normalized_directory_path)`` when the caller should 1005 continue with directory listing; returns ``(None, None)`` when filtering 1006 excludes the single-file candidate and listing should stop. 1007 """ 1008 if not path: 1009 return None, path 1010 1011 if self._is_posix_file_storage_provider() and not self._metadata_provider: 1012 provider = cast(PosixFileStorageProvider, self._storage_provider) 1013 normalized_path = path.rstrip("/") or path 1014 physical_path = provider._prepend_base_path(normalized_path) 1015 if os.path.islink(physical_path): 1016 return None, normalized_path 1017 1018 if self.is_file(path): 1019 if pattern_matcher and not pattern_matcher.should_include_file(path): 1020 return None, None 1021 1022 try: 1023 object_metadata = self.info(path) 1024 if start_after and object_metadata.key <= start_after: 1025 return None, None 1026 if end_at and object_metadata.key > end_at: 1027 return None, None 1028 if include_url_prefix: 1029 object_metadata = self._with_url_prefix(object_metadata) 1030 return object_metadata, path 1031 except FileNotFoundError: 1032 pass 1033 if self._config.read_only and path.endswith("/"): 1034 return None, path 1035 return None, path.rstrip("/") + "/" 1036 1037 def _with_url_prefix(self, obj: ObjectMetadata) -> ObjectMetadata: 1038 # Return a copy: listed objects may be owned by the metadata provider and must not be mutated. 1039 if self.is_default_profile(): 1040 return obj.replace(key=str(PurePosixPath("/") / obj.key)) 1041 return obj.replace(key=self.url(obj.key)) 1042 1043 def _filter_and_decorate( 1044 self, 1045 objects: Iterator[ObjectMetadata], 1046 include_url_prefix: bool, 1047 pattern_matcher: PatternMatcher | None, 1048 ) -> Iterator[ObjectMetadata]: 1049 for obj in self._process_local_listing(objects): 1050 if pattern_matcher and not pattern_matcher.should_include_file(obj.key): 1051 continue 1052 if include_url_prefix: 1053 obj = self._with_url_prefix(obj) 1054 yield obj 1055
[docs] 1056 def list_recursive( 1057 self, 1058 path: str = "", 1059 start_after: str | None = None, 1060 end_at: str | None = None, 1061 max_workers: int = 32, 1062 look_ahead: int = 2, 1063 include_url_prefix: bool = False, 1064 patterns: PatternList | None = None, 1065 symlink_handling: SymlinkHandling = SymlinkHandling.FOLLOW, 1066 ) -> Iterator[ObjectMetadata]: 1067 """ 1068 List files recursively in the storage provider under the specified path. 1069 1070 :param path: The directory or file path to list objects under. This should be a 1071 complete filesystem path (e.g., "my-bucket/documents/" or "data/2024/"). 1072 :param start_after: The key to start after (i.e. exclusive). An object with this key doesn't have to exist. 1073 :param end_at: The key to end at (i.e. inclusive). An object with this key doesn't have to exist. 1074 :param max_workers: Maximum concurrent workers for provider-level recursive listing. 1075 :param look_ahead: Prefixes to buffer per worker for provider-level recursive listing. 1076 :param include_url_prefix: Whether to include the URL prefix ``msc://profile`` in the result. 1077 :param patterns: PatternList for include/exclude filtering. If None, all files are included. 1078 :param symlink_handling: How to handle symbolic links during listing. Only applicable for POSIX file storage providers. 1079 :return: An iterator over ObjectMetadata for matching files. 1080 """ 1081 self._ensure_current_process() 1082 pattern_matcher = PatternMatcher(patterns) if patterns else None 1083 1084 single_file, effective_path = self._resolve_single_file( 1085 path, start_after, end_at, include_url_prefix, pattern_matcher 1086 ) 1087 if single_file is not None: 1088 yield single_file 1089 return 1090 if effective_path is None: 1091 return 1092 1093 if self._metadata_provider: 1094 objects = self._metadata_provider.list_objects( 1095 effective_path, 1096 start_after=start_after, 1097 end_at=end_at, 1098 include_directories=False, 1099 ) 1100 else: 1101 objects = self._storage_provider.list_objects_recursive( 1102 effective_path, 1103 start_after=start_after, 1104 end_at=end_at, 1105 max_workers=max_workers, 1106 look_ahead=look_ahead, 1107 symlink_handling=symlink_handling, 1108 ) 1109 1110 yield from self._filter_and_decorate(objects, include_url_prefix, pattern_matcher)
1111
[docs] 1112 def open( 1113 self, 1114 path: str, 1115 mode: str = "rb", 1116 buffering: int = -1, 1117 encoding: str | None = None, 1118 disable_read_cache: bool = False, 1119 memory_load_limit: int = MEMORY_LOAD_LIMIT, 1120 atomic: bool = True, 1121 check_source_version: SourceVersionCheckMode = SourceVersionCheckMode.INHERIT, 1122 attributes: dict[str, Any] | None = None, 1123 prefetch_file: bool | None = None, 1124 writer_options: StreamingWriterOptions | None = None, 1125 ) -> PosixFile | ObjectFile: 1126 """ 1127 Open a file for reading or writing. 1128 1129 :param path: The logical path of the object to open. 1130 :param mode: The file mode. Supported modes: "r", "rb", "w", "wb", "a", "ab". 1131 :param buffering: The buffering mode. Only applies to PosixFile. 1132 :param encoding: The encoding to use for text files. 1133 :param disable_read_cache: When set to ``True``, disables caching for file content. 1134 This parameter is only applicable to ObjectFile when the mode is "r" or "rb". 1135 :param memory_load_limit: Size limit in bytes for loading files into memory. Defaults to 512MB. 1136 This parameter is only applicable to ObjectFile when the mode is "r" or "rb". Defaults to 512MB. 1137 :param atomic: When set to ``True``, file will be written atomically (rename upon close). 1138 This parameter is only applicable to PosixFile in write mode. 1139 :param check_source_version: Whether to check the source version of cached objects. 1140 :param attributes: Attributes to add to the file. 1141 This parameter is only applicable when the mode is "w" or "wb" or "a" or "ab". Defaults to None. 1142 :param prefetch_file: Whether to prefetch the file content. 1143 This parameter is only applicable to ObjectFile when the mode is "r" or "rb". 1144 If None, inherits from cache configuration. 1145 :param writer_options: Stream the object through a bounded multipart upload instead of buffering it in memory. 1146 Only valid with mode ``"wb"`` on a storage provider that supports streaming writes. 1147 :return: A file-like object (PosixFile or ObjectFile) for the specified path. 1148 :raises FileNotFoundError: If the file does not exist (read mode). 1149 :raises ValueError: If ``writer_options`` is set with a mode other than ``"wb"``. 1150 :raises NotImplementedError: If ``writer_options`` is set and the storage provider does not support streaming writes. 1151 """ 1152 self._ensure_open_mode(mode) 1153 if writer_options is not None and mode != "wb": 1154 raise ValueError(f'writer_options requires mode "wb", got {mode!r}.') 1155 self._ensure_current_process() 1156 if self._is_posix_file_storage_provider(): 1157 if writer_options is not None: 1158 raise NotImplementedError("Streaming writes are not supported by POSIX file storage providers.") 1159 return PosixFile( 1160 self, path=path, mode=mode, buffering=buffering, encoding=encoding, atomic=atomic, attributes=attributes 1161 ) 1162 else: 1163 if atomic is False: 1164 logger.warning("Non-atomic writes are not supported for object storage providers.") 1165 1166 return ObjectFile( 1167 self, 1168 remote_path=path, 1169 mode=mode, 1170 encoding=encoding, 1171 disable_read_cache=disable_read_cache, 1172 memory_load_limit=memory_load_limit, 1173 check_source_version=check_source_version, 1174 attributes=attributes, 1175 prefetch_file=prefetch_file, 1176 streaming_writer=( 1177 self._open_streaming_writer(path, attributes, writer_options) 1178 if writer_options is not None 1179 else None 1180 ), 1181 )
1182
[docs] 1183 def get_posix_path(self, path: str) -> str | None: 1184 """ 1185 Returns the physical POSIX filesystem path for POSIX storage providers. 1186 1187 :param path: The path to resolve (may be a symlink or virtual path). 1188 :return: Physical POSIX filesystem path if POSIX storage, None otherwise. 1189 """ 1190 self._ensure_current_process() 1191 if not self._is_posix_file_storage_provider(): 1192 return None 1193 1194 self._ensure_path_export_allowed() 1195 realpath = self._metadata_provider.realpath(path).physical_path if self._metadata_provider else path 1196 return cast(PosixFileStorageProvider, self._storage_provider)._prepend_base_path(realpath)
1197
[docs] 1198 def is_file(self, path: str) -> bool: 1199 """ 1200 Checks whether the specified path points to a file (rather than a folder or directory). 1201 1202 :param path: The logical path to check. 1203 :return: ``True`` if the key points to a file, ``False`` otherwise. 1204 """ 1205 self._ensure_current_process() 1206 if self._metadata_provider: 1207 resolved = self._metadata_provider.realpath(path) 1208 return resolved.exists 1209 1210 return self._storage_provider.is_file(path)
1211
[docs] 1212 def commit_metadata(self, prefix: str | None = None) -> None: 1213 """ 1214 Commits any pending updates to the metadata provider. No-op if not using a metadata provider. 1215 1216 :param prefix: If provided, scans the prefix to find files to commit. 1217 """ 1218 self._ensure_writable() 1219 if self._metadata_provider: 1220 with self._metadata_provider_lock or contextlib.nullcontext(): 1221 if prefix: 1222 base_resolved = self._metadata_provider.generate_physical_path("") 1223 physical_base = base_resolved.physical_path 1224 1225 prefix_resolved = self._metadata_provider.generate_physical_path(prefix) 1226 physical_prefix = prefix_resolved.physical_path 1227 1228 for obj in self._storage_provider.list_objects(physical_prefix): 1229 virtual_path = obj.key[len(physical_base) :].lstrip("/") 1230 self._metadata_provider.add_file(virtual_path, obj) 1231 self._metadata_provider.commit_updates()
1232
[docs] 1233 def is_empty(self, path: str) -> bool: 1234 """ 1235 Check whether the specified path is empty. A path is considered empty if there are no 1236 objects whose keys start with the given path as a prefix. 1237 1238 :param path: The logical path to check (typically a directory or folder prefix). 1239 :return: ``True`` if no objects exist under the specified path prefix, ``False`` otherwise. 1240 """ 1241 self._ensure_current_process() 1242 if self._metadata_provider: 1243 objects = self._metadata_provider.list_objects(path) 1244 else: 1245 objects = self._storage_provider.list_objects(path) 1246 1247 try: 1248 return next(objects) is None 1249 except StopIteration: 1250 pass 1251 1252 return True
1253
[docs] 1254 def sync_from( 1255 self, 1256 source_client: AbstractStorageClient, 1257 source_path: str = "", 1258 target_path: str = "", 1259 delete_unmatched_files: bool = False, 1260 description: str = "Syncing", 1261 num_worker_processes: int | None = None, 1262 execution_mode: ExecutionMode = ExecutionMode.LOCAL, 1263 patterns: PatternList | None = None, 1264 preserve_source_attributes: bool = False, 1265 source_files: list[str] | None = None, 1266 ignore_hidden: bool = True, 1267 commit_metadata: bool = True, 1268 dryrun: bool = False, 1269 dryrun_output_path: str | None = None, 1270 symlink_handling: SymlinkHandling = SymlinkHandling.FOLLOW, 1271 ) -> SyncResult: 1272 """ 1273 Syncs files from the source storage client to "path/". 1274 1275 :param source_client: The source storage client. 1276 :param source_path: The logical path to sync from. 1277 :param target_path: The logical path to sync to. 1278 :param delete_unmatched_files: Whether to delete files at the target that are not present at the source. 1279 :param description: Description of sync process for logging purposes. 1280 :param num_worker_processes: The number of worker processes to use. 1281 :param execution_mode: The execution mode to use. Currently supports "local" and "ray". 1282 :param patterns: PatternList for include/exclude filtering. If None, all files are included. 1283 Cannot be used together with source_files. 1284 :param preserve_source_attributes: Whether to preserve source file metadata attributes during synchronization. 1285 When ``False`` (default), only file content is copied. When ``True``, custom metadata attributes are also preserved. 1286 1287 .. warning:: 1288 **Performance Impact**: When enabled without a ``metadata_provider`` configured, this will make a HEAD 1289 request for each object to retrieve attributes, which can significantly impact performance on large-scale 1290 sync operations. For production use at scale, configure a ``metadata_provider`` in your storage profile. 1291 1292 :param source_files: Optional list of file paths (relative to source_path) to sync. When provided, only these 1293 specific files will be synced, skipping enumeration of the source path. Cannot be used together with patterns. 1294 :param ignore_hidden: Whether to ignore hidden files and directories. Default is ``True``. 1295 :param commit_metadata: When ``True`` (default), calls :py:meth:`StorageClient.commit_metadata` after sync completes. 1296 Set to ``False`` to skip the commit, allowing batching of multiple sync operations before committing manually. 1297 :param dryrun: If ``True``, only enumerate and compare objects without performing any copy/delete operations. 1298 The returned :py:class:`SyncResult` will include a :py:class:`DryrunResult` with paths to JSONL files. 1299 :param dryrun_output_path: Directory to write dryrun JSONL files into. If ``None`` (default), a temporary 1300 directory is created automatically. Ignored when ``dryrun`` is ``False``. 1301 :param symlink_handling: How to handle symbolic links during sync. 1302 :py:attr:`SymlinkHandling.FOLLOW` (default) dereferences symlinks and copies the target's bytes. 1303 :py:attr:`SymlinkHandling.SKIP` excludes symlinks from the sync. 1304 :py:attr:`SymlinkHandling.PRESERVE` recreates symlinks on the target via :py:meth:`make_symlink` 1305 instead of copying bytes (required for round-trip preservation of symlinks). 1306 :raises ValueError: If both source_files and patterns are provided. 1307 :raises RuntimeError: If errors occur during sync operations. The sync will stop on first error (fail-fast). 1308 """ 1309 self._ensure_writable() 1310 if source_files and patterns: 1311 raise ValueError("Cannot specify both 'source_files' and 'patterns'. Please use only one filtering method.") 1312 1313 pattern_matcher = PatternMatcher(patterns) if patterns else None 1314 1315 # Disable the replica manager during sync 1316 if not isinstance(source_client, NullStorageClient) and source_client._replica_manager: 1317 # Import here to avoid circular dependency 1318 from .client import StorageClient as StorageClientFacade 1319 1320 source_client = StorageClientFacade(source_client._config) 1321 source_client._replica_manager = None 1322 1323 m = SyncManager(source_client, source_path, self, target_path) 1324 batch_size = int(os.environ.get("MSC_SYNC_BATCH_SIZE", DEFAULT_SYNC_BATCH_SIZE)) 1325 1326 return m.sync_objects( 1327 execution_mode=execution_mode, 1328 description=description, 1329 num_worker_processes=num_worker_processes, 1330 delete_unmatched_files=delete_unmatched_files, 1331 pattern_matcher=pattern_matcher, 1332 preserve_source_attributes=preserve_source_attributes, 1333 symlink_handling=symlink_handling, 1334 source_files=source_files, 1335 ignore_hidden=ignore_hidden, 1336 commit_metadata=commit_metadata, 1337 batch_size=batch_size, 1338 dryrun=dryrun, 1339 dryrun_output_path=dryrun_output_path, 1340 )
1341
[docs] 1342 def sync_replicas( 1343 self, 1344 source_path: str, 1345 replica_indices: Sequence[int] | None = None, 1346 delete_unmatched_files: bool = False, 1347 description: str = "Syncing replica", 1348 num_worker_processes: int | None = None, 1349 execution_mode: ExecutionMode = ExecutionMode.LOCAL, 1350 patterns: PatternList | None = None, 1351 ignore_hidden: bool = True, 1352 symlink_handling: SymlinkHandling = SymlinkHandling.FOLLOW, 1353 ) -> None: 1354 """ 1355 Sync files from this client to its replica storage clients. 1356 1357 :param source_path: The logical path to sync from. 1358 :param replica_indices: Specific replica indices to sync to (0-indexed). If None, syncs to all writable replicas. 1359 Read-only replicas are skipped by default; explicitly selecting one raises ``ValueError``. 1360 :param delete_unmatched_files: When set to ``True``, delete files in replicas that don't exist in source. 1361 :param description: Description of sync process for logging purposes. 1362 :param num_worker_processes: Number of worker processes for parallel sync. 1363 :param execution_mode: Execution mode (LOCAL or REMOTE). 1364 :param patterns: PatternList for include/exclude filtering. If None, all files are included. 1365 :param ignore_hidden: When set to ``True``, ignore hidden files (starting with '.'). Defaults to ``True``. 1366 :param symlink_handling: How to handle symbolic links during sync. 1367 :py:attr:`SymlinkHandling.FOLLOW` (default) dereferences symlinks and copies the target's bytes. 1368 :py:attr:`SymlinkHandling.SKIP` excludes symlinks from the sync. 1369 :py:attr:`SymlinkHandling.PRESERVE` recreates symlinks on each replica via 1370 :py:meth:`make_symlink` instead of copying bytes. 1371 """ 1372 self._ensure_writable() 1373 if not self._replicas: 1374 logger.warning( 1375 "No replicas found in profile '%s'. Add a 'replicas' section to your profile configuration to enable " 1376 "secondary storage locations for redundancy and performance.", 1377 self._config.profile, 1378 ) 1379 return 1380 1381 if replica_indices: 1382 try: 1383 replicas = [self._replicas[i] for i in replica_indices] 1384 except IndexError as e: 1385 raise ValueError(f"Replica index out of range: {replica_indices}") from e 1386 for index, replica in zip(replica_indices, replicas): 1387 if replica not in self._writable_replicas: 1388 raise ValueError(f"Replica index {index} ('{replica.profile}') is read-only and cannot be synced") 1389 else: 1390 replicas = self._writable_replicas 1391 1392 if not replicas: 1393 logger.warning("No writable replicas configured for profile '%s'; sync skipped", self._config.profile) 1394 return 1395 1396 # Disable the replica manager during sync 1397 if self._replica_manager: 1398 # Import here to avoid circular dependency 1399 from .client import StorageClient as StorageClientFacade 1400 1401 source_client = StorageClientFacade(self._config) 1402 source_client._replica_manager = None 1403 else: 1404 source_client = self 1405 1406 for replica in replicas: 1407 replica.sync_from( 1408 source_client, 1409 source_path, 1410 source_path, 1411 delete_unmatched_files=delete_unmatched_files, 1412 description=f"{description} ({replica.profile})", 1413 num_worker_processes=num_worker_processes, 1414 execution_mode=execution_mode, 1415 patterns=patterns, 1416 ignore_hidden=ignore_hidden, 1417 symlink_handling=symlink_handling, 1418 )
1419
[docs] 1420 def list( 1421 self, 1422 path: str = "", 1423 start_after: str | None = None, 1424 end_at: str | None = None, 1425 include_directories: bool = False, 1426 include_url_prefix: bool = False, 1427 attribute_filter_expression: str | None = None, 1428 show_attributes: bool = False, 1429 patterns: PatternList | None = None, 1430 symlink_handling: SymlinkHandling = SymlinkHandling.FOLLOW, 1431 ) -> Iterator[ObjectMetadata]: 1432 """ 1433 List objects in the storage provider under the specified path. 1434 1435 :param path: The directory or file path to list objects under. This should be a 1436 complete filesystem path (e.g., "my-bucket/documents/" or "data/2024/"). 1437 :param start_after: The key to start after (i.e. exclusive). An object with this key doesn't have to exist. 1438 :param end_at: The key to end at (i.e. inclusive). An object with this key doesn't have to exist. 1439 :param include_directories: Whether to include directories in the result. When ``True``, directories are returned alongside objects. 1440 :param include_url_prefix: Whether to include the URL prefix ``msc://profile`` in the result. 1441 :param attribute_filter_expression: The attribute filter expression to apply to the result. 1442 :param show_attributes: Whether to return attributes in the result. WARNING: Depending on implementation, there may be a performance impact if this is set to ``True``. 1443 :param patterns: PatternList for include/exclude filtering. If None, all files are included. 1444 :param symlink_handling: How to handle symbolic links during listing. Only applicable for POSIX file storage providers. 1445 :return: An iterator over ObjectMetadata for matching objects. 1446 """ 1447 self._ensure_current_process() 1448 pattern_matcher = PatternMatcher(patterns) if patterns else None 1449 1450 single_file, effective_path = self._resolve_single_file( 1451 path, start_after, end_at, include_url_prefix, pattern_matcher 1452 ) 1453 if single_file is not None: 1454 evaluator = ( 1455 create_attribute_filter_evaluator(attribute_filter_expression) if attribute_filter_expression else None 1456 ) 1457 if matches_attribute_filter_expression(single_file, evaluator): 1458 yield single_file 1459 return 1460 if effective_path is None: 1461 return 1462 1463 if self._metadata_provider: 1464 objects = self._metadata_provider.list_objects( 1465 effective_path, 1466 start_after=start_after, 1467 end_at=end_at, 1468 include_directories=include_directories, 1469 attribute_filter_expression=attribute_filter_expression, 1470 show_attributes=show_attributes, 1471 ) 1472 else: 1473 objects = self._storage_provider.list_objects( 1474 effective_path, 1475 start_after=start_after, 1476 end_at=end_at, 1477 include_directories=include_directories, 1478 attribute_filter_expression=attribute_filter_expression, 1479 show_attributes=show_attributes, 1480 symlink_handling=symlink_handling, 1481 ) 1482 1483 yield from self._filter_and_decorate(objects, include_url_prefix, pattern_matcher)
1484
[docs] 1485 def generate_presigned_url( 1486 self, 1487 path: str, 1488 *, 1489 method: str = "GET", 1490 signer_type: SignerType | None = None, 1491 signer_options: dict[str, Any] | None = None, 1492 ) -> str: 1493 self._ensure_signing_method(method) 1494 self._ensure_current_process() 1495 if self._metadata_provider: 1496 if method.upper() not in ("GET", "HEAD"): 1497 raise ValueError( 1498 f"Presigned {method.upper()} URLs are not supported when a metadata provider is configured; " 1499 "uploads through such a URL would bypass the metadata provider." 1500 ) 1501 path = self._resolve_read_path(path) 1502 return self._storage_provider.generate_presigned_url( 1503 path, method=method, signer_type=signer_type, signer_options=signer_options 1504 )