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 builtins
17import hashlib
18import json
19import logging
20import os
21import re
22import threading
23from collections.abc import Callable, Iterator, Sequence
24from datetime import timedelta
25from time import time
26from typing import IO, Any
27from urllib.parse import urlparse
28from uuid import uuid4
29from weakref import WeakValueDictionary
30
31from .client import StorageClient
32from .config import RESERVED_POSIX_PROFILE_NAME, PathMapping, StorageClientConfig
33from .file import ObjectFile, PosixFile
34from .references import ParsedReference, URLResolver
35from .schema import SUPPORTED_IMPLICIT_PROFILE_PROTOCOLS, validate_config
36from .telemetry import Telemetry
37from .types import MSC_PROTOCOL, ExecutionMode, ObjectMetadata, PatternList, SignerType, SymlinkHandling, SyncResult
38from .utils import build_full_path, expand_env_vars, import_class
39
40_TELEMETRY_PROVIDER: Callable[[], Telemetry] | None = None
41_TELEMETRY_PROVIDER_LOCK = threading.Lock()
42_STORAGE_CLIENT_CACHE: dict[str, StorageClient] = {}
43_STORAGE_CLIENT_CACHE_LOCK = threading.Lock()
44_MAX_ROUTING_CONFIGS = 16
45_MAX_REFERENCE_BINDINGS = 128
46_ANY_SCOPE = object()
47_PATH_MAPPING_CACHE: dict[str | None, tuple[PathMapping, dict[str, "_ConfiguredResolver"]]] = {}
48_PATH_MAPPING_CACHE_LOCK = threading.Lock()
49_PROCESS_ID = os.getpid()
50
51logger = logging.getLogger(__name__)
52
53
54def _reinitialize_after_fork() -> None:
55 """
56 Reinitialize module state after fork to ensure fork-safety.
57
58 This function is called automatically after a fork to:
59 1. Clear the storage client cache (cached clients may have invalid state)
60 2. Reinitialize locks (parent's lock state must not be inherited)
61 3. Update process ID tracking
62
63 Note: The telemetry provider is intentionally inherited by child processes,
64 only its lock is reinitialized.
65 """
66 global _STORAGE_CLIENT_CACHE, _STORAGE_CLIENT_CACHE_LOCK # noqa: PLW0602
67 global _PATH_MAPPING_CACHE, _PATH_MAPPING_CACHE_LOCK # noqa: PLW0602
68 global _TELEMETRY_PROVIDER_LOCK
69 global _PROCESS_ID
70
71 _STORAGE_CLIENT_CACHE.clear()
72 _STORAGE_CLIENT_CACHE_LOCK = threading.Lock()
73 _PATH_MAPPING_CACHE.clear()
74 _PATH_MAPPING_CACHE_LOCK = threading.Lock()
75 # we don't need to reset telemetry provider as it is supposed to be a top-level Python function
76 _TELEMETRY_PROVIDER_LOCK = threading.Lock()
77 _PROCESS_ID = os.getpid()
78
79
80def _check_and_reinitialize_if_forked() -> None:
81 """
82 Check if the current process is a fork and reinitialize if needed.
83
84 This provides fork-safety for systems where os.register_at_fork is not available
85 or as a fallback mechanism.
86 """
87 global _PROCESS_ID # noqa: PLW0602
88
89 current_pid = os.getpid()
90 if current_pid != _PROCESS_ID:
91 _reinitialize_after_fork()
92
93
94if hasattr(os, "register_at_fork"):
95 os.register_at_fork(after_in_child=_reinitialize_after_fork)
96
97
[docs]
98def get_telemetry_provider() -> Callable[[], Telemetry] | None:
99 """
100 Get the function used to create :py:class:`Telemetry` instances for storage clients created by shortcuts.
101
102 :return: A function that provides a telemetry instance.
103 """
104 global _TELEMETRY_PROVIDER # noqa: PLW0602
105
106 return _TELEMETRY_PROVIDER
107
108
[docs]
109def set_telemetry_provider(telemetry_provider: Callable[[], Telemetry] | None) -> None:
110 """
111 Set the function used to create :py:class:`Telemetry` instances for storage clients created by shortcuts.
112
113 :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.
114 """
115 global _TELEMETRY_PROVIDER
116 global _TELEMETRY_PROVIDER_LOCK # noqa: PLW0602
117
118 with _TELEMETRY_PROVIDER_LOCK:
119 _TELEMETRY_PROVIDER = telemetry_provider
120
121
122def _resolve_msc_url(url: str) -> tuple[str, str]:
123 """
124 Resolve an MSC URL to a profile name and path.
125
126 :param url: The MSC URL to resolve (msc://profile/path)
127 :return: A tuple of (profile_name, path)
128 """
129 pr = urlparse(url)
130 profile = pr.netloc
131 # Normalize only the object path so the msc:// scheme separator and profile stay intact.
132 pr = pr._replace(path=re.sub(r"/+", "/", pr.path))
133 path = build_full_path(url, pr)
134 path = path.removeprefix("/")
135 return profile, path
136
137
138class _ConfiguredResolver:
139 def __init__(self, scheme: str, config: dict[str, Any], config_identity: str):
140 self.scheme = scheme
141 self._config = config
142 self._identity = config_identity
143 self._resolver: URLResolver | None = None
144 self._clients: dict[tuple[str, str | None], tuple[float, StorageClient]] = {}
145 self._inflight: WeakValueDictionary[tuple[str, str | None], threading.Lock] = WeakValueDictionary()
146 self._lock = threading.Lock()
147
148 def _load(self) -> URLResolver:
149 if self._resolver is None:
150 with self._lock:
151 if self._resolver is None:
152 spec = self._config["url_resolvers"][self.scheme]
153 module, _, name = spec["type"].rpartition(".")
154 if not module or not name:
155 raise ValueError(f"Expected a fully qualified URL resolver class for {self.scheme!r}")
156 self._resolver = import_class(name, module)(**expand_env_vars(spec.get("options", {})))
157 assert self._resolver is not None
158 return self._resolver
159
160 def resolve(
161 self, url: str, *, expected_root: str | None = None, expected_scope: str | None | object = _ANY_SCOPE
162 ) -> tuple[StorageClient, str]:
163 resolver = self._load()
164 ref = resolver.parse(url)
165 if expected_root is not None and (
166 not ref.is_canonical or ref.root_url != expected_root or (url == expected_root and ref.relative_path)
167 ):
168 raise ValueError("The configured resolver did not recognize the recorded canonical root")
169 if expected_scope is not _ANY_SCOPE and (expected_scope is None or ref.access_scope != expected_scope):
170 raise PermissionError("The inherited reference belongs to a different or unknown access scope")
171 if ref.is_canonical and not url.startswith(ref.root_url):
172 raise ValueError("The parsed canonical root differs from the input URL")
173 if ref.is_canonical and ref.access_scope is not None:
174 key = ref.root_url, ref.access_scope
175 entry = self._clients.get(key)
176 if entry is not None and time() < entry[0]:
177 return entry[1], ref.relative_path
178
179 # Serialize only cold binds for this revision and caller.
180 with self._lock:
181 lock = self._inflight.get(key)
182 if lock is None:
183 self._inflight[key] = lock = threading.Lock()
184 with lock:
185 entry = self._clients.get(key)
186 if entry is not None and time() < entry[0]:
187 return entry[1], ref.relative_path
188 return self._bind(resolver, ref), ref.relative_path
189 return self._bind(resolver, ref), ref.relative_path
190
191 def _bind(self, resolver: URLResolver, ref: ParsedReference) -> StorageClient:
192 bound = resolver.bind(ref)
193 root = bound.canonical_root_url
194 parsed_root = urlparse(root)
195 if (
196 not root.startswith(f"{self.scheme}://")
197 or not parsed_root.netloc
198 or not root.endswith("/")
199 or "?" in root
200 or "#" in root
201 or parsed_root.username is not None
202 ):
203 raise ValueError("A bound reference must return a canonical root URI ending in '/' for its scheme")
204 if ref.is_canonical:
205 if root != ref.root_url:
206 raise ValueError("Resolver redirected a canonical reference to a different root")
207 else:
208 pinned = resolver.parse(root)
209 if not pinned.is_canonical or pinned.root_url != root or pinned.relative_path:
210 raise ValueError("Resolver returned a mutable or invalid canonical root")
211 if (
212 ref.access_scope is not None
213 and pinned.access_scope is not None
214 and pinned.access_scope != ref.access_scope
215 ):
216 raise PermissionError("The caller scope changed while authorizing the reference")
217
218 deadline = bound.reuse_until
219 if deadline is not None and deadline.utcoffset() != timedelta(0):
220 raise ValueError("URL resolver reuse_until must be a timezone-aware UTC datetime")
221
222 # The underscore namespace is reserved for generated profiles.
223 if ref.access_scope is None:
224 identity = uuid4().hex
225 else:
226 identity = hashlib.sha256(json.dumps([self._identity, ref.access_scope, root]).encode()).hexdigest()
227 profile = f"_ref-{identity}"
228 json.dumps(bound.profile_config, allow_nan=False)
229 validate_config({"profiles": {"reference": bound.profile_config}})
230 config = {**self._config, "profiles": {**self._config.get("profiles", {}), profile: bound.profile_config}}
231 client = StorageClient(
232 config=StorageClientConfig._from_bound_profile(
233 config, profile, root, ref.access_scope, telemetry_provider=get_telemetry_provider()
234 )
235 )
236
237 if ref.access_scope is not None:
238 key = root, ref.access_scope
239 with self._lock:
240 now = time()
241 for stale in [k for k, entry in self._clients.items() if entry[0] <= now]:
242 del self._clients[stale]
243 self._clients.pop(key, None)
244 if deadline is not None and deadline.timestamp() > now:
245 if len(self._clients) >= _MAX_REFERENCE_BINDINGS:
246 del self._clients[next(iter(self._clients))]
247 self._clients[key] = deadline.timestamp(), client
248 return client
249
250
251def _read_cached_routes() -> tuple[PathMapping, dict[str, _ConfiguredResolver]]:
252 """Load shortcut routing once per MSC_CONFIG selection, importing extensions only on use."""
253 cache_key = os.getenv("MSC_CONFIG")
254 routes = _PATH_MAPPING_CACHE.get(cache_key)
255 if routes is None:
256 with _PATH_MAPPING_CACHE_LOCK:
257 routes = _PATH_MAPPING_CACHE.get(cache_key)
258 if routes is None:
259 generations = []
260 config, _ = StorageClientConfig._read_msc_config(generations=generations)
261 config = config or {}
262 registration = config.get("url_resolvers", {})
263 identity = hashlib.sha256(json.dumps(generations).encode()).hexdigest() if registration else ""
264 routes = (
265 PathMapping.from_config(config),
266 {scheme: _ConfiguredResolver(scheme, config, identity) for scheme in registration},
267 )
268 if len(_PATH_MAPPING_CACHE) >= _MAX_ROUTING_CONFIGS:
269 del _PATH_MAPPING_CACHE[next(iter(_PATH_MAPPING_CACHE))]
270 _PATH_MAPPING_CACHE[cache_key] = routes
271 return routes
272
273
274def _reopen_reference_path(
275 url: str, root_url: str, *, expected_scope: str | None | object = _ANY_SCOPE
276) -> tuple[StorageClient, str]:
277 """Reopen a recorded URL through its owning resolver in the receiving caller's context."""
278 _check_and_reinitialize_if_forked()
279 _, resolvers = _read_cached_routes()
280 scheme = root_url.partition(":")[0]
281 resolver = resolvers.get(scheme)
282 if resolver is None:
283 raise ValueError(f"No URL resolver configured for the recorded scheme {scheme!r}")
284 return resolver.resolve(url, expected_root=root_url, expected_scope=expected_scope)
285
286
287def _reopen_reference(canonical_root_url: str, *, expected_scope: str | None | object = _ANY_SCOPE) -> StorageClient:
288 return _reopen_reference_path(canonical_root_url, canonical_root_url, expected_scope=expected_scope)[0]
289
290
291def _resolve_non_msc_url(url: str, path_mapping: PathMapping | None = None) -> tuple[str, str]:
292 """
293 Resolve a non-MSC URL to a profile name and path.
294
295 Resolution process:
296 1. First check if MSC config exists
297 2. If config exists, check for possible path mapping
298 3. If no mapping is found, fall back to the reserved POSIX profile (``__filesystem__``) for file paths or create an implicit profile based on URL
299
300 :param url: The non-MSC URL to resolve
301 :return: A tuple of (profile_name, path)
302 """
303 # Check if we have a valid path mapping, if so check if there is a matching mapping
304 if path_mapping is None:
305 path_mapping, _ = _read_cached_routes()
306 if path_mapping:
307 # Look for a matching mapping
308 possible_mapping = path_mapping.find_mapping(url)
309 if possible_mapping:
310 return possible_mapping # return the profile name and path
311
312 # For file paths, use the default POSIX profile
313 if url.startswith("file://"):
314 pr = urlparse(url)
315 return RESERVED_POSIX_PROFILE_NAME, build_full_path(url, pr)
316 elif url.startswith("/"):
317 url = os.path.normpath(url)
318 return RESERVED_POSIX_PROFILE_NAME, url
319
320 # For other URL protocol, create an implicit profile name
321 pr = urlparse(url)
322 protocol = pr.scheme.lower()
323
324 # Translate relative paths to absolute paths
325 if not protocol:
326 return RESERVED_POSIX_PROFILE_NAME, os.path.abspath(url)
327
328 # Validate the protocol is supported
329 if protocol not in SUPPORTED_IMPLICIT_PROFILE_PROTOCOLS:
330 supported_protocols = ", ".join([f"{p}://" for p in SUPPORTED_IMPLICIT_PROFILE_PROTOCOLS])
331 raise ValueError(
332 f'Unknown URL "{url}", expecting "{MSC_PROTOCOL}" or a supported protocol ({supported_protocols}) or a POSIX path'
333 )
334
335 # Build the implicit profile name using the format _protocol-bucket
336 bucket = pr.netloc
337 if not bucket:
338 raise ValueError(f'Invalid URL "{url}", bucket name is required for {protocol}:// URLs')
339
340 profile_name = f"_{protocol}-{bucket}"
341
342 # Return normalized path with leading slash removed
343 path = build_full_path(url, pr)
344 path = path.removeprefix("/")
345
346 return profile_name, path
347
348
[docs]
349def resolve_storage_client(url: str) -> tuple[StorageClient, str]:
350 """
351 Build and return a :py:class:`multistorageclient.StorageClient` instance based on the provided URL or path.
352
353 This function parses the given URL or path and determines the appropriate storage profile and path.
354 It supports URLs with the protocol ``msc://``, as well as POSIX paths or ``file://`` URLs for local file
355 system access. If the profile has already been instantiated, it returns the cached client. Otherwise,
356 it creates a new :py:class:`StorageClient` and caches it.
357
358 The function also supports implicit profiles for non-MSC URLs. When a non-MSC URL is provided (like s3://,
359 gs://, ais://, file://), MSC will infer the storage provider based on the URL protocol and create an implicit
360 profile with the naming convention "_protocol-bucket" (e.g., "_s3-bucket1", "_gs-bucket1").
361
362 Configured URL resolvers authorize catalog references and return clients pinned to a read-only revision.
363 Path mappings defined in the MSC configuration are applied before creating implicit profiles.
364 This allows for explicit mappings between source paths and destination MSC profiles.
365
366 This function is fork-safe: after a fork, the cache is automatically cleared and new client instances
367 are created in the child process to avoid sharing stale connections or file descriptors.
368
369 :param url: The storage location, which can be:
370 - A URL in the format ``msc://profile/path`` for object storage.
371 - A local file system path (absolute POSIX path) or a ``file://`` URL.
372 - A non-MSC URL with a supported protocol (s3://, gs://, ais://).
373
374 :return: A tuple containing the :py:class:`multistorageclient.StorageClient` instance and the parsed path.
375
376 :raises ValueError: If the URL's protocol is neither ``msc`` nor a valid local file system path
377 or a supported non-MSC protocol.
378 """
379 global _STORAGE_CLIENT_CACHE # noqa: PLW0602
380 global _STORAGE_CLIENT_CACHE_LOCK # noqa: PLW0602
381
382 _check_and_reinitialize_if_forked()
383
384 # Normalize the path for msc:/ prefix due to pathlib.Path('msc://')
385 if url.startswith("msc:/") and not url.startswith("msc://"):
386 url = url.replace("msc:/", "msc://")
387
388 # Resolve the URL to a profile name and path
389 if url.startswith(MSC_PROTOCOL):
390 profile, path = _resolve_msc_url(url)
391 else:
392 mappings, resolvers = _read_cached_routes()
393 if resolvers and ":" in url and (owner := resolvers.get(url.partition(":")[0].lower())) is not None:
394 return owner.resolve(url)
395 profile, path = _resolve_non_msc_url(url, mappings)
396
397 # Check if the profile has already been instantiated
398 if profile in _STORAGE_CLIENT_CACHE:
399 return _STORAGE_CLIENT_CACHE[profile], path
400
401 # Create a new StorageClient instance and cache it
402 with _STORAGE_CLIENT_CACHE_LOCK:
403 if profile in _STORAGE_CLIENT_CACHE:
404 return _STORAGE_CLIENT_CACHE[profile], path
405 else:
406 client = StorageClient(
407 config=StorageClientConfig.from_file(profile=profile, telemetry_provider=get_telemetry_provider())
408 )
409 _STORAGE_CLIENT_CACHE[profile] = client
410
411 return client, path
412
413
[docs]
414def open(url: str, mode: str = "rb", **kwargs: Any) -> PosixFile | ObjectFile:
415 """
416 Open a file at the given URL using the specified mode.
417
418 The function utilizes the :py:class:`multistorageclient.StorageClient` to open a file at the provided path.
419 The URL is parsed, and the corresponding :py:class:`multistorageclient.StorageClient` is retrieved or built.
420
421 :param url: The URL of the file to open. (example: ``msc://profile/prefix/dataset.tar``)
422 :param mode: The file mode to open the file in.
423
424 :return: A file-like object that allows interaction with the file.
425
426 :raises ValueError: If the URL's protocol does not match the expected protocol ``msc``.
427 """
428 client, path = resolve_storage_client(url)
429 return client.open(path, mode, **kwargs)
430
431
[docs]
432def glob(pattern: str, attribute_filter_expression: str | None = None) -> builtins.list[str]:
433 """
434 Return a list of files matching a pattern.
435
436 This function supports glob-style patterns for matching multiple files within a storage system. The pattern is
437 parsed, and the associated :py:class:`multistorageclient.StorageClient` is used to retrieve the
438 list of matching files.
439
440 :param pattern: The glob-style pattern to match files. (example: ``msc://profile/prefix/**/*.tar``)
441 :param attribute_filter_expression: The attribute filter expression to apply to the result.
442
443 :return: A list of file paths matching the pattern.
444
445 :raises ValueError: If the URL's protocol does not match the expected protocol ``msc``.
446 """
447 client, path = resolve_storage_client(pattern)
448 if not pattern.startswith(MSC_PROTOCOL) and client.profile == RESERVED_POSIX_PROFILE_NAME:
449 return client.glob(path, include_url_prefix=False, attribute_filter_expression=attribute_filter_expression)
450 else:
451 return client.glob(path, include_url_prefix=True, attribute_filter_expression=attribute_filter_expression)
452
453
[docs]
454def upload_file(url: str, local_path: str | IO, attributes: dict[str, Any] | None = None) -> None:
455 """
456 Upload a file to the given URL from a local path.
457
458 The function utilizes the :py:class:`multistorageclient.StorageClient` to upload a file (object) to the
459 provided path. The URL is parsed, and the corresponding :py:class:`multistorageclient.StorageClient`
460 is retrieved or built.
461
462 :param url: The URL of the file. (example: ``msc://profile/prefix/dataset.tar``)
463 :param local_path: The local path or file-like object to read from.
464
465 :raises ValueError: If the URL's protocol does not match the expected protocol ``msc``.
466 """
467 client, path = resolve_storage_client(url)
468 return client.upload_file(remote_path=path, local_path=local_path, attributes=attributes)
469
470
[docs]
471def download_file(url: str, local_path: str | IO) -> None:
472 """
473 Download a file in a given remote_path to a local path
474
475 The function utilizes the :py:class:`multistorageclient.StorageClient` to download a file (object) at the
476 provided path. The URL is parsed, and the corresponding :py:class:`multistorageclient.StorageClient`
477 is retrieved or built.
478
479 :param url: The URL of the file to download. (example: ``msc://profile/prefix/dataset.tar``)
480 :param local_path: The local path or file-like object to write to.
481
482 :raises ValueError: If the URL's protocol does not match the expected protocol ``msc``.
483 """
484 client, path = resolve_storage_client(url)
485 return client.download_file(remote_path=path, local_path=local_path)
486
487
[docs]
488def is_empty(url: str) -> bool:
489 """
490 Checks whether the specified URL contains any objects.
491
492 :param url: The URL to check, typically pointing to a storage location.
493 :return: ``True`` if there are no objects/files under this URL, ``False`` otherwise.
494
495 :raises ValueError: If the URL's protocol does not match the expected protocol ``msc``.
496 """
497 client, path = resolve_storage_client(url)
498 return client.is_empty(path)
499
500
[docs]
501def is_file(url: str) -> bool:
502 """
503 Checks whether the specified url points to a file (rather than a directory or folder).
504
505 The function utilizes the :py:class:`multistorageclient.StorageClient` to check if a file (object) exists
506 at the provided path. The URL is parsed, and the corresponding :py:class:`multistorageclient.StorageClient`
507 is retrieved or built.
508
509 :param url: The URL to check the existence of a file. (example: ``msc://profile/prefix/dataset.tar``)
510 """
511 client, path = resolve_storage_client(url)
512 return client.is_file(path=path)
513
514
[docs]
515def sync(
516 source_url: str,
517 target_url: str,
518 delete_unmatched_files: bool = False,
519 execution_mode: ExecutionMode = ExecutionMode.LOCAL,
520 patterns: PatternList | None = None,
521 preserve_source_attributes: bool = False,
522 ignore_hidden: bool = True,
523 dryrun: bool = False,
524 dryrun_output_path: str | None = None,
525 symlink_handling: SymlinkHandling = SymlinkHandling.FOLLOW,
526) -> SyncResult:
527 """
528 Syncs files from the source storage to the target storage.
529
530 :param source_url: The URL for the source storage.
531 :param target_url: The URL for the target storage.
532 :param delete_unmatched_files: Whether to delete files at the target that are not present at the source.
533 :param execution_mode: The execution mode to use. Currently supports "local" and "ray".
534 :param patterns: PatternList for include/exclude filtering. If None, all files are included.
535 :param preserve_source_attributes: Whether to preserve source file metadata attributes during synchronization.
536 When False (default), only file content is copied. When True, custom metadata attributes are also preserved.
537
538 .. warning::
539 **Performance Impact**: When enabled without a ``metadata_provider`` configured, this will make a HEAD
540 request for each object to retrieve attributes, which can significantly impact performance on large-scale
541 sync operations. For production use at scale, configure a ``metadata_provider`` in your storage profile.
542 :param ignore_hidden: Whether to ignore hidden files and directories (starting with dot). Default is True.
543 :param dryrun: If True, only enumerate and compare objects without performing any copy/delete operations.
544 The returned :py:class:`SyncResult` will include a :py:class:`DryrunResult` with paths to JSONL files.
545 :param dryrun_output_path: Directory to write dryrun JSONL files into. If None (default), a temporary
546 directory is created automatically. Ignored when dryrun is False.
547 :param symlink_handling: How to handle symbolic links during sync.
548 :py:attr:`SymlinkHandling.FOLLOW` (default) dereferences symlinks and copies the target's bytes.
549 :py:attr:`SymlinkHandling.SKIP` excludes symlinks from the sync.
550 :py:attr:`SymlinkHandling.PRESERVE` recreates symlinks on the target via
551 :py:meth:`AbstractStorageClient.make_symlink` instead of copying bytes (required for
552 round-trip preservation of symlinks).
553 """
554 source_client, source_path = resolve_storage_client(source_url)
555 target_client, target_path = resolve_storage_client(target_url)
556 return target_client.sync_from(
557 source_client,
558 source_path,
559 target_path,
560 delete_unmatched_files,
561 execution_mode=execution_mode,
562 patterns=patterns,
563 preserve_source_attributes=preserve_source_attributes,
564 ignore_hidden=ignore_hidden,
565 dryrun=dryrun,
566 dryrun_output_path=dryrun_output_path,
567 symlink_handling=symlink_handling,
568 )
569
570
[docs]
571def sync_replicas(
572 source_url: str,
573 replica_indices: Sequence[int] | None = None,
574 delete_unmatched_files: bool = False,
575 execution_mode: ExecutionMode = ExecutionMode.LOCAL,
576 patterns: PatternList | None = None,
577 ignore_hidden: bool = True,
578 symlink_handling: SymlinkHandling = SymlinkHandling.FOLLOW,
579) -> None:
580 """
581 Syncs files from the source storage to all the replicas.
582
583 :param source_url: The URL for the source storage.
584 :param replica_indices: Specify the indices of the replicas to sync to. If not provided, all replicas will be synced. Index starts from 0.
585 :param delete_unmatched_files: Whether to delete files at the replicas that are not present at the source.
586 :param execution_mode: The execution mode to use. Currently supports "local" and "ray".
587 :param patterns: PatternList for include/exclude filtering. If None, all files are included.
588 :param ignore_hidden: Whether to ignore hidden files and directories (starting with dot). Default is True.
589 :param symlink_handling: How to handle symbolic links during sync.
590 :py:attr:`SymlinkHandling.FOLLOW` (default) dereferences symlinks and copies the target's bytes.
591 :py:attr:`SymlinkHandling.SKIP` excludes symlinks from the sync.
592 :py:attr:`SymlinkHandling.PRESERVE` recreates symlinks on each replica via
593 :py:meth:`AbstractStorageClient.make_symlink` instead of copying bytes.
594 """
595 source_client, source_path = resolve_storage_client(source_url)
596 source_client.sync_replicas(
597 source_path,
598 replica_indices=replica_indices,
599 delete_unmatched_files=delete_unmatched_files,
600 execution_mode=execution_mode,
601 patterns=patterns,
602 ignore_hidden=ignore_hidden,
603 symlink_handling=symlink_handling,
604 )
605
606
[docs]
607def list(
608 url: str,
609 start_after: str | None = None,
610 end_at: str | None = None,
611 include_directories: bool = False,
612 attribute_filter_expression: str | None = None,
613 show_attributes: bool = False,
614 patterns: PatternList | None = None,
615 symlink_handling: SymlinkHandling = SymlinkHandling.FOLLOW,
616) -> Iterator[ObjectMetadata]:
617 """
618 Lists the contents of the specified URL prefix.
619
620 This function retrieves the corresponding :py:class:`multistorageclient.StorageClient`
621 for the given URL and returns an iterator of objects (files or directories) stored under the provided prefix.
622
623 :param url: The prefix to list objects under.
624 :param start_after: The key to start after (i.e. exclusive). An object with this key doesn't have to exist.
625 :param end_at: The key to end at (i.e. inclusive). An object with this key doesn't have to exist.
626 :param include_directories: Whether to include directories in the result. When True, directories are returned alongside objects.
627 :param attribute_filter_expression: The attribute filter expression to apply to the result.
628 :param show_attributes: Whether to return attributes in the result.
629 :param patterns: PatternList for include/exclude filtering. If None, all files are included.
630 :param symlink_handling: How to handle symbolic links. Only applicable for POSIX file storage.
631 :return: An iterator of :py:class:`ObjectMetadata` objects representing the files (and optionally directories)
632 accessible under the specified URL prefix. Keys are formatted using the client's canonical URL.
633 """
634 client, path = resolve_storage_client(url)
635 return client.list(
636 path=path,
637 start_after=start_after,
638 end_at=end_at,
639 include_directories=include_directories,
640 include_url_prefix=True,
641 attribute_filter_expression=attribute_filter_expression,
642 show_attributes=show_attributes,
643 patterns=patterns,
644 symlink_handling=symlink_handling,
645 )
646
647
[docs]
648def list_recursive(
649 url: str,
650 start_after: str | None = None,
651 end_at: str | None = None,
652 max_workers: int = 32,
653 look_ahead: int = 2,
654 patterns: PatternList | None = None,
655 symlink_handling: SymlinkHandling = SymlinkHandling.FOLLOW,
656) -> Iterator[ObjectMetadata]:
657 """
658 Lists files recursively under the specified URL.
659
660 This function retrieves the corresponding :py:class:`multistorageclient.StorageClient`
661 for the given URL and returns an iterator of files under the provided path.
662
663 :param url: The path to list objects under.
664 :param start_after: The key to start after (i.e. exclusive). An object with this key doesn't have to exist.
665 :param end_at: The key to end at (i.e. inclusive). An object with this key doesn't have to exist.
666 :param max_workers: Maximum concurrent workers for provider-level recursive listing.
667 :param look_ahead: Prefixes to buffer per worker for provider-level recursive listing.
668 :param patterns: PatternList for include/exclude filtering. If None, all files are included.
669 :param symlink_handling: How to handle symbolic links during listing.
670 :return: An iterator of :py:class:`ObjectMetadata` objects representing files accessible under the specified URL path.
671 The returned keys use the same URL-prefix behavior as :py:meth:`multistorageclient.list`.
672 """
673 client, path = resolve_storage_client(url)
674 return client.list_recursive(
675 path=path,
676 start_after=start_after,
677 end_at=end_at,
678 max_workers=max_workers,
679 look_ahead=look_ahead,
680 include_url_prefix=True,
681 patterns=patterns,
682 symlink_handling=symlink_handling,
683 )
684
685
[docs]
686def write(url: str, body: bytes, attributes: dict[str, Any] | None = None) -> None:
687 """
688 Writes an object to the storage provider at the specified path.
689
690 :param url: The path where the object should be written.
691 :param body: The content to write to the object.
692 """
693 client, path = resolve_storage_client(url)
694 client.write(path=path, body=body, attributes=attributes)
695
696
[docs]
697def make_symlink(url: str, target_url: str) -> None:
698 """
699 Creates a symbolic link at ``url`` pointing to ``target_url``.
700
701 Both URLs must resolve to the same storage profile.
702
703 :param url: The URL where the symlink will be created.
704 :param target_url: The URL of the target that the symlink points to.
705 :raises ValueError: If the two URLs resolve to different storage profiles.
706 """
707 client, path = resolve_storage_client(url)
708 target_client, target_path = resolve_storage_client(target_url)
709 if client is not target_client:
710 raise ValueError("Cannot create cross-profile symlink: url and target_url must belong to the same profile.")
711 client.make_symlink(path=path, target=target_path)
712
713
[docs]
714def delete(url: str, recursive: bool = False) -> None:
715 """
716 Deletes the specified object(s) from the storage provider.
717
718 This function retrieves the corresponding :py:class:`multistorageclient.StorageClient`
719 for the given URL and deletes the object(s) at the specified path.
720
721 :param url: The URL of the object to delete. (example: ``msc://profile/prefix/file.txt``)
722 :param recursive: Whether to delete objects in the path recursively.
723 """
724 client, path = resolve_storage_client(url)
725 client.delete(path, recursive=recursive)
726
727
[docs]
728def info(url: str) -> ObjectMetadata:
729 """
730 Retrieves metadata or information about an object stored at the specified path.
731
732 :param url: The URL of the object to retrieve information about. (example: ``msc://profile/prefix/file.txt``)
733
734 :return: An :py:class:`ObjectMetadata` object representing the object's metadata.
735 """
736 client, path = resolve_storage_client(url)
737 return client.info(path)
738
739
748
749
[docs]
750def generate_presigned_url(
751 url: str,
752 *,
753 method: str = "GET",
754 signer_type: SignerType | None = None,
755 signer_options: dict[str, Any] | None = None,
756) -> str:
757 """
758 Generate a pre-signed URL granting temporary access to the object at *url*.
759
760 :param url: The storage URL. (example: ``msc://profile/prefix/file.bin``)
761 :param method: The HTTP method the URL should authorise (e.g. ``"GET"``, ``"PUT"``).
762 :param signer_type: The signing backend to use. ``None`` means the provider's native signer.
763 :param signer_options: Backend-specific options forwarded to the signer.
764 :return: A pre-signed URL string.
765 """
766 client, path = resolve_storage_client(url)
767 return client.generate_presigned_url(path, method=method, signer_type=signer_type, signer_options=signer_options)