Source code for multistorageclient.config

   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 copy
  17import json
  18import logging
  19import os
  20import tempfile
  21from collections import Counter, defaultdict
  22from collections.abc import Callable, Iterable
  23from dataclasses import replace
  24from pathlib import Path
  25from typing import Any
  26from urllib.parse import urlparse
  27
  28import yaml
  29
  30from .cache import DEFAULT_CACHE_LINE_SIZE, DEFAULT_CACHE_SIZE, CacheManager
  31from .caching.cache_config import CacheConfig, EvictionPolicyConfig
  32from .providers.manifest_metadata import ManifestMetadataProvider
  33from .rclone import read_rclone_config
  34from .schema import SUPPORTED_IMPLICIT_PROFILE_PROTOCOLS, validate_config
  35from .telemetry import Telemetry
  36from .telemetry import init as telemetry_init
  37from .types import (
  38    DEFAULT_RETRY_ATTEMPTS,
  39    DEFAULT_RETRY_BACKOFF_MULTIPLIER,
  40    DEFAULT_RETRY_DELAY,
  41    MSC_PROTOCOL,
  42    AutoCommitConfig,
  43    CredentialsProvider,
  44    MetadataProvider,
  45    ProviderBundle,
  46    ProviderBundleV2,
  47    Replica,
  48    RetryConfig,
  49    StorageBackend,
  50    StorageProvider,
  51    StorageProviderConfig,
  52)
  53from .utils import build_full_path, expand_env_vars, import_class, merge_dictionaries_no_overwrite
  54
  55# Constants related to implicit profiles
  56PROTOCOL_TO_PROVIDER_TYPE_MAPPING = {
  57    "s3": "s3",
  58    "gs": "gcs",
  59    "ais": "ais",
  60    "file": "file",
  61}
  62
  63
  64# Template for creating implicit profile configurations
  65def create_implicit_profile_config(profile_name: str, protocol: str, base_path: str) -> dict:
  66    """
  67    Create a configuration dictionary for an implicit profile.
  68
  69    :param profile_name: The name of the profile (e.g., "_s3-bucket1")
  70    :param protocol: The storage protocol (e.g., "s3", "gs", "ais")
  71    :param base_path: The base path (e.g., bucket name) for the storage provider
  72
  73    :return: A configuration dictionary for the implicit profile
  74    """
  75    provider_type = PROTOCOL_TO_PROVIDER_TYPE_MAPPING[protocol]
  76    return {
  77        "profiles": {profile_name: {"storage_provider": {"type": provider_type, "options": {"base_path": base_path}}}}
  78    }
  79
  80
  81RESERVED_POSIX_PROFILE_NAME = "__filesystem__"
  82DEFAULT_POSIX_PROFILE = create_implicit_profile_config(RESERVED_POSIX_PROFILE_NAME, "file", "/")
  83
  84STORAGE_PROVIDER_MAPPING = {
  85    "file": "PosixFileStorageProvider",
  86    "s3": "S3StorageProvider",
  87    "gcs": "GoogleStorageProvider",
  88    "oci": "OracleStorageProvider",
  89    "azure": "AzureBlobStorageProvider",
  90    "ais": "AIStoreStorageProvider",
  91    "ais_s3": "AIStoreS3StorageProvider",
  92    "s8k": "S8KStorageProvider",
  93    "gcs_s3": "GoogleS3StorageProvider",
  94    "s3_cuobject": "S3CuObjectStorageProvider",
  95    "huggingface": "HuggingFaceStorageProvider",
  96}
  97
  98CREDENTIALS_PROVIDER_MAPPING = {
  99    "S3Credentials": "StaticS3CredentialsProvider",
 100    "AzureCredentials": "StaticAzureCredentialsProvider",
 101    "DefaultAzureCredentials": "DefaultAzureCredentialsProvider",
 102    "AISCredentials": "StaticAISCredentialProvider",
 103    "GoogleIdentityPoolCredentialsProvider": "GoogleIdentityPoolCredentialsProvider",
 104    "GoogleServiceAccountCredentialsProvider": "GoogleServiceAccountCredentialsProvider",
 105    "HuggingFaceCredentials": "HuggingFaceCredentialsProvider",
 106    "FileBasedCredentials": "FileBasedCredentialsProvider",
 107}
 108
 109
 110def _load_config(text: str, *, is_json: bool) -> Any:
 111    """Load config and reject duplicate resolver registrations before a mapping can discard them."""
 112    if is_json:
 113        duplicates: list[tuple[dict[str, Any], list[str]]] = []
 114
 115        def load_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
 116            obj = dict(pairs)
 117            if len(obj) < len(pairs):
 118                counts = Counter(key for key, _ in pairs)
 119                duplicates.append((obj, [key for key, count in counts.items() if count > 1]))
 120            return obj
 121
 122        config = json.loads(text, object_pairs_hook=load_object)
 123        if isinstance(config, dict):
 124            for obj, keys in reversed(duplicates):
 125                if obj is config and "url_resolvers" in keys:
 126                    raise ValueError("Duplicate url_resolvers section")
 127                if obj is config.get("url_resolvers"):
 128                    raise ValueError(f"Duplicate URL resolver registration for scheme {keys[0]!r}")
 129        return config
 130
 131    loader = yaml.SafeLoader(text)
 132    try:
 133        root = loader.get_single_node()
 134        if root is None:
 135            return None
 136        if isinstance(root, yaml.MappingNode):
 137            loader.flatten_mapping(root)
 138            sections = [value for key, value in root.value if key.value == "url_resolvers"]
 139            if len(sections) > 1:
 140                raise ValueError("Duplicate url_resolvers section")
 141            if sections and isinstance(sections[0], yaml.MappingNode):
 142                loader.flatten_mapping(sections[0])
 143                schemes = set()
 144                for key, _ in sections[0].value:
 145                    if key.value in schemes:
 146                        raise ValueError(f"Duplicate URL resolver registration for scheme {key.value!r}")
 147                    schemes.add(key.value)
 148        return loader.construct_document(root)
 149    finally:
 150        loader.dispose()
 151
 152
 153_ConfigFileGeneration = tuple[str, int, int, int, int, int]
 154
 155
 156def _config_file_generation(path: str, fd: int) -> _ConfigFileGeneration:
 157    stat = os.fstat(fd)
 158    return path, stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns
 159
 160
 161def _read_config_file(path: str, generations: list[_ConfigFileGeneration] | None) -> Any:
 162    with open(path) as f:
 163        if generations is None:
 164            text = f.read()
 165        else:
 166            generation = _config_file_generation(path, f.fileno())
 167            text = f.read()
 168            if generation != _config_file_generation(path, f.fileno()):
 169                raise ValueError(f"Configuration file changed while reading: {path}")
 170            generations.append(generation)
 171    return _load_config(text, is_json=path.endswith(".json"))
 172
 173
 174def _resolve_include_path(include_path: str, parent_config_path: str) -> str:
 175    """
 176    Resolve include path (absolute or relative to parent config file).
 177
 178    :param include_path: Path from include keyword (can be absolute or relative)
 179    :param parent_config_path: Absolute path of the config file containing the include
 180    :return: Absolute, normalized path to the included config file
 181    """
 182    if os.path.isabs(include_path):
 183        return os.path.abspath(include_path)
 184    else:
 185        parent_dir = os.path.dirname(parent_config_path)
 186        return os.path.abspath(os.path.join(parent_dir, include_path))
 187
 188
 189def _merge_profiles(
 190    base_profiles: dict[str, Any],
 191    new_profiles: dict[str, Any],
 192    base_path: str,
 193    new_path: str,
 194) -> dict[str, Any]:
 195    """
 196    Merge profiles from two config files with conflict detection.
 197
 198    Profiles with the same name are allowed if their definitions are identical (idempotent).
 199    If a profile name exists in both configs with different definitions, an error is raised.
 200
 201    NOTE: This function performs SHALLOW merging - each profile is treated as a complete unit.
 202    We cannot use merge_dictionaries_no_overwrite() here because it would recursively merge
 203    profile fields, which could lead to unintended behavior. For example:
 204
 205    base_config:
 206        profiles:
 207            my-profile:
 208                storage_provider:
 209                    type: s3
 210                    options:
 211                        base_path: bucket
 212
 213    new_config:
 214        profiles:
 215            my-profile:
 216                credentials_provider:
 217                    type: S3Credentials
 218                    options:
 219                        access_key: foo
 220                        secret_key: bar
 221
 222    If we used merge_dictionaries_no_overwrite(), the result would be a profile with BOTH storage_provider
 223    and credentials_provider, which might not be the intended configuration.
 224
 225    :param base_profiles: Profiles from the base config
 226    :param new_profiles: Profiles from the new config to merge
 227    :param base_path: Path to the base config file (for error messages)
 228    :param new_path: Path to the new config file (for error messages)
 229    :return: Merged profiles dictionary
 230    :raises ValueError: If any profile name exists in both configs with different definitions
 231    """
 232    result = base_profiles.copy()
 233    conflicting_profiles = []
 234
 235    for profile_name, new_profile_def in new_profiles.items():
 236        if profile_name in result:
 237            if result[profile_name] != new_profile_def:
 238                conflicting_profiles.append(profile_name)
 239        else:
 240            result[profile_name] = new_profile_def
 241
 242    if conflicting_profiles:
 243        conflicts_list = ", ".join(f"'{p}'" for p in sorted(conflicting_profiles))
 244        raise ValueError(f"Profile conflict: {conflicts_list} defined differently in {base_path} and {new_path}")
 245
 246    return result
 247
 248
 249def _merge_opentelemetry(
 250    base_otel: dict[str, Any],
 251    new_otel: dict[str, Any],
 252    base_path: str,
 253    new_path: str,
 254) -> dict[str, Any]:
 255    """
 256    Merge opentelemetry configurations with special handling for metrics.attributes.
 257
 258    Merge strategy:
 259    - metrics.attributes: Concatenate arrays (preserve order for fallback mechanism)
 260    - Other fields: Use idempotent check (must be identical)
 261
 262    Attributes providers are concatenated to support fallback scenarios where multiple
 263    providers of the same type supply the same attribute key with different sources.
 264    The order matters - later providers override earlier ones.
 265
 266    :param base_otel: Base opentelemetry config
 267    :param new_otel: New opentelemetry config to merge
 268    :param base_path: Path to base config file (for error messages)
 269    :param new_path: Path to new config file (for error messages)
 270    :return: Merged opentelemetry configuration
 271    :raises ValueError: If conflicts are detected
 272    """
 273    # Merge metrics.attributes
 274    base_attrs = base_otel.get("metrics", {}).get("attributes", [])
 275    new_attrs = new_otel.get("metrics", {}).get("attributes", [])
 276    merged_attrs = base_attrs + new_attrs
 277
 278    # Merge other opentelemetry fields
 279    base_otel_without_attrs = copy.deepcopy(base_otel)
 280    if "metrics" in base_otel_without_attrs and "attributes" in base_otel_without_attrs["metrics"]:
 281        del base_otel_without_attrs["metrics"]["attributes"]
 282
 283    new_otel_without_attrs = copy.deepcopy(new_otel)
 284    if "metrics" in new_otel_without_attrs and "attributes" in new_otel_without_attrs["metrics"]:
 285        del new_otel_without_attrs["metrics"]["attributes"]
 286
 287    merged, conflicts = merge_dictionaries_no_overwrite(
 288        base_otel_without_attrs, new_otel_without_attrs, allow_idempotent=True
 289    )
 290
 291    if conflicts:
 292        conflicts_list = ", ".join(f"'{k}'" for k in sorted(conflicts))
 293        raise ValueError(
 294            f"opentelemetry config conflict: {conflicts_list} defined differently in {base_path} and {new_path}"
 295        )
 296
 297    if "metrics" in merged:
 298        merged["metrics"]["attributes"] = merged_attrs
 299    elif merged_attrs:
 300        merged["metrics"] = {"attributes": merged_attrs}
 301
 302    return merged
 303
 304
 305def _merge_configs(
 306    base_config: dict[str, Any],
 307    new_config: dict[str, Any],
 308    base_path: str,
 309    new_path: str,
 310) -> dict[str, Any]:
 311    """
 312    Merge two config dictionaries with field-specific strategies.
 313
 314    Different config fields have different merge strategies:
 315    - profiles: Shallow merge with idempotent check (uses _merge_profiles)
 316    - path_mapping: Flat dict merge with idempotent check
 317    - experimental_features: Flat dict merge with idempotent check
 318    - opentelemetry: Hybrid merge (attributes concatenate, others idempotent)
 319    - cache, posix: Global configs, idempotent if identical, error if different
 320
 321    :param base_config: Base configuration dictionary
 322    :param new_config: New configuration to merge
 323    :param base_path: Path to base config file (for error messages)
 324    :param new_path: Path to new config file (for error messages)
 325    :return: Merged configuration dictionary
 326    :raises ValueError: If conflicts are detected
 327    """
 328    result = {}
 329
 330    all_keys = set(base_config.keys()) | set(new_config.keys())
 331
 332    for key in all_keys:
 333        base_value = base_config.get(key)
 334        new_value = new_config.get(key)
 335
 336        # Key only in base
 337        if key not in new_config:
 338            result[key] = base_value
 339            continue
 340
 341        # Key only in new
 342        if key not in base_config:
 343            result[key] = new_value
 344            continue
 345
 346        # Key in both - need to merge or detect conflict
 347        if key == "profiles":
 348            result["profiles"] = _merge_profiles(base_value or {}, new_value or {}, base_path, new_path)
 349
 350        elif key == "url_resolvers":
 351            base_resolvers = base_config[key]
 352            new_resolvers = new_config[key]
 353            duplicates = base_resolvers.keys() & new_resolvers.keys()
 354            if duplicates:
 355                raise ValueError(f"Duplicate URL resolver registration for scheme {min(duplicates)!r}")
 356            result[key] = {**base_resolvers, **new_resolvers}
 357
 358        elif key in ("path_mapping", "experimental_features"):
 359            merged, conflicts = merge_dictionaries_no_overwrite(
 360                (base_value or {}).copy(), new_value or {}, allow_idempotent=True
 361            )
 362            if conflicts:
 363                conflicts_list = ", ".join(f"'{k}'" for k in sorted(conflicts))
 364                raise ValueError(
 365                    f"Config merge conflict: {conflicts_list} have different values in {base_path} and {new_path}"
 366                )
 367            result[key] = merged
 368
 369        elif key == "opentelemetry":
 370            result["opentelemetry"] = _merge_opentelemetry(base_value or {}, new_value or {}, base_path, new_path)
 371
 372        elif key in ("cache", "posix"):
 373            if base_value != new_value:
 374                raise ValueError(f"'{key}' defined differently in {base_path} and {new_path}")
 375            result[key] = base_value
 376
 377        elif key == "include":
 378            # 'include' is processed by _load_and_merge_includes, not part of final config
 379            pass
 380
 381        else:
 382            # This should never happen and all top level fields must have explicit handling above
 383            raise ValueError(f"Unknown field '{key}' in config file.")
 384
 385    return result
 386
 387
 388def _load_and_merge_includes(
 389    main_config_path: str,
 390    main_config_dict: dict[str, Any],
 391    generations: list[_ConfigFileGeneration] | None = None,
 392) -> dict[str, Any]:
 393    """
 394    Load and merge included config files.
 395
 396    Processes the 'include' directive in the main config, loading and merging all
 397    specified config files. Only supports one level of includes - included files
 398    cannot themselves have 'include' directives.
 399
 400    :param main_config_path: Absolute path to the main config file
 401    :param main_config_dict: Dictionary loaded from the main config file
 402    :return: Merged configuration dictionary (without 'include' field)
 403    :raises ValueError: If include file not found, malformed, or contains nested includes
 404    """
 405    include_paths = main_config_dict.get("include", [])
 406
 407    if not include_paths:
 408        return {k: v for k, v in main_config_dict.items() if k != "include"}
 409
 410    merged_config = {k: v for k, v in main_config_dict.items() if k != "include"}
 411
 412    for include_path in include_paths:
 413        resolved_path = _resolve_include_path(include_path, main_config_path)
 414
 415        if not os.path.exists(resolved_path):
 416            raise ValueError(f"Included config file not found: {resolved_path} (from {main_config_path})")
 417
 418        try:
 419            included_config = _read_config_file(resolved_path, generations)
 420        except Exception as e:
 421            raise ValueError(f"Failed to load included config {resolved_path}: {e}")
 422
 423        validate_config(included_config)
 424        if "include" in included_config:
 425            raise ValueError(f"Nested includes not allowed: {resolved_path} contains 'include' directive")
 426
 427        merged_config = _merge_configs(merged_config, included_config, main_config_path, resolved_path)
 428
 429    return merged_config
 430
 431
 432def _find_config_file_paths() -> tuple[str, ...]:
 433    """
 434    Get configuration file search paths.
 435
 436    Returns paths in order of precedence:
 437
 438    1. User-specific config (${XDG_CONFIG_HOME}/msc/, ${HOME}/, ${HOME}/.config/msc/)
 439    2. System-wide configs (${XDG_CONFIG_DIRS}/msc/, /etc/xdg, /etc/)
 440    """
 441    paths = []
 442
 443    # 1. User-specific configuration directory
 444    xdg_config_home = os.getenv("XDG_CONFIG_HOME")
 445
 446    if xdg_config_home:
 447        paths.extend(
 448            [
 449                os.path.join(xdg_config_home, "msc", "config.yaml"),
 450                os.path.join(xdg_config_home, "msc", "config.json"),
 451            ]
 452        )
 453
 454    user_home = os.getenv("HOME")
 455
 456    if user_home:
 457        paths.extend(
 458            [
 459                os.path.join(user_home, ".msc_config.yaml"),
 460                os.path.join(user_home, ".msc_config.json"),
 461                os.path.join(user_home, ".config", "msc", "config.yaml"),
 462                os.path.join(user_home, ".config", "msc", "config.json"),
 463            ]
 464        )
 465
 466    # 2. System-wide configuration directories
 467    xdg_config_dirs = os.getenv("XDG_CONFIG_DIRS")
 468    if not xdg_config_dirs:
 469        xdg_config_dirs = "/etc/xdg"
 470
 471    for config_dir in xdg_config_dirs.split(":"):
 472        config_dir = config_dir.strip()
 473        if config_dir:
 474            paths.extend(
 475                [
 476                    os.path.join(config_dir, "msc", "config.yaml"),
 477                    os.path.join(config_dir, "msc", "config.json"),
 478                ]
 479            )
 480
 481    paths.extend(
 482        [
 483            "/etc/msc_config.yaml",
 484            "/etc/msc_config.json",
 485        ]
 486    )
 487
 488    return tuple(paths)
 489
 490
 491PACKAGE_NAME = "multistorageclient"
 492
 493logger = logging.getLogger(__name__)
 494
 495
 496class ImmutableDict(dict):
 497    """
 498    Immutable dictionary that raises an error when attempting to modify it.
 499    """
 500
 501    def __init__(self, *args, **kwargs):
 502        super().__init__(*args, **kwargs)
 503
 504        # Recursively freeze nested structures
 505        for key, value in list(super().items()):
 506            if isinstance(value, dict) and not isinstance(value, ImmutableDict):
 507                super().__setitem__(key, ImmutableDict(value))
 508            elif isinstance(value, list):
 509                super().__setitem__(key, self._freeze_list(value))
 510
 511    @staticmethod
 512    def _freeze_list(lst):
 513        """
 514        Convert list to tuple, freezing nested dicts recursively.
 515        """
 516        frozen = []
 517        for item in lst:
 518            if isinstance(item, dict):
 519                frozen.append(ImmutableDict(item))
 520            elif isinstance(item, list):
 521                frozen.append(ImmutableDict._freeze_list(item))
 522            else:
 523                frozen.append(item)
 524        return tuple(frozen)
 525
 526    def __deepcopy__(self, memo):
 527        """
 528        Return a regular mutable dict when deepcopy is called.
 529        """
 530        # dict(self) would keep the frozen tuples; _copy_value converts nested structures back to dicts and lists.
 531        return copy.deepcopy(self._copy_value(self), memo)
 532
 533    def __reduce__(self):
 534        """
 535        Support for pickle serialization.
 536        """
 537        return (self.__class__, (dict(self),))
 538
 539    def _copy_value(self, value):
 540        """
 541        Convert frozen structures back to mutable equivalents.
 542        """
 543        if isinstance(value, ImmutableDict):
 544            return {k: self._copy_value(v) for k, v in value.items()}
 545        elif isinstance(value, tuple):
 546            # Check if it was originally a list (frozen by _freeze_list)
 547            return [self._copy_value(item) for item in value]
 548        else:
 549            return value
 550
 551    def __getitem__(self, key):
 552        """
 553        Return a mutable copy of the value.
 554        """
 555        value = super().__getitem__(key)
 556        return self._copy_value(value)
 557
 558    def get(self, key, default=None):
 559        """
 560        Return a mutable copy of the value.
 561        """
 562        return self[key] if key in self else default  # noqa: SIM401
 563
 564    def __setitem__(self, key, value):
 565        raise TypeError("ImmutableDict is immutable")
 566
 567    def __delitem__(self, key):
 568        raise TypeError("ImmutableDict is immutable")
 569
 570    def __ior__(self, other):
 571        raise TypeError("ImmutableDict is immutable")
 572
 573    def clear(self):
 574        raise TypeError("ImmutableDict is immutable")
 575
 576    def pop(self, *args):
 577        raise TypeError("ImmutableDict is immutable")
 578
 579    def popitem(self):
 580        raise TypeError("ImmutableDict is immutable")
 581
 582    def setdefault(self, key, default=None):
 583        raise TypeError("ImmutableDict is immutable")
 584
 585    def update(self, *args, **kwargs):
 586        raise TypeError("ImmutableDict is immutable")
 587
 588
 589class SimpleProviderBundle(ProviderBundle):
 590    def __init__(
 591        self,
 592        storage_provider_config: StorageProviderConfig,
 593        credentials_provider: CredentialsProvider | None = None,
 594        metadata_provider: MetadataProvider | None = None,
 595        replicas: list[Replica] | None = None,
 596    ):
 597        if replicas is None:
 598            replicas = []
 599
 600        self._storage_provider_config = storage_provider_config
 601        self._credentials_provider = credentials_provider
 602        self._metadata_provider = metadata_provider
 603        self._replicas = replicas
 604
 605    @property
 606    def storage_provider_config(self) -> StorageProviderConfig:
 607        return self._storage_provider_config
 608
 609    @property
 610    def credentials_provider(self) -> CredentialsProvider | None:
 611        return self._credentials_provider
 612
 613    @property
 614    def metadata_provider(self) -> MetadataProvider | None:
 615        return self._metadata_provider
 616
 617    @property
 618    def replicas(self) -> list[Replica]:
 619        return self._replicas
 620
 621
 622class SimpleProviderBundleV2(ProviderBundleV2):
 623    def __init__(self, storage_backends: dict[str, StorageBackend], metadata_provider: MetadataProvider | None = None):
 624        self._storage_backends = storage_backends
 625        self._metadata_provider = metadata_provider
 626
 627    @staticmethod
 628    def from_v1_bundle(profile_name: str, v1_bundle: ProviderBundle) -> "SimpleProviderBundleV2":
 629        backend = StorageBackend(
 630            storage_provider_config=v1_bundle.storage_provider_config,
 631            credentials_provider=v1_bundle.credentials_provider,
 632            replicas=v1_bundle.replicas,
 633        )
 634
 635        return SimpleProviderBundleV2(
 636            storage_backends={profile_name: backend},
 637            metadata_provider=v1_bundle.metadata_provider,
 638        )
 639
 640    @property
 641    def storage_backends(self) -> dict[str, StorageBackend]:
 642        return self._storage_backends
 643
 644    @property
 645    def metadata_provider(self) -> MetadataProvider | None:
 646        return self._metadata_provider
 647
 648
 649DEFAULT_CACHE_REFRESH_INTERVAL = 300
 650
 651
 652class StorageClientConfigLoader:
 653    _provider_bundle: ProviderBundleV2
 654    _resolved_config_dict: dict[str, Any]
 655    _profiles: dict[str, Any]
 656    _profile: str
 657    _profile_dict: dict[str, Any]
 658    _opentelemetry_dict: dict[str, Any] | None
 659    _telemetry_provider: Callable[[], Telemetry] | None
 660    _cache_dict: dict[str, Any] | None
 661
 662    def __init__(
 663        self,
 664        config_dict: dict[str, Any],
 665        profile: str = RESERVED_POSIX_PROFILE_NAME,
 666        provider_bundle: ProviderBundle | ProviderBundleV2 | None = None,
 667        telemetry_provider: Callable[[], Telemetry] | None = None,
 668    ) -> None:
 669        """
 670        Initializes a :py:class:`StorageClientConfigLoader` to create a
 671        StorageClientConfig. Components are built using the ``config_dict`` and
 672        profile, but a pre-built provider_bundle takes precedence.
 673
 674        :param config_dict: Dictionary of configuration options.
 675        :param profile: Name of profile in ``config_dict`` to use to build configuration.
 676        :param provider_bundle: Optional pre-built :py:class:`multistorageclient.types.ProviderBundle` or :py:class:`multistorageclient.types.ProviderBundleV2`, takes precedence over ``config_dict``.
 677        :param telemetry_provider: A function that provides a telemetry instance. The function must be defined at the top level of a module to work with pickling.
 678        """
 679        # Interpolates all environment variables into actual values.
 680        config_dict = expand_env_vars(config_dict)
 681        self._resolved_config_dict = ImmutableDict(config_dict)
 682
 683        self._profiles = config_dict.get("profiles", {})
 684
 685        if RESERVED_POSIX_PROFILE_NAME not in self._profiles:
 686            # Assign the default POSIX profile
 687            self._profiles[RESERVED_POSIX_PROFILE_NAME] = DEFAULT_POSIX_PROFILE["profiles"][RESERVED_POSIX_PROFILE_NAME]
 688        else:
 689            # Cannot override default POSIX profile
 690            if (
 691                self._profiles[RESERVED_POSIX_PROFILE_NAME]
 692                != DEFAULT_POSIX_PROFILE["profiles"][RESERVED_POSIX_PROFILE_NAME]
 693            ):
 694                raise ValueError(f'Cannot override "{RESERVED_POSIX_PROFILE_NAME}" profile with different settings.')
 695
 696        profile_dict = self._profiles.get(profile)
 697
 698        if not profile_dict:
 699            raise ValueError(f"Profile {profile} not found; available profiles: {list(self._profiles.keys())}")
 700
 701        self._profile = profile
 702        self._profile_dict = ImmutableDict(profile_dict)
 703
 704        self._opentelemetry_dict = config_dict.get("opentelemetry", None)
 705        # Multiprocessing unpickles during the Python interpreter's bootstrap phase for new processes.
 706        # New processes (e.g. multiprocessing manager server) can't be created during this phase.
 707        #
 708        # Pass thunks everywhere instead for lazy telemetry initialization.
 709        self._telemetry_provider = telemetry_provider or telemetry_init
 710
 711        self._cache_dict = config_dict.get("cache", None)
 712
 713        self._provider_bundle = self._build_provider_bundle(provider_bundle)
 714        self._inject_profiles_from_bundle()
 715
 716    def _build_storage_provider(
 717        self,
 718        storage_provider_name: str,
 719        storage_options: dict[str, Any] | None = None,
 720        credentials_provider: CredentialsProvider | None = None,
 721    ) -> StorageProvider:
 722        if storage_options is None:
 723            storage_options = {}
 724        if storage_provider_name not in STORAGE_PROVIDER_MAPPING:
 725            raise ValueError(
 726                f"Storage provider {storage_provider_name} is not supported. "
 727                f"Supported providers are: {list(STORAGE_PROVIDER_MAPPING.keys())}"
 728            )
 729        if credentials_provider:
 730            storage_options["credentials_provider"] = credentials_provider
 731        if self._resolved_config_dict is not None:
 732            # Make a deep copy to drop any external references which may be mutated or cause infinite recursion.
 733            storage_options["config_dict"] = copy.deepcopy(self._resolved_config_dict)
 734        if self._telemetry_provider is not None:
 735            storage_options["telemetry_provider"] = self._telemetry_provider
 736        class_name = STORAGE_PROVIDER_MAPPING[storage_provider_name]
 737        module_name = ".providers"
 738        cls = import_class(class_name, module_name, PACKAGE_NAME)
 739        return cls(**storage_options)
 740
 741    def _build_storage_provider_from_profile(self, storage_provider_profile: str):
 742        storage_profile_dict = self._profiles.get(storage_provider_profile)
 743        if not storage_profile_dict:
 744            raise ValueError(
 745                f"Profile '{storage_provider_profile}' referenced by storage_provider_profile does not exist."
 746            )
 747
 748        # Check if metadata provider is configured for this profile
 749        # NOTE: The storage profile for manifests does not support metadata provider (at the moment).
 750        local_metadata_provider_dict = storage_profile_dict.get("metadata_provider", None)
 751        if local_metadata_provider_dict:
 752            raise ValueError(
 753                f"Profile '{storage_provider_profile}' cannot have a metadata provider when used for manifests"
 754            )
 755
 756        # Initialize CredentialsProvider
 757        local_creds_provider_dict = storage_profile_dict.get("credentials_provider", None)
 758        local_creds_provider = self._build_credentials_provider(credentials_provider_dict=local_creds_provider_dict)
 759
 760        # Initialize StorageProvider
 761        local_storage_provider_dict = storage_profile_dict.get("storage_provider", None)
 762        if local_storage_provider_dict:
 763            local_name = local_storage_provider_dict["type"]
 764            local_storage_options = local_storage_provider_dict.get("options", {})
 765        else:
 766            raise ValueError(f"Missing storage_provider in the config for profile {storage_provider_profile}.")
 767
 768        storage_provider = self._build_storage_provider(local_name, local_storage_options, local_creds_provider)
 769        return storage_provider
 770
 771    def _build_credentials_provider(
 772        self,
 773        credentials_provider_dict: dict[str, Any] | None,
 774        storage_options: dict[str, Any] | None = None,
 775    ) -> CredentialsProvider | None:
 776        """
 777        Initializes the CredentialsProvider based on the provided dictionary.
 778
 779        Args:
 780            credentials_provider_dict: Dictionary containing credentials provider configuration
 781            storage_options: Storage provider options required by some credentials providers to scope the credentials.
 782        """
 783        if not credentials_provider_dict:
 784            return None
 785
 786        if credentials_provider_dict["type"] not in CREDENTIALS_PROVIDER_MAPPING:
 787            # Fully qualified class path case
 788            class_type = credentials_provider_dict["type"]
 789            module_name, class_name = class_type.rsplit(".", 1)
 790            cls = import_class(class_name, module_name)
 791        else:
 792            # Mapped class name case
 793            class_name = CREDENTIALS_PROVIDER_MAPPING[credentials_provider_dict["type"]]
 794            module_name = ".providers"
 795            cls = import_class(class_name, module_name, PACKAGE_NAME)
 796
 797        # Propagate storage provider options to credentials provider since they may be
 798        # required by some credentials providers to scope the credentials.
 799        import inspect
 800
 801        init_params = list(inspect.signature(cls.__init__).parameters)[1:]  # skip 'self'
 802        options = credentials_provider_dict.get("options", {})
 803        if storage_options:
 804            for storage_provider_option in storage_options:
 805                if storage_provider_option in init_params and storage_provider_option not in options:
 806                    options[storage_provider_option] = storage_options[storage_provider_option]
 807
 808        return cls(**options)
 809
 810    def _build_provider_bundle_from_config(self, profile_dict: dict[str, Any]) -> ProviderBundle:
 811        # Initialize StorageProvider
 812        storage_provider_dict = profile_dict.get("storage_provider", None)
 813        if storage_provider_dict:
 814            storage_provider_name = storage_provider_dict["type"]
 815            storage_options = storage_provider_dict.get("options", {})
 816        else:
 817            raise ValueError("Missing storage_provider in the config.")
 818
 819        # Initialize CredentialsProvider
 820        # It is prudent to assume that in some cases, the credentials provider
 821        # will provide credentials scoped to specific base_path.
 822        # So we need to pass the storage_options to the credentials provider.
 823        credentials_provider_dict = profile_dict.get("credentials_provider", None)
 824        credentials_provider = self._build_credentials_provider(
 825            credentials_provider_dict=credentials_provider_dict,
 826            storage_options=storage_options,
 827        )
 828
 829        # Initialize MetadataProvider
 830        metadata_provider_dict = profile_dict.get("metadata_provider", None)
 831        metadata_provider = None
 832        if metadata_provider_dict:
 833            if metadata_provider_dict["type"] == "manifest":
 834                metadata_options = metadata_provider_dict.get("options", {})
 835                # If MetadataProvider has a reference to a different storage provider profile
 836                storage_provider_profile = metadata_options.pop("storage_provider_profile", None)
 837                if storage_provider_profile:
 838                    storage_provider = self._build_storage_provider_from_profile(storage_provider_profile)
 839                else:
 840                    storage_provider = self._build_storage_provider(
 841                        storage_provider_name, storage_options, credentials_provider
 842                    )
 843
 844                metadata_provider = ManifestMetadataProvider(storage_provider, **metadata_options)
 845            else:
 846                class_type = metadata_provider_dict["type"]
 847                if "." not in class_type:
 848                    raise ValueError(
 849                        f"Expected a fully qualified class name (e.g., 'module.ClassName'); got '{class_type}'."
 850                    )
 851                module_name, class_name = class_type.rsplit(".", 1)
 852                cls = import_class(class_name, module_name)
 853                options = metadata_provider_dict.get("options", {})
 854                metadata_provider = cls(**options)
 855
 856        # Build replicas if configured
 857        replicas_config = profile_dict.get("replicas", [])
 858        replicas = []
 859        if replicas_config:
 860            for replica_dict in replicas_config:
 861                replicas.append(
 862                    Replica(
 863                        replica_profile=replica_dict["replica_profile"],
 864                        read_priority=replica_dict["read_priority"],
 865                        read_only=replica_dict.get("read_only", False),
 866                    )
 867                )
 868
 869            # Sort replicas by read_priority
 870            replicas.sort(key=lambda r: r.read_priority)
 871
 872        return SimpleProviderBundle(
 873            storage_provider_config=StorageProviderConfig(storage_provider_name, storage_options),
 874            credentials_provider=credentials_provider,
 875            metadata_provider=metadata_provider,
 876            replicas=replicas,
 877        )
 878
 879    def _build_provider_bundle_from_extension(self, provider_bundle_dict: dict[str, Any]) -> ProviderBundle:
 880        class_type = provider_bundle_dict["type"]
 881        module_name, class_name = class_type.rsplit(".", 1)
 882        cls = import_class(class_name, module_name)
 883        options = provider_bundle_dict.get("options", {})
 884        return cls(**options)
 885
 886    def _build_provider_bundle(self, provider_bundle: ProviderBundle | ProviderBundleV2 | None) -> ProviderBundleV2:
 887        if provider_bundle:
 888            bundle = provider_bundle
 889        else:
 890            provider_bundle_dict = self._profile_dict.get("provider_bundle", None)
 891            if provider_bundle_dict:
 892                bundle = self._build_provider_bundle_from_extension(provider_bundle_dict)
 893            else:
 894                bundle = self._build_provider_bundle_from_config(self._profile_dict)
 895
 896        if isinstance(bundle, ProviderBundle) and not isinstance(bundle, ProviderBundleV2):
 897            bundle = SimpleProviderBundleV2.from_v1_bundle(self._profile, bundle)
 898
 899        return bundle
 900
 901    def _inject_profiles_from_bundle(self) -> None:
 902        """
 903        Inject child profiles and build child configs for multi-backend configurations.
 904
 905        For ProviderBundleV2 with multiple backends, this method:
 906        1. Injects child profiles into config dict (needed for replica initialization)
 907        2. Pre-builds child configs so CompositeStorageClient can use them directly
 908
 909        Profile injection is required because SingleStorageClient._initialize_replicas()
 910        uses StorageClientConfig.from_dict() to create replica clients, which looks up
 911        profiles in the config dict.
 912        """
 913        self._child_configs: dict[str, StorageClientConfig] | None = None
 914
 915        backends = self._provider_bundle.storage_backends
 916        if len(backends) > 1:
 917            # First, inject all child profiles into config dict (needed for replica lookup)
 918            profiles = copy.deepcopy(self._profiles)
 919            for child_name, backend in backends.items():
 920                child_profile_dict = {
 921                    "storage_provider": {
 922                        "type": backend.storage_provider_config.type,
 923                        "options": backend.storage_provider_config.options,
 924                    }
 925                }
 926
 927                if child_name in profiles:
 928                    # Profile already exists - check if it matches what we would inject
 929                    existing = profiles[child_name]
 930                    if existing.get("storage_provider") != child_profile_dict["storage_provider"]:
 931                        raise ValueError(
 932                            f"Profile '{child_name}' already exists in configuration with different settings."
 933                        )
 934                else:
 935                    profiles[child_name] = child_profile_dict
 936
 937            # Update config dict BEFORE building child configs
 938            resolved_config_dict = copy.deepcopy(self._resolved_config_dict)
 939            resolved_config_dict["profiles"] = profiles
 940            self._profiles = ImmutableDict(profiles)
 941            self._resolved_config_dict = ImmutableDict(resolved_config_dict)
 942
 943            # Now build child configs (they will get the updated config dict)
 944            retry_config = self._build_retry_config()
 945            child_configs: dict[str, StorageClientConfig] = {}
 946            for child_name, backend in backends.items():
 947                storage_provider = self._build_storage_provider(
 948                    backend.storage_provider_config.type,
 949                    backend.storage_provider_config.options,
 950                    backend.credentials_provider,
 951                )
 952
 953                child_config = StorageClientConfig(
 954                    profile=child_name,
 955                    storage_provider=storage_provider,
 956                    credentials_provider=backend.credentials_provider,
 957                    storage_provider_profiles=None,
 958                    child_configs=None,
 959                    metadata_provider=None,
 960                    cache_config=None,
 961                    cache_manager=None,
 962                    retry_config=retry_config,
 963                    telemetry_provider=self._telemetry_provider,
 964                    replicas=backend.replicas,
 965                    autocommit_config=None,
 966                )
 967                child_config._config_dict = self._resolved_config_dict
 968                child_configs[child_name] = child_config
 969
 970            self._child_configs = child_configs
 971
 972    def _build_retry_config(self) -> RetryConfig:
 973        """Build retry config from profile dict."""
 974        retry_config_dict = self._profile_dict.get("retry", None)
 975        if retry_config_dict:
 976            attempts = retry_config_dict.get("attempts", DEFAULT_RETRY_ATTEMPTS)
 977            delay = retry_config_dict.get("delay", DEFAULT_RETRY_DELAY)
 978            backoff_multiplier = retry_config_dict.get("backoff_multiplier", DEFAULT_RETRY_BACKOFF_MULTIPLIER)
 979            return RetryConfig(attempts=attempts, delay=delay, backoff_multiplier=backoff_multiplier)
 980        else:
 981            return RetryConfig(
 982                attempts=DEFAULT_RETRY_ATTEMPTS,
 983                delay=DEFAULT_RETRY_DELAY,
 984                backoff_multiplier=DEFAULT_RETRY_BACKOFF_MULTIPLIER,
 985            )
 986
 987    def _build_autocommit_config(self) -> AutoCommitConfig:
 988        """Build autocommit config from profile dict."""
 989        autocommit_dict = self._profile_dict.get("autocommit", None)
 990        if autocommit_dict:
 991            interval_minutes = autocommit_dict.get("interval_minutes", None)
 992            at_exit = autocommit_dict.get("at_exit", False)
 993            return AutoCommitConfig(interval_minutes=interval_minutes, at_exit=at_exit)
 994        return AutoCommitConfig()
 995
 996    def _verify_cache_config(self, cache_dict: dict[str, Any]) -> None:
 997        if "size_mb" in cache_dict:
 998            raise ValueError(
 999                "The 'size_mb' property is no longer supported. \n"
1000                "Please use 'size' with a unit suffix (M, G, T) instead of size_mb.\n"
1001                "Example configuration:\n"
1002                "cache:\n"
1003                "  size: 500G                    # Optional: Maximum cache size (default: 10G)\n"
1004                "  cache_line_size: 64M          # Optional: Chunk size for partial file caching (default: 64M)\n"
1005                "  check_source_version: true    # Optional: Use ETag for cache validation (default: true)\n"
1006                "  location: /tmp/msc_cache      # Optional: Cache directory path (default: system tempdir + '/msc_cache')\n"
1007                "  eviction_policy:               # Optional: Cache eviction policy\n"
1008                "    policy: fifo                 # Optional: Policy type: lru, mru, fifo, random, no_eviction (default: fifo)\n"
1009                "    refresh_interval: 300        # Optional: Cache refresh interval in seconds (default: 300)\n"
1010            )
1011
1012        # Validate that cache_line_size doesn't exceed cache size
1013        cache_size_str = cache_dict.get("size", DEFAULT_CACHE_SIZE)
1014        cache_line_size_str = cache_dict.get("cache_line_size", DEFAULT_CACHE_LINE_SIZE)
1015
1016        # Use CacheConfig to convert sizes to bytes for comparison
1017        temp_cache_config = CacheConfig(
1018            size=cache_size_str,
1019            cache_line_size=cache_line_size_str,
1020        )
1021        cache_size_bytes = temp_cache_config.size_bytes()
1022        cache_line_size_bytes = temp_cache_config.cache_line_size_bytes()
1023
1024        if cache_line_size_bytes > cache_size_bytes:
1025            raise ValueError(
1026                f"cache_line_size ({cache_line_size_str}) exceeds cache size ({cache_size_str}). "
1027                f"cache_line_size must be less than or equal to cache size. "
1028                f"Consider increasing cache size or decreasing cache_line_size."
1029            )
1030
1031    def _validate_replicas(self, replicas: list[Replica]) -> None:
1032        """
1033        Validates that replica profiles do not have their own replicas configuration.
1034
1035        This prevents circular references where a replica profile could reference
1036        another profile that also has replicas, creating an infinite loop.
1037
1038        :param replicas: The list of Replica objects to validate
1039        :raises ValueError: If any replica profile has its own replicas configuration
1040        """
1041        for replica in replicas:
1042            replica_profile_name = replica.replica_profile
1043
1044            # Check that replica profile is not the same as the current profile
1045            if replica_profile_name == self._profile:
1046                raise ValueError(
1047                    f"Replica profile {replica_profile_name} cannot be the same as the profile {self._profile}."
1048                )
1049
1050            # Check if the replica profile exists in the configuration
1051            if replica_profile_name not in self._profiles:
1052                raise ValueError(f"Replica profile '{replica_profile_name}' not found in configuration")
1053
1054            # Get the replica profile configuration
1055            replica_profile_dict = self._profiles[replica_profile_name]
1056
1057            # Check if the replica profile has its own replicas configuration
1058            if replica_profile_dict.get("replicas"):
1059                raise ValueError(
1060                    f"Invalid replica configuration: profile '{replica_profile_name}' has its own replicas. "
1061                    f"This creates a circular reference which is not allowed."
1062                )
1063
1064    def build_config(self) -> "StorageClientConfig":
1065        bundle = self._provider_bundle
1066        backends = bundle.storage_backends
1067
1068        if len(backends) > 1:
1069            if not bundle.metadata_provider:
1070                raise ValueError(
1071                    f"Multi-backend configuration for profile '{self._profile}' requires metadata_provider "
1072                    "for routing between storage locations."
1073                )
1074
1075            child_profile_names = list(backends.keys())
1076            retry_config = self._build_retry_config()
1077            autocommit_config = self._build_autocommit_config()
1078
1079            # config for Composite StorageClient
1080            config = StorageClientConfig(
1081                profile=self._profile,
1082                storage_provider=None,
1083                credentials_provider=None,
1084                storage_provider_profiles=child_profile_names,
1085                child_configs=self._child_configs,
1086                metadata_provider=bundle.metadata_provider,
1087                cache_config=None,
1088                cache_manager=None,
1089                retry_config=retry_config,
1090                telemetry_provider=self._telemetry_provider,
1091                replicas=[],
1092                autocommit_config=autocommit_config,
1093            )
1094
1095            config._config_dict = self._resolved_config_dict
1096            return config
1097
1098        # Single-backend (len == 1)
1099        _, backend = next(iter(backends.items()))
1100        storage_provider = self._build_storage_provider(
1101            backend.storage_provider_config.type,
1102            backend.storage_provider_config.options,
1103            backend.credentials_provider,
1104        )
1105        credentials_provider = backend.credentials_provider
1106        metadata_provider = bundle.metadata_provider
1107        replicas = backend.replicas
1108
1109        # Validate replicas to prevent circular references
1110        if replicas:
1111            self._validate_replicas(replicas)
1112
1113        cache_config: CacheConfig | None = None
1114        cache_manager: CacheManager | None = None
1115
1116        # Check if caching is enabled for this profile
1117        caching_enabled = self._profile_dict.get("caching_enabled", False)
1118
1119        if self._cache_dict is not None and caching_enabled:
1120            tempdir = tempfile.gettempdir()
1121            default_location = os.path.join(tempdir, "msc_cache")
1122            location = self._cache_dict.get("location", default_location)
1123
1124            # Check if cache_backend.cache_path is defined
1125            cache_backend = self._cache_dict.get("cache_backend", {})
1126            cache_backend_path = cache_backend.get("cache_path") if cache_backend else None
1127
1128            # Warn if both location and cache_backend.cache_path are defined
1129            if cache_backend_path and self._cache_dict.get("location") is not None:
1130                logger.warning(
1131                    f"Both 'location' and 'cache_backend.cache_path' are defined in cache config. "
1132                    f"Using 'location' ({location}) and ignoring 'cache_backend.cache_path' ({cache_backend_path})."
1133                )
1134            elif cache_backend_path:
1135                # Use cache_backend.cache_path only if location is not explicitly defined
1136                location = cache_backend_path
1137
1138            check_source_version = self._cache_dict.get("check_source_version", True)
1139
1140            if not Path(location).is_absolute():
1141                raise ValueError(f"Cache location must be an absolute path: {location}")
1142
1143            # Initialize cache_dict with default values
1144            cache_dict = self._cache_dict
1145
1146            # Verify cache config
1147            self._verify_cache_config(cache_dict)
1148
1149            # Initialize eviction policy
1150            if "eviction_policy" in cache_dict:
1151                policy = cache_dict["eviction_policy"]["policy"].lower()
1152                purge_factor = cache_dict["eviction_policy"].get("purge_factor", 0)
1153                eviction_policy = EvictionPolicyConfig(
1154                    policy=policy,
1155                    refresh_interval=cache_dict["eviction_policy"].get(
1156                        "refresh_interval", DEFAULT_CACHE_REFRESH_INTERVAL
1157                    ),
1158                    purge_factor=purge_factor,
1159                )
1160            else:
1161                eviction_policy = EvictionPolicyConfig(policy="fifo", refresh_interval=DEFAULT_CACHE_REFRESH_INTERVAL)
1162
1163            # Create cache config from the standardized format
1164            cache_config = CacheConfig(
1165                size=cache_dict.get("size", DEFAULT_CACHE_SIZE),
1166                location=cache_dict.get("location", location),
1167                check_source_version=check_source_version,
1168                prefetch_file=cache_dict.get("prefetch_file", True),
1169                eviction_policy=eviction_policy,
1170                cache_line_size=cache_dict.get("cache_line_size", DEFAULT_CACHE_LINE_SIZE),
1171            )
1172
1173            cache_manager = CacheManager(profile=self._profile, cache_config=cache_config)
1174        elif self._cache_dict is not None and not caching_enabled:
1175            logger.debug(f"Caching is disabled for profile '{self._profile}'")
1176        elif self._cache_dict is None and caching_enabled:
1177            logger.warning(f"Caching is enabled for profile '{self._profile}' but no cache configuration is provided")
1178
1179        retry_config = self._build_retry_config()
1180        autocommit_config = self._build_autocommit_config()
1181
1182        config = StorageClientConfig(
1183            profile=self._profile,
1184            storage_provider=storage_provider,
1185            credentials_provider=credentials_provider,
1186            storage_provider_profiles=None,
1187            child_configs=None,
1188            metadata_provider=metadata_provider,
1189            cache_config=cache_config,
1190            cache_manager=cache_manager,
1191            retry_config=retry_config,
1192            telemetry_provider=self._telemetry_provider,
1193            replicas=replicas,
1194            autocommit_config=autocommit_config,
1195        )
1196
1197        config._config_dict = self._resolved_config_dict
1198        return config
1199
1200
1201class PathMapping:
1202    """
1203    Class to handle path mappings defined in the MSC configuration.
1204
1205    Path mappings create a nested structure of protocol -> bucket -> [(prefix, profile)]
1206    where entries are sorted by prefix length (longest first) for optimal matching.
1207    Longer paths take precedence when matching.
1208    """
1209
1210    def __init__(self):
1211        """Initialize an empty PathMapping."""
1212        self._mapping = defaultdict(lambda: defaultdict(list))
1213
1214    @classmethod
1215    def from_config(cls, config_dict: dict[str, Any] | None = None) -> "PathMapping":
1216        """
1217        Create a PathMapping instance from configuration dictionary.
1218
1219        :param config_dict: Configuration dictionary, if None the config will be loaded
1220        :return: A PathMapping instance with processed mappings
1221        """
1222        if config_dict is None:
1223            # Import locally to avoid circular imports
1224            from multistorageclient.config import StorageClientConfig
1225
1226            config_dict, _ = StorageClientConfig.read_msc_config()
1227
1228        if not config_dict:
1229            return cls()
1230
1231        instance = cls()
1232        instance._load_mapping(config_dict)
1233        return instance
1234
1235    def _load_mapping(self, config_dict: dict[str, Any]) -> None:
1236        """
1237        Load path mapping from a configuration dictionary.
1238
1239        :param config_dict: Configuration dictionary containing path mapping
1240        """
1241        # Get the path_mapping section
1242        path_mapping = config_dict.get("path_mapping", {})
1243        if path_mapping is None:
1244            return
1245
1246        # Process each mapping
1247        for source_path, dest_path in path_mapping.items():
1248            # Validate format
1249            if not source_path.endswith("/"):
1250                continue
1251            if not dest_path.startswith(MSC_PROTOCOL):
1252                continue
1253            if not dest_path.endswith("/"):
1254                continue
1255
1256            # Extract the destination profile
1257            pr_dest = urlparse(dest_path)
1258            dest_profile = pr_dest.netloc
1259
1260            # Parse the source path
1261            pr = urlparse(source_path)
1262            protocol = pr.scheme.lower() if pr.scheme else "file"
1263
1264            if protocol == "file" or source_path.startswith("/"):
1265                # For file or absolute paths, use the whole path as the prefix
1266                # and leave bucket empty
1267                bucket = ""
1268                prefix = source_path if source_path.startswith("/") else build_full_path(source_path, pr)
1269            else:
1270                # For object storage, extract bucket and prefix
1271                bucket = pr.netloc
1272                prefix = build_full_path(source_path, pr)
1273                prefix = prefix.removeprefix("/")
1274
1275            # Add the mapping to the nested dict
1276            self._mapping[protocol][bucket].append((prefix, dest_profile))
1277
1278        # Sort each bucket's prefixes by length (longest first) for optimal matching
1279        for protocol, buckets in self._mapping.items():
1280            for bucket, prefixes in buckets.items():
1281                self._mapping[protocol][bucket] = sorted(prefixes, key=lambda x: len(x[0]), reverse=True)
1282
1283    def find_mapping(self, url: str) -> tuple[str, str] | None:
1284        """
1285        Find the best matching mapping for the given URL.
1286
1287        :param url: URL to find matching mapping for
1288        :return: Tuple of (profile_name, translated_path) if a match is found, None otherwise
1289        """
1290        # Parse the URL
1291        pr = urlparse(url)
1292        protocol = pr.scheme.lower() if pr.scheme else "file"
1293
1294        # For file paths or absolute paths
1295        if protocol == "file" or url.startswith("/"):
1296            path = url if url.startswith("/") else build_full_path(url, pr)
1297
1298            possible_mapping = self._mapping[protocol][""] if protocol in self._mapping else []
1299
1300            # Check each prefix (already sorted by length, longest first)
1301            for prefix, profile in possible_mapping:
1302                if path.startswith(prefix):
1303                    # Calculate the relative path
1304                    rel_path = path[len(prefix) :]
1305                    if not rel_path.startswith("/"):
1306                        rel_path = "/" + rel_path
1307                    return profile, rel_path
1308
1309            return None
1310
1311        # For object storage
1312        bucket = pr.netloc
1313        path = build_full_path(url, pr)
1314        path = path.removeprefix("/")
1315
1316        # Check bucket-specific mapping
1317        possible_mapping = (
1318            self._mapping[protocol][bucket] if (protocol in self._mapping and bucket in self._mapping[protocol]) else []
1319        )
1320
1321        # Check each prefix (already sorted by length, longest first)
1322        for prefix, profile in possible_mapping:
1323            # matching prefix
1324            if path.startswith(prefix):
1325                rel_path = path[len(prefix) :]
1326                # Remove leading slash if present
1327                rel_path = rel_path.removeprefix("/")
1328
1329                return profile, rel_path
1330
1331        return None
1332
1333
[docs] 1334class StorageClientConfig: 1335 """ 1336 Configuration class for the :py:class:`multistorageclient.StorageClient`. 1337 """ 1338 1339 profile: str 1340 storage_provider: StorageProvider | None 1341 credentials_provider: CredentialsProvider | None 1342 storage_provider_profiles: list[str] | None 1343 child_configs: dict[str, "StorageClientConfig"] | None 1344 metadata_provider: MetadataProvider | None 1345 cache_config: CacheConfig | None 1346 cache_manager: CacheManager | None 1347 retry_config: RetryConfig | None 1348 telemetry_provider: Callable[[], Telemetry] | None 1349 replicas: list[Replica] 1350 autocommit_config: AutoCommitConfig | None 1351 1352 _config_dict: dict[str, Any] | None 1353 1354 def __init__( 1355 self, 1356 profile: str, 1357 storage_provider: StorageProvider | None = None, 1358 credentials_provider: CredentialsProvider | None = None, 1359 storage_provider_profiles: list[str] | None = None, 1360 child_configs: dict[str, "StorageClientConfig"] | None = None, 1361 metadata_provider: MetadataProvider | None = None, 1362 cache_config: CacheConfig | None = None, 1363 cache_manager: CacheManager | None = None, 1364 retry_config: RetryConfig | None = None, 1365 telemetry_provider: Callable[[], Telemetry] | None = None, 1366 replicas: list[Replica] | None = None, 1367 autocommit_config: AutoCommitConfig | None = None, 1368 ): 1369 # exactly one of storage_provider or storage_provider_profiles must be set 1370 if storage_provider and storage_provider_profiles: 1371 raise ValueError( 1372 "Cannot specify both storage_provider and storage_provider_profiles. " 1373 "Use storage_provider for SingleStorageClient or storage_provider_profiles for CompositeStorageClient." 1374 ) 1375 if not storage_provider and not storage_provider_profiles: 1376 raise ValueError("Must specify either storage_provider or storage_provider_profiles.") 1377 1378 if replicas is None: 1379 replicas = [] 1380 self.profile = profile 1381 self.storage_provider = storage_provider 1382 self.credentials_provider = credentials_provider 1383 self.storage_provider_profiles = storage_provider_profiles 1384 self.child_configs = child_configs 1385 self.metadata_provider = metadata_provider 1386 self.cache_config = cache_config 1387 self.cache_manager = cache_manager 1388 self.retry_config = retry_config 1389 self.telemetry_provider = telemetry_provider 1390 self.replicas = replicas 1391 self.autocommit_config = autocommit_config 1392 1393 canonical_root_url: str | None = None 1394 access_scope: str | None = None 1395 _reference_pid: int | None = None 1396 _reference_route: tuple[str, ...] = () 1397 1398 @property 1399 def read_only(self) -> bool: 1400 """Whether this configuration belongs to a read-only reference binding.""" 1401 return self.canonical_root_url is not None 1402 1403 @property 1404 def resolver_identity(self) -> tuple[str, str] | None: 1405 """The scheme and namespace of this reference's canonical root.""" 1406 if self.canonical_root_url is None: 1407 return None 1408 uri = urlparse(self.canonical_root_url) 1409 return uri.scheme, uri.netloc 1410 1411 @property 1412 def _inherited_reference(self) -> bool: 1413 return self._reference_pid is not None and self._reference_pid != os.getpid() 1414 1415 @staticmethod 1416 def _from_bound_profile( 1417 config_dict: dict[str, Any], 1418 profile: str, 1419 canonical_root_url: str, 1420 access_scope: str | None, 1421 telemetry_provider: Callable[[], Telemetry] | None = None, 1422 *, 1423 binding_profile: str | None = None, 1424 route: tuple[str, ...] = (), 1425 ) -> "StorageClientConfig": 1426 profiles = config_dict["profiles"] 1427 autocommit = profiles[profile].get("autocommit", {}) 1428 if autocommit.get("at_exit") or autocommit.get("interval_minutes"): 1429 raise ValueError("Metadata autocommit is not supported for a read-only reference.") 1430 # A persistent cache hit could bypass a bound provider's revocation check. 1431 bound_profile = {**profiles[profile], "caching_enabled": False} 1432 config_dict = {**config_dict, "profiles": {**profiles, profile: bound_profile}} 1433 config_dict.pop("cache", None) 1434 config = StorageClientConfig.from_dict( 1435 config_dict, profile, skip_validation=True, telemetry_provider=telemetry_provider 1436 ) 1437 config._set_reference(binding_profile or profile, canonical_root_url, access_scope, route) 1438 return config 1439 1440 def _set_reference(self, identity: str, root: str, scope: str | None, route: tuple[str, ...]) -> None: 1441 self.autocommit_config = None 1442 self.profile = identity 1443 self.canonical_root_url = root 1444 self.access_scope = scope 1445 self._reference_pid = os.getpid() 1446 self._reference_route = route 1447 self.replicas = [replace(replica, read_only=True) for replica in self.replicas] 1448 for name, child in (self.child_configs or {}).items(): 1449 child._set_reference(identity, root, scope, (*route, name)) 1450 1451 def _related_config(self, name: str) -> "StorageClientConfig": 1452 if self.child_configs and name in self.child_configs: 1453 return self.child_configs[name] 1454 if self._config_dict is None: 1455 raise ValueError(f"Cannot initialize related profile '{name}' without a configuration.") 1456 if self.canonical_root_url is not None: 1457 return StorageClientConfig._from_bound_profile( 1458 self._config_dict, 1459 name, 1460 self.canonical_root_url, 1461 self.access_scope, 1462 binding_profile=self.profile, 1463 route=(*self._reference_route, name), 1464 ) 1465 return StorageClientConfig.from_dict(self._config_dict, name) 1466 1467 def _current_process_config(self) -> "StorageClientConfig": 1468 if self._inherited_reference: 1469 from .shortcuts import _reopen_reference 1470 1471 assert self.canonical_root_url is not None 1472 root = _reopen_reference(self.canonical_root_url, expected_scope=self.access_scope)._config 1473 return root._component_config(self._reference_route) 1474 return self 1475 1476 def _component_config(self, route: tuple[str, ...]) -> "StorageClientConfig": 1477 config = self 1478 for name in route: 1479 if name not in (config.storage_provider_profiles or ()) and not any( 1480 replica.replica_profile == name for replica in config.replicas 1481 ): 1482 raise ValueError(f"Reopened reference no longer declares backend or replica '{name}'.") 1483 config = config._related_config(name) 1484 return config 1485
[docs] 1486 @staticmethod 1487 def from_json( 1488 config_json: str, 1489 profile: str = RESERVED_POSIX_PROFILE_NAME, 1490 telemetry_provider: Callable[[], Telemetry] | None = None, 1491 ) -> "StorageClientConfig": 1492 """ 1493 Load a storage client configuration from a JSON string. 1494 1495 :param config_json: Configuration JSON string. 1496 :param profile: Profile to use. 1497 :param telemetry_provider: A function that provides a telemetry instance. The function must be defined at the top level of a module to work with pickling. 1498 """ 1499 config_dict = _load_config(config_json, is_json=True) 1500 return StorageClientConfig.from_dict( 1501 config_dict=config_dict, profile=profile, telemetry_provider=telemetry_provider 1502 )
1503
[docs] 1504 @staticmethod 1505 def from_yaml( 1506 config_yaml: str, 1507 profile: str = RESERVED_POSIX_PROFILE_NAME, 1508 telemetry_provider: Callable[[], Telemetry] | None = None, 1509 ) -> "StorageClientConfig": 1510 """ 1511 Load a storage client configuration from a YAML string. 1512 1513 :param config_yaml: Configuration YAML string. 1514 :param profile: Profile to use. 1515 :param telemetry_provider: A function that provides a telemetry instance. The function must be defined at the top level of a module to work with pickling. 1516 """ 1517 config_dict = _load_config(config_yaml, is_json=False) or {} 1518 return StorageClientConfig.from_dict( 1519 config_dict=config_dict, profile=profile, telemetry_provider=telemetry_provider 1520 )
1521
[docs] 1522 @staticmethod 1523 def from_dict( 1524 config_dict: dict[str, Any], 1525 profile: str = RESERVED_POSIX_PROFILE_NAME, 1526 skip_validation: bool = False, 1527 telemetry_provider: Callable[[], Telemetry] | None = None, 1528 ) -> "StorageClientConfig": 1529 """ 1530 Load a storage client configuration from a Python dictionary. 1531 1532 :param config_dict: Configuration Python dictionary. 1533 :param profile: Profile to use. 1534 :param skip_validation: Skip configuration schema validation. 1535 :param telemetry_provider: A function that provides a telemetry instance. The function must be defined at the top level of a module to work with pickling. 1536 """ 1537 # Validate the config file with predefined JSON schema 1538 if not skip_validation: 1539 validate_config(config_dict) 1540 1541 # Load config 1542 loader = StorageClientConfigLoader( 1543 config_dict=config_dict, 1544 profile=profile, 1545 telemetry_provider=telemetry_provider, 1546 ) 1547 config = loader.build_config() 1548 1549 return config
1550
[docs] 1551 @staticmethod 1552 def from_file( 1553 config_file_paths: Iterable[str] | None = None, 1554 profile: str = RESERVED_POSIX_PROFILE_NAME, 1555 telemetry_provider: Callable[[], Telemetry] | None = None, 1556 ) -> "StorageClientConfig": 1557 """ 1558 Load a storage client configuration from the first file found. 1559 1560 :param config_file_paths: Configuration file search paths. If omitted, the default search paths are used (see :py:meth:`StorageClientConfig.read_msc_config`). 1561 :param profile: Profile to use. 1562 :param telemetry_provider: A function that provides a telemetry instance. The function must be defined at the top level of a module to work with pickling. 1563 """ 1564 msc_config_dict, msc_config_file = StorageClientConfig.read_msc_config(config_file_paths=config_file_paths) 1565 # Parse rclone config file. 1566 rclone_config_dict, rclone_config_file = read_rclone_config() 1567 1568 # Merge config files. 1569 merged_config, conflicted_keys = merge_dictionaries_no_overwrite(msc_config_dict, rclone_config_dict) 1570 if conflicted_keys: 1571 raise ValueError( 1572 f'Conflicting keys found in configuration files "{msc_config_file}" and "{rclone_config_file}: {conflicted_keys}' 1573 ) 1574 merged_profiles = merged_config.get("profiles", {}) 1575 1576 # Check if profile is in merged_profiles 1577 if profile in merged_profiles: 1578 return StorageClientConfig.from_dict( 1579 config_dict=merged_config, profile=profile, telemetry_provider=telemetry_provider 1580 ) 1581 else: 1582 # Check if profile is the default POSIX profile or an implicit profile 1583 if profile == RESERVED_POSIX_PROFILE_NAME: 1584 implicit_profile_config = DEFAULT_POSIX_PROFILE 1585 elif profile.startswith("_"): 1586 # Handle implicit profiles 1587 parts = profile[1:].split("-", 1) 1588 if len(parts) == 2: 1589 protocol, bucket = parts 1590 # Verify it's a supported protocol 1591 if protocol not in SUPPORTED_IMPLICIT_PROFILE_PROTOCOLS: 1592 raise ValueError(f'Unsupported protocol in implicit profile: "{protocol}"') 1593 implicit_profile_config = create_implicit_profile_config( 1594 profile_name=profile, protocol=protocol, base_path=bucket 1595 ) 1596 else: 1597 raise ValueError(f'Invalid implicit profile format: "{profile}"') 1598 else: 1599 raise ValueError( 1600 f'Profile "{profile}" not found in configuration files. Configuration was checked in ' 1601 f"{msc_config_file or 'MSC config (not found)'} and {rclone_config_file or 'Rclone config (not found)'}. " 1602 f"Please verify that the profile exists and that configuration files are correctly located." 1603 ) 1604 # merge the implicit profile config into the merged config so the cache & observability config can be inherited 1605 if "profiles" not in merged_config: 1606 merged_config["profiles"] = implicit_profile_config["profiles"] 1607 else: 1608 merged_config["profiles"][profile] = implicit_profile_config["profiles"][profile] 1609 # the config is already validated while reading, skip the validation for implicit profiles which start profile with "_" 1610 return StorageClientConfig.from_dict( 1611 config_dict=merged_config, profile=profile, skip_validation=True, telemetry_provider=telemetry_provider 1612 )
1613 1614 @staticmethod 1615 def from_provider_bundle( 1616 config_dict: dict[str, Any], 1617 provider_bundle: ProviderBundle | ProviderBundleV2, 1618 telemetry_provider: Callable[[], Telemetry] | None = None, 1619 ) -> "StorageClientConfig": 1620 loader = StorageClientConfigLoader( 1621 config_dict=config_dict, provider_bundle=provider_bundle, telemetry_provider=telemetry_provider 1622 ) 1623 config = loader.build_config() 1624 config._config_dict = None # Explicitly mark as None to avoid confusing pickling errors 1625 return config 1626
[docs] 1627 @staticmethod 1628 def read_msc_config( 1629 config_file_paths: Iterable[str] | None = None, 1630 ) -> tuple[dict[str, Any] | None, str | None]: 1631 """Get the MSC configuration dictionary and the path of the first file found. 1632 1633 If no config paths are specified, configs are searched in the following order: 1634 1635 1. ``MSC_CONFIG`` environment variable (highest precedence) 1636 2. Standard search paths (user-specified config and system-wide config) 1637 1638 :param config_file_paths: Configuration file search paths. If omitted, the default search paths are used. 1639 :return: Tuple of ``(config_dict, config_file_path)``. ``config_dict`` is the MSC configuration 1640 dictionary or empty dict if no config was found. ``config_file_path`` is the absolute 1641 path of the config file used, or ``None`` if no config file was found. 1642 """ 1643 return StorageClientConfig._read_msc_config(config_file_paths)
1644 1645 @staticmethod 1646 def _read_msc_config( 1647 config_file_paths: Iterable[str] | None = None, 1648 *, 1649 generations: list[_ConfigFileGeneration] | None = None, 1650 ) -> tuple[dict[str, Any] | None, str | None]: 1651 config_dict: dict[str, Any] = {} 1652 config_file_path: str | None = None 1653 1654 config_file_paths = list(config_file_paths or []) 1655 1656 # Add default paths if none provided. 1657 if len(config_file_paths) == 0: 1658 # Environment variable. 1659 msc_config_env = os.getenv("MSC_CONFIG", None) 1660 if msc_config_env is not None: 1661 config_file_paths.append(msc_config_env) 1662 1663 # Standard search paths. 1664 config_file_paths.extend(_find_config_file_paths()) 1665 1666 # Normalize + absolutize paths. 1667 config_file_paths = [os.path.abspath(path) for path in config_file_paths] 1668 1669 # Log plan. 1670 logger.debug(f"Searching MSC config file paths: {config_file_paths}") 1671 1672 # Load config. 1673 for path in config_file_paths: 1674 if os.path.exists(path): 1675 try: 1676 config_dict = _read_config_file(path, generations) 1677 config_file_path = path 1678 # Use the first config file. 1679 break 1680 except Exception as e: 1681 raise ValueError(f"malformed MSC config file: {path}, exception: {e}") 1682 1683 # Log result. 1684 if config_file_path is None: 1685 logger.debug("No MSC config files found in any of the search locations.") 1686 else: 1687 logger.debug(f"Using MSC config file: {config_file_path}") 1688 1689 if config_dict: 1690 validate_config(config_dict) 1691 1692 if "include" in config_dict and config_file_path: 1693 config_dict = _load_and_merge_includes(config_file_path, config_dict, generations) 1694 if "url_resolvers" in config_dict: 1695 validate_config(config_dict) 1696 1697 return config_dict, config_file_path 1698
[docs] 1699 @staticmethod 1700 def read_path_mapping() -> PathMapping: 1701 """ 1702 Get the path mapping defined in the MSC configuration. 1703 1704 Path mappings create a nested structure of protocol -> bucket -> [(prefix, profile)] 1705 where entries are sorted by prefix length (longest first) for optimal matching. 1706 Longer paths take precedence when matching. 1707 1708 :return: A PathMapping instance with translation mappings 1709 """ 1710 try: 1711 return PathMapping.from_config() 1712 except Exception: 1713 # Log the error but continue - this shouldn't stop the application from working 1714 logger.error("Failed to load path_mapping from MSC config") 1715 return PathMapping()
1716 1717 def __getstate__(self) -> dict[str, Any]: 1718 if self.canonical_root_url is not None: 1719 return { 1720 "canonical_root_url": self.canonical_root_url, 1721 "resolver_identity": self.resolver_identity, 1722 "route": self._reference_route, 1723 } 1724 state = self.__dict__.copy() 1725 if not state.get("_config_dict"): 1726 raise ValueError("StorageClientConfig is not serializable") 1727 del state["credentials_provider"] 1728 del state["storage_provider"] 1729 del state["metadata_provider"] 1730 del state["cache_manager"] 1731 del state["replicas"] 1732 del state["child_configs"] 1733 return state 1734 1735 def __setstate__(self, state: dict[str, Any]) -> None: 1736 if "canonical_root_url" in state: 1737 from .shortcuts import _reopen_reference 1738 1739 root = state["canonical_root_url"] 1740 uri = urlparse(root) 1741 if (uri.scheme, uri.netloc) != state["resolver_identity"]: 1742 raise ValueError("Serialized reference does not match its recorded resolver identity.") 1743 config = _reopen_reference(root)._config._component_config(state["route"]) 1744 self.__dict__.update(config.__dict__) 1745 return 1746 1747 # Presence checked by __getstate__. 1748 config_dict = state["_config_dict"] 1749 loader = StorageClientConfigLoader( 1750 config_dict=config_dict, 1751 profile=state["profile"], 1752 telemetry_provider=state["telemetry_provider"], 1753 ) 1754 new_config = loader.build_config() 1755 self.profile = new_config.profile 1756 self.storage_provider = new_config.storage_provider 1757 self.credentials_provider = new_config.credentials_provider 1758 self.storage_provider_profiles = new_config.storage_provider_profiles 1759 self.child_configs = new_config.child_configs 1760 self.metadata_provider = new_config.metadata_provider 1761 self.cache_config = new_config.cache_config 1762 self.cache_manager = new_config.cache_manager 1763 self.retry_config = new_config.retry_config 1764 self.telemetry_provider = new_config.telemetry_provider 1765 self._config_dict = config_dict 1766 self.replicas = new_config.replicas 1767 self.autocommit_config = new_config.autocommit_config