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 asyncio
17import atexit
18import os
19from collections.abc import Callable
20from concurrent.futures import ThreadPoolExecutor
21from functools import partial
22from typing import Any
23
24from fsspec.asyn import AsyncFileSystem, _run_coros_in_chunks
25
26from ..client import StorageClient
27from ..file import ObjectFile, PosixFile
28from ..shortcuts import resolve_storage_client
29from ..types import MSC_PROTOCOL_NAME, Range, SuffixRange
30from ..utils import _ensure_bytes
31
32_GLOBAL_THREAD_POOL = ThreadPoolExecutor(max_workers=int(os.getenv("MSC_MAX_WORKERS", "8")))
33
34atexit.register(lambda: _GLOBAL_THREAD_POOL.shutdown(wait=False))
35
36
37# pyright: reportIncompatibleMethodOverride=false
[docs]
38class MultiStorageAsyncFileSystem(AsyncFileSystem):
39 """
40 Custom :py:class:`fsspec.asyn.AsyncFileSystem` implementation for MSC protocol (``msc://``).
41 Uses :py:class:`multistorageclient.StorageClient` for backend operations.
42 """
43
44 protocol = MSC_PROTOCOL_NAME
45
46 def __init__(self, **kwargs: Any) -> None:
47 """
48 Initializes the :py:class:`MultiStorageAsyncFileSystem`.
49
50 :param kwargs: Additional arguments for the :py:class:`fsspec.asyn.AsyncFileSystem`.
51 """
52 super().__init__(**kwargs)
53
[docs]
54 def resolve_path_and_storage_client(self, path: str | os.PathLike) -> tuple[StorageClient, str]:
55 """
56 Resolves the path and retrieves the associated :py:class:`multistorageclient.StorageClient`.
57
58 :param path: The file path to resolve.
59
60 :return: A tuple containing the :py:class:`multistorageclient.StorageClient` and the resolved path.
61 """
62 # Use unstrip_protocol to prepend our 'msc://' protocol only if it wasn't given in "path".
63 return resolve_storage_client(self.unstrip_protocol(str(path).lstrip("/")))
64
[docs]
65 @staticmethod
66 def asynchronize_sync(func: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
67 """
68 Runs a synchronous function asynchronously using asyncio.
69
70 :param func: The synchronous function to be executed asynchronously.
71 :param args: Positional arguments to pass to the function.
72 :param kwargs: Keyword arguments to pass to the function.
73
74 :return: The result of the asynchronous execution of the function.
75 """
76 loop = asyncio.get_event_loop()
77 return loop.run_in_executor(_GLOBAL_THREAD_POOL, partial(func, *args, **kwargs))
78
[docs]
79 def ls(self, path: str, detail: bool = True, **kwargs: Any) -> list[dict[str, Any]] | list[str]:
80 """
81 Lists the contents of a directory.
82
83 :param path: The directory path to list.
84 :param detail: Whether to return detailed information for each file.
85 :param kwargs: Additional arguments for list functionality.
86
87 :return: A list of file names or detailed information depending on the 'detail' argument.
88 """
89 storage_client, dir_path = self.resolve_path_and_storage_client(path)
90
91 if dir_path and not dir_path.endswith("/"):
92 dir_path += "/"
93
94 objects = storage_client.list(path=dir_path, include_directories=True)
95
96 if detail:
97 return [
98 {
99 "name": os.path.join(storage_client.profile, obj.key),
100 "ETag": obj.etag,
101 "LastModified": obj.last_modified,
102 "size": obj.content_length,
103 "ContentType": obj.content_type,
104 "type": obj.type,
105 }
106 for obj in objects
107 ]
108 else:
109 return [os.path.join(storage_client.profile, obj.key) for obj in objects]
110
111 async def _ls(self, path: str, detail: bool = True, **kwargs: Any) -> list[dict[str, Any]] | list[str]:
112 """
113 Asynchronously lists the contents of a directory.
114
115 :param path: The directory path to list.
116 :param detail: Whether to return detailed information for each file.
117 :param kwargs: Additional arguments for list functionality.
118
119 :return: A list of file names or detailed information depending on the 'detail' argument.
120 """
121 return await self.asynchronize_sync(self.ls, path, detail, **kwargs)
122
[docs]
123 def info(self, path: str, **kwargs: Any) -> dict[str, Any]:
124 """
125 Retrieves metadata information for a file.
126
127 :param path: The file path to retrieve information for.
128 :param kwargs: Additional arguments for info functionality.
129
130 :return: A dictionary containing file metadata such as ETag, last modified, and size.
131 """
132 storage_client, file_path = self.resolve_path_and_storage_client(path)
133 metadata = storage_client.info(file_path)
134 return {
135 "name": os.path.join(storage_client.profile, metadata.key),
136 "ETag": metadata.etag,
137 "LastModified": metadata.last_modified,
138 "size": metadata.content_length,
139 "ContentType": metadata.content_type,
140 "type": metadata.type,
141 }
142
143 async def _info(self, path: str, **kwargs: Any) -> dict[str, Any]:
144 """
145 Asynchronously retrieves metadata information for a file.
146
147 :param path: The file path to retrieve information for.
148 :param kwargs: Additional arguments for info functionality.
149
150 :return: A dictionary containing file metadata such as ETag, last modified, and size.
151 """
152 return await self.asynchronize_sync(self.info, path, **kwargs)
153
[docs]
154 def rm_file(self, path: str, **kwargs: Any):
155 """
156 Removes a file.
157
158 :param path: The file or directory path to remove.
159 :param kwargs: Additional arguments for remove functionality.
160 """
161 storage_client, file_path = self.resolve_path_and_storage_client(path)
162 recursive = kwargs.get("recursive", False)
163 storage_client.delete(file_path, recursive=recursive)
164
165 async def _rm_file(self, path: str, **kwargs: Any):
166 """
167 Asynchronously removes a file.
168
169 :param path: The file or directory path to remove.
170 :param kwargs: Additional arguments for remove functionality.
171 """
172 return await self.asynchronize_sync(self.rm_file, path, **kwargs)
173
174 async def _rm(self, path, recursive=False, batch_size=None, **kwargs):
175 """
176 Asynchronously removes a file or directory.
177 Instead of using the implementation in the parent class to expand the path and parallel delete the files,
178 we explicitly pass down the recursive value and use the delete method in the StorageClient to handle the directory deletion.
179
180 :param path: The file or directory path to remove.
181 :param recursive: Whether to recursively remove directories.
182 :param batch_size: The number of files to process in each batch.
183 :param kwargs: Additional arguments for remove functionality.
184 """
185
186 if "recursive" not in kwargs:
187 kwargs["recursive"] = recursive
188
189 return await _run_coros_in_chunks(
190 [self._rm_file(path, **kwargs)],
191 batch_size=-1, # no throttling
192 nofiles=True,
193 )
194
[docs]
195 def cp_file(self, path1: str, path2: str, **kwargs: Any):
196 """
197 Copies a file from the source path to the destination path.
198
199 Virtual directory prefixes are skipped. Recursive fsspec moves expand those
200 prefixes and ask for them to be copied, but they are not objects.
201
202 :param path1: The source file path.
203 :param path2: The destination file path.
204 :param kwargs: Additional arguments for copy functionality.
205
206 :raises AttributeError: If the source and destination paths are associated with different profiles.
207 """
208 src_storage_client, src_path = self.resolve_path_and_storage_client(path1)
209 dest_storage_client, dest_path = self.resolve_path_and_storage_client(path2)
210
211 if src_storage_client != dest_storage_client:
212 raise AttributeError(
213 f"Cannot copy file from '{path1}' to '{path2}' because the source and destination paths are associated with different profiles. Cross-profile file operations are not supported."
214 )
215
216 if src_storage_client.info(src_path).type == "directory":
217 return
218
219 src_storage_client.copy(src_path, dest_path)
220
221 async def _cp_file(self, path1: str, path2: str, **kwargs: Any):
222 """
223 Asynchronously copies a file from the source path to the destination path.
224
225 :param path1: The source file path.
226 :param path2: The destination file path.
227 :param kwargs: Additional arguments for copy functionality.
228
229 :raises AttributeError: If the source and destination paths are associated with different profiles.
230 """
231 await self.asynchronize_sync(self.cp_file, path1, path2, **kwargs)
232
[docs]
233 def get_file(self, rpath: str, lpath: str, **kwargs: Any) -> None:
234 """
235 Downloads a file from the remote path to the local path.
236
237 :param rpath: The remote path of the file to download.
238 :param lpath: The local path to store the file.
239 :param kwargs: Additional arguments for file retrieval functionality.
240 """
241 storage_client, rpath = self.resolve_path_and_storage_client(rpath)
242 storage_client.download_file(rpath, lpath)
243
244 async def _get_file(self, rpath: str, lpath: str, **kwargs: Any) -> None:
245 """
246 Asynchronously downloads a file from the remote path to the local path.
247
248 :param rpath: The remote path of the file to download.
249 :param lpath: The local path to store the file.
250 :param kwargs: Additional arguments for file retrieval functionality.
251 """
252 await self.asynchronize_sync(self.get_file, rpath, lpath, **kwargs)
253
[docs]
254 def put_file(self, lpath: str, rpath: str, **kwargs: Any) -> None:
255 """
256 Uploads a local file to the remote path.
257
258 :param lpath: The local path of the file to upload.
259 :param rpath: The remote path to store the file.
260 :param kwargs: Additional arguments for file upload functionality.
261 """
262 attributes_dict = kwargs.pop("attributes", {})
263 storage_client, rpath = self.resolve_path_and_storage_client(rpath)
264 storage_client.upload_file(rpath, lpath, attributes=attributes_dict)
265
266 async def _put_file(self, lpath: str, rpath: str, **kwargs: Any) -> None:
267 """
268 Asynchronously uploads a local file to the remote path.
269
270 :param lpath: The local path of the file to upload.
271 :param rpath: The remote path to store the file.
272 :param kwargs: Additional arguments for file upload functionality.
273 """
274 await self.asynchronize_sync(self.put_file, lpath, rpath, **kwargs)
275
[docs]
276 def open(self, path: str, mode: str = "rb", **kwargs: Any) -> PosixFile | ObjectFile:
277 """
278 Opens a file at the given path.
279
280 :param path: The file path to open.
281 :param mode: The mode in which to open the file.
282 :param kwargs: Additional arguments passed to client.open (e.g., check_source_version, prefetch_file, etc.)
283
284 :return: A ManagedFile object representing the opened file.
285 """
286 storage_client, path = self.resolve_path_and_storage_client(path)
287 return storage_client.open(path, mode, **kwargs)
288
289 async def _open(self, path: str, mode: str = "rb", **kwargs: Any) -> PosixFile | ObjectFile:
290 """
291 Asynchronously opens a file at the given path.
292
293 :param path: The file path to open.
294 :param mode: The mode in which to open the file.
295 :param kwargs: Additional arguments for file opening.
296
297 :return: A ManagedFile object representing the opened file.
298 """
299 return await self.asynchronize_sync(self.open, path, mode, **kwargs)
300
[docs]
301 def pipe_file(self, path: str, value: bytes, **kwargs: Any) -> None:
302 """
303 Writes a value (bytes) directly to a file at the given path.
304
305 :param path: The file path to write the value to.
306 :param value: The bytes to write to the file.
307 :param kwargs: Additional arguments for writing functionality (e.g., attributes dict for custom metadata).
308 """
309 attributes_dict = kwargs.pop("attributes", {})
310 storage_client, path = self.resolve_path_and_storage_client(path)
311 storage_client.write(path, value, attributes=attributes_dict)
312
313 async def _pipe_file(self, path: str, value: bytes, **kwargs: Any) -> None:
314 """
315 Asynchronously writes a value (bytes) directly to a file at the given path.
316
317 :param path: The file path to write the value to.
318 :param value: The bytes to write to the file.
319 :param kwargs: Additional arguments for writing functionality.
320 """
321 await self.asynchronize_sync(self.pipe_file, path, value, **kwargs)
322
[docs]
323 def cat_file(self, path: str, start: int | None = None, end: int | None = None, **kwargs: Any) -> bytes:
324 """
325 Reads the contents of a file at the given path.
326
327 :param path: The file path to read from.
328 :param start: The offset of the first byte to read. Negative values count back from the end of the file.
329 Defaults to the start of the file.
330 :param end: The offset to stop reading at (exclusive). Negative values count back from the end of the file.
331 Defaults to the end of the file.
332 :param kwargs: Additional arguments for file reading functionality.
333
334 :return: The contents of the file, or of the requested byte range, as bytes.
335 """
336 storage_client, path = self.resolve_path_and_storage_client(path)
337 if start is None and end is None:
338 return _ensure_bytes(storage_client.read(path))
339
340 if start is None:
341 start = 0
342 if start < 0 and end is None:
343 return _ensure_bytes(storage_client.read(path, byte_range=SuffixRange(size=-start)))
344 if start < 0 or end is None or end < 0:
345 start, end, _ = slice(start, end).indices(storage_client.info(path).content_length)
346 if end <= start:
347 return b""
348 return _ensure_bytes(storage_client.read(path, byte_range=Range(offset=start, size=end - start)))
349
350 async def _cat_file(self, path: str, start: int | None = None, end: int | None = None, **kwargs: Any) -> bytes:
351 """
352 Asynchronously reads the contents of a file at the given path.
353
354 :param path: The file path to read from.
355 :param start: The offset of the first byte to read. Negative values count back from the end of the file.
356 Defaults to the start of the file.
357 :param end: The offset to stop reading at (exclusive). Negative values count back from the end of the file.
358 Defaults to the end of the file.
359 :param kwargs: Additional arguments for file reading functionality.
360
361 :return: The contents of the file, or of the requested byte range, as bytes.
362 """
363 return await self.asynchronize_sync(self.cat_file, path, start=start, end=end, **kwargs)