Repository navigation
Type put destinations and document path addressing (GH-1404) #1426
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
c12ec87
b228a1e
919067b
032abc3
a5e334f
7eb9cd6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -190,11 +190,12 @@ def run(self) -> None: | |
| if stopped: | ||
| raise CancelledError("Stopped before the transaction could commit the write.") | ||
|
|
||
| def open(self, path: str, mode: str, **kwargs) -> S3File: | ||
| def open(self, path: str | S3Path, mode: str, **kwargs) -> S3File: | ||
| """Open the file of the write, which joins the transaction unless the write is stopped. | ||
|
|
||
| Args: | ||
| path: S3 path (s3://bucket/key) of the file. | ||
| path: S3 path (s3://bucket/key) of the file, or an ``S3Path``, | ||
| which is opened by its bucket and key. | ||
| mode: The binary write mode of the file. | ||
| **kwargs: The other arguments of ``open()``, except | ||
| ``compression``. With ``autocommit=True``, as with | ||
|
|
@@ -205,7 +206,12 @@ def open(self, path: str, mode: str, **kwargs) -> S3File: | |
| The file. | ||
| """ | ||
| autocommit = kwargs.pop("autocommit", False) | ||
| file = self._fs._open(self._fs._strip_protocol(path), mode, autocommit=autocommit, **kwargs) | ||
| file = self._fs._open( | ||
| path if isinstance(path, S3Path) else self._fs._strip_protocol(path), | ||
| mode, | ||
| autocommit=autocommit, | ||
| **kwargs, | ||
| ) | ||
| with self._lock: | ||
| self._files.append(file) | ||
| # Under the lock, so that a cancellation either finds the file | ||
|
|
@@ -541,29 +547,29 @@ def _pipe_file_in_transaction( | |
| async def _put_file( | ||
| self, | ||
| lpath: str | os.PathLike[str], | ||
| rpath: str | os.PathLike[str], | ||
| rpath: str | os.PathLike[str] | S3Path, | ||
| callback=_DEFAULT_CALLBACK, | ||
| mode: str = "overwrite", | ||
| **kwargs, | ||
| ) -> None: | ||
| _S3BatchTasks.track() | ||
| rpath = stringify_path(rpath) | ||
| target: str | S3Path = rpath if isinstance(rpath, S3Path) else stringify_path(rpath) | ||
| if self._intrans: | ||
| # See _pipe_file. | ||
| await self._write_in_transaction( | ||
| functools.partial( | ||
| self._put_file_in_transaction, lpath, rpath, callback, mode, **kwargs | ||
| self._put_file_in_transaction, lpath, target, callback, mode, **kwargs | ||
| ) | ||
| ) | ||
| return | ||
| await self._thread_pool.run( | ||
| self._sync_fs.put_file, lpath, rpath, callback=callback, mode=mode, **kwargs | ||
| self._sync_fs.put_file, lpath, target, callback=callback, mode=mode, **kwargs | ||
| ) | ||
|
|
||
| def _put_file_in_transaction( | ||
| self, | ||
| lpath: str | os.PathLike[str], | ||
| rpath: str, | ||
| rpath: str | S3Path, | ||
| callback, | ||
| mode: str, | ||
| open_file: Callable[..., S3File], | ||
|
|
@@ -576,7 +582,8 @@ def _put_file_in_transaction( | |
|
|
||
| Args: | ||
| lpath: Local file path to upload. | ||
| rpath: S3 destination path (s3://bucket/key). | ||
| rpath: S3 destination path (s3://bucket/key), or an ``S3Path``, | ||
| whose bucket and key are written as they are. | ||
| callback: Progress callback for tracking upload progress. | ||
| mode: "overwrite" or "create". With "create", the file is | ||
| opened in ``xb`` mode: raise FileExistsError when the object | ||
|
|
@@ -595,7 +602,8 @@ def _put_file_in_transaction( | |
| """ | ||
| if os.path.isdir(lpath): | ||
| return | ||
| if not S3Path.parse(rpath).key: | ||
| s3_path = S3Path.of(rpath) | ||
| if not s3_path.key: | ||
| return | ||
|
|
||
| size = os.path.getsize(lpath) | ||
|
|
@@ -619,7 +627,7 @@ def _put_file_in_transaction( | |
| max_workers=max_workers, | ||
| s3_additional_kwargs=s3_additional_kwargs, | ||
| )._write_file_and_close(local, callback) | ||
| self.invalidate_cache(rpath) | ||
| self._invalidate(s3_path) | ||
|
|
||
| async def _get_file( | ||
| self, | ||
|
|
@@ -929,42 +937,14 @@ async def _get( | |
| batch_size = kwargs.get("batch_size", self.batch_size) | ||
| if batch_size is not None and batch_size > 0: | ||
| concurrency = min(concurrency, batch_size) | ||
| await _S3BatchTasks().run( | ||
| self._get_pairs(pairs, callback, **self._sync_fs._batch_kwargs(concurrency, kwargs)) | ||
| ) | ||
|
|
||
| async def _get_pairs( | ||
| self, pairs: list[tuple[str | S3Path, Any]], callback: Any, **kwargs | ||
| ) -> None: | ||
| """Download the pairs of a ``get()`` as fsspec's ``_get()`` downloads lists of paths. | ||
|
|
||
| Each download gets a branch of the callback named after the string of | ||
| its source, and the sources that a listing returns are downloaded by | ||
| their buckets and keys. | ||
|
|
||
| Args: | ||
| pairs: The S3 sources and their local destinations. | ||
| callback: Progress callback. | ||
| **kwargs: Passed to ``_get_file()``, and ``batch_size``, the | ||
| number of downloads to run at once. | ||
| """ | ||
| # As fsspec's _get() for lists of paths. | ||
| for _, lp in pairs: | ||
| os.makedirs(os.path.dirname(lp), exist_ok=True) | ||
| batch_size = kwargs.pop("batch_size", self.batch_size) | ||
| callback.set_size(len(pairs)) | ||
|
|
||
| async def get_pair(rp: str | S3Path, lp: Any) -> None: | ||
| """Download a pair with a branch of the callback. | ||
|
|
||
| Args: | ||
| rp: The S3 source. | ||
| lp: The local destination. | ||
| """ | ||
| with callback.branched(str(rp), lp, **kwargs) as child: | ||
| await self._get_file(rp, lp, callback=child, **kwargs) | ||
|
|
||
| await _run_coros_in_chunks( | ||
| [get_pair(rp, lp) for rp, lp in pairs], batch_size=batch_size, callback=callback | ||
| # A local path, as copy_pairs() names it. | ||
| os.makedirs(os.path.dirname(cast(str, lp)), exist_ok=True) | ||
| await _S3BatchTasks().run( | ||
| self._transfer_pairs( | ||
| self._get_file, pairs, callback, **self._sync_fs._batch_kwargs(concurrency, kwargs) | ||
| ) | ||
| ) | ||
|
|
||
| async def _put( | ||
|
|
@@ -1001,23 +981,104 @@ async def _put( | |
| The return values of the ``_put_file()`` calls, as in fsspec. | ||
|
|
||
| Raises: | ||
| ValueError: If two files have the same destination. | ||
| ValueError: If two files have the same destination, or the | ||
| destination of a local file names a version, also when | ||
| ``rpath`` names one and the file is named below it. | ||
| """ | ||
| lpath, rpath = self._sync_fs._stringify_paths(lpath), self._sync_fs._stringify_paths(rpath) | ||
| pairs = await self._thread_pool.run( | ||
| self._sync_fs._put_pairs, lpath, rpath, recursive=recursive, maxdepth=maxdepth, **kwargs | ||
| ) | ||
| files = [(lp, rp) for lp, rp in pairs if not os.path.isdir(lp)] | ||
| return await _S3BatchTasks().run( | ||
| super()._put( | ||
| [lp for lp, _ in files], | ||
| [rp for _, rp in files], | ||
| callback=callback, | ||
| batch_size=batch_size, | ||
| **kwargs, | ||
| self._transfer_pairs( | ||
| self._put_file, files, callback, batch_size=batch_size or self.batch_size, **kwargs | ||
| ) | ||
| ) | ||
|
|
||
| async def _transfer_pairs( | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Rebase onto #1398, and independent review of the resolution (relayed result, Codex): FINDINGS (4), repaired in 0ee4e26 Rebase:
Reviewer and run:
Coverage, in the reviewer's words: the duplicate check "still runs before transfers start", explicit destinations "compare as protocol-stripped strings", generated children "compare by Findings and repairs:
Validation at 0ee4e26:
An independent follow-up of these repairs follows.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Independent follow-up of the rebase repairs (relayed result, Codex): FINDINGS (4). 2 were repaired in 798b7d3; 2 predate #1426 and are added to #1427 Reviewer and run:
Coverage, in the reviewer's words: upload pairing "preserves literal suffixes for files named below the root, keeps directory destinations as strings, and checks duplicate file destinations before scheduling uploads", plus the callback arguments, batching, return values, cancellation, the two new tests and the docstrings. Findings:
Validation at 798b7d3:
An independent follow-up of this repair follows.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Rebase onto #1423, and independent follow-up of the cancellation repair (relayed result, Codex): FINDINGS (3). 2 were repaired in 7eb9cd6; 1 is accepted within the interrupt guarantee Rebase:
Reviewer and run:
Findings:
Validation at 7eb9cd6, rebased on 703aaad:
|
||
| self, | ||
| transfer: Callable[..., Awaitable[Any]], | ||
| pairs: list[tuple[Any, Any]], | ||
| callback: Any, | ||
| **kwargs, | ||
| ) -> list[Any]: | ||
| """Run the transfers of lists of paths as fsspec's ``_get()`` and ``_put()`` do. | ||
|
|
||
| Each transfer receives its paths as they are, so that a listed key or | ||
| a destination named after a local file is transferred by its bucket | ||
| and key, and runs through the callback's ``branch_coro()``, as in | ||
| fsspec, with the paths as the names of its branch, an ``S3Path`` as | ||
| its string. | ||
|
|
||
| Args: | ||
| transfer: ``_get_file()`` or ``_put_file()``. | ||
| pairs: The sources and destinations. | ||
| callback: Progress callback. | ||
| **kwargs: Passed to the transfers, and ``batch_size``, the | ||
| number of transfers to run at once. | ||
|
|
||
| Returns: | ||
| The results of the transfers, as fsspec's ``_put()`` returns them. | ||
| """ | ||
| batch_size = kwargs.pop("batch_size", self.batch_size) | ||
| callback.set_size(len(pairs)) | ||
|
|
||
| def run(path1: Any, path2: Any) -> Awaitable[Any]: | ||
| """Return the transfer of a pair, run through the callback's ``branch_coro()``. | ||
|
|
||
| The callback wraps the transfer when the coroutine is created, | ||
| before any transfer is scheduled, as in fsspec. The task of the | ||
| transfer joins the batch before the wrapper runs, so that a | ||
| cancellation of the batch also stops a transfer whose wrapper is | ||
| still waiting to start it. | ||
|
|
||
| Args: | ||
| path1: The source. | ||
| path2: The destination. | ||
|
|
||
| Returns: | ||
| The coroutine of the transfer. | ||
| """ | ||
|
|
||
| async def transfer_pair(label1: Any, label2: Any, **transfer_kwargs: Any) -> Any: | ||
| """Transfer the pair, whose branch the labels name. | ||
|
|
||
| Args: | ||
| label1: The name of the source in the branch. | ||
| label2: The name of the destination in the branch. | ||
| **transfer_kwargs: The arguments of the transfer, with the | ||
| branch of the callback. | ||
|
|
||
| Returns: | ||
| The result of the transfer. | ||
| """ | ||
| return await transfer(path1, path2, **transfer_kwargs) | ||
|
|
||
| branched = callback.branch_coro(transfer_pair) | ||
|
|
||
| async def tracked() -> Any: | ||
| """Run the wrapped transfer as a task of the batch. | ||
|
|
||
| Returns: | ||
| The result of the transfer. | ||
| """ | ||
| _S3BatchTasks.track() | ||
| return await branched( | ||
| str(path1) if isinstance(path1, S3Path) else path1, | ||
| str(path2) if isinstance(path2, S3Path) else path2, | ||
| **kwargs, | ||
| ) | ||
|
|
||
| return tracked() | ||
|
|
||
| return cast( | ||
| list[Any], | ||
| await _run_coros_in_chunks( | ||
| [run(p1, p2) for p1, p2 in pairs], batch_size=batch_size, callback=callback | ||
| ), | ||
| ) | ||
|
|
||
| async def _pipe(self, path, value=None, batch_size=None, **kwargs) -> list[Any]: | ||
| """Write bytes into one or more paths. | ||
|
|
||
|
|
@@ -1659,7 +1720,7 @@ async def _expand_path(self, path, recursive=False, maxdepth=None, **kwargs) -> | |
|
|
||
| def _open( | ||
| self, | ||
| path: str, | ||
| path: str | S3Path, | ||
| mode: str = "rb", | ||
| block_size: int | None = None, | ||
| cache_type: str | None = None, | ||
|
|
@@ -1785,13 +1846,14 @@ def rmdir(self, path: str | os.PathLike[str]) -> None: | |
| """ | ||
| self._sync_fs.rmdir(path) | ||
|
|
||
| def sign(self, path: str | os.PathLike[str], expiration: int = 3600, **kwargs) -> str: | ||
| def sign(self, path: str | os.PathLike[str] | S3Path, expiration: int = 3600, **kwargs) -> str: | ||
| """Generate a presigned URL for S3 object access. | ||
|
|
||
| See :meth:`S3FileSystem.sign`. | ||
|
|
||
| Args: | ||
| path: S3 path (s3://bucket/key) to generate the URL for. | ||
| path: S3 path (s3://bucket/key) to generate the URL for, or an | ||
| ``S3Path``, as for :meth:`S3FileSystem.sign`. | ||
| expiration: URL expiration time in seconds. | ||
| **kwargs: Additional parameters passed to :meth:`S3FileSystem.sign`. | ||
|
|
||
|
|
@@ -1800,27 +1862,31 @@ def sign(self, path: str | os.PathLike[str], expiration: int = 3600, **kwargs) - | |
| """ | ||
| return cast(str, self._sync_fs.sign(path, expiration=expiration, **kwargs)) | ||
|
|
||
| def metadata(self, path: str | os.PathLike[str], **kwargs) -> S3Metadata: | ||
| def metadata(self, path: str | os.PathLike[str] | S3Path, **kwargs) -> S3Metadata: | ||
| """Return the metadata of the path. | ||
|
|
||
| See :meth:`S3FileSystem.metadata`. | ||
|
|
||
| Args: | ||
| path: S3 path (s3://bucket/key) to get metadata for. | ||
| path: S3 path (s3://bucket/key) to get metadata for, or an | ||
| ``S3Path``, as for :meth:`S3FileSystem.metadata`. | ||
| **kwargs: Additional parameters passed to the HeadObject API. | ||
|
|
||
| Returns: | ||
| S3Metadata of the object. | ||
| """ | ||
| return self._sync_fs.metadata(path, **kwargs) | ||
|
|
||
| def getxattr(self, path: str | os.PathLike[str], attr_name: str, **kwargs) -> str | None: | ||
| def getxattr( | ||
| self, path: str | os.PathLike[str] | S3Path, attr_name: str, **kwargs | ||
| ) -> str | None: | ||
| """Get an attribute from the user-defined metadata of the path. | ||
|
|
||
| See :meth:`S3FileSystem.getxattr`. | ||
|
|
||
| Args: | ||
| path: S3 path (s3://bucket/key) to get the attribute for. | ||
| path: S3 path (s3://bucket/key) to get the attribute for, or an | ||
| ``S3Path``. | ||
| attr_name: The name of the attribute. | ||
| **kwargs: Additional parameters passed to the HeadObject API. | ||
|
|
||
|
|
@@ -1830,14 +1896,18 @@ def getxattr(self, path: str | os.PathLike[str], attr_name: str, **kwargs) -> st | |
| return self._sync_fs.getxattr(path, attr_name, **kwargs) | ||
|
|
||
| def setxattr( | ||
| self, path: str | os.PathLike[str], copy_kwargs: dict[str, Any] | None = None, **kwargs | ||
| self, | ||
| path: str | os.PathLike[str] | S3Path, | ||
| copy_kwargs: dict[str, Any] | None = None, | ||
| **kwargs, | ||
| ) -> None: | ||
| """Set the user-defined metadata of the path. | ||
|
|
||
| See :meth:`S3FileSystem.setxattr`. | ||
|
|
||
| Args: | ||
| path: S3 path (s3://bucket/key) to set metadata for. | ||
| path: S3 path (s3://bucket/key) to set metadata for, or an | ||
| ``S3Path``. | ||
| copy_kwargs: Additional parameters to use for the underlying | ||
| CopyObject API call. | ||
| **kwargs: Key-value pairs of metadata to set; a None value deletes the | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Self-review round one (implementation behavior): FINDINGS, repaired in e9bc32d
Scope: the full diff
89ffcd97..522d2cab.Passes:
/code-reviewat high effort./simplify, with four cleanup agents: reuse (CLEAN), simplification, efficiency (CLEAN) and altitude.Findings and repairs:
_get()/_put()took athreading.Lockon the event loop (/code-review). The wrapped callback took it on the loop thread while worker threads held it for their child callbacks. That stalls the loop, and deadlocks it if a child callback calls a sync method of the filesystem, which waits on the loop._S3LockedCallbackno longer converts labels. The syncget()andput()passstr()of their S3 path, as Act on listed identities in pairing and copy/mv/get (GH-1403) #1421 did._get()/_put()run their transfers through_transfer_pairs(), which works as fsspec's loop for lists of paths and labels each branch with the string of its path, without a lock, as before Type put destinations and document path addressing (GH-1404) #1426. It replaces the_get_pairs()of Act on listed identities in pairing and copy/mv/get (GH-1403) #1421.put, async_put, async_get).S3Pathused its path string (altitude).S3Path("bucket", "a/x?versionId=null"),url(),metadata()andgetxattr()signed and read thenullversion ofa/x, andsetxattr()rejected the file as a version.sign(), whichS3Filedoes not have (its method isurl()).sign(),metadata(),getxattr()andsetxattr()accept anS3Path, andS3Filepasses its bucket, key and version (_s3_path). The docs now name only pickling as the limit.TestS3File::test_path_methods_address_path_as_it_is; all four cases fail at 522d2ca./code-review, altitude).copy()of listed sources andput()raisedwith_key_suffix()'s generic message.s3_copy_pairs()raisesCannot copy to a versioned file.again, and_put_pairs()raisesCannot write to the file with the version specified., the message that the string path gave atopen(). TheRaisesofput()and_put()say so._put_pairs()returns early when no destination is named after a local file.put_file()and the async transaction write parse their destination once.self._invalidate()./code-review):TestS3File.puttest compares the callback's labels exactly (dirincludes the directory'sbucket/up).Deferred, with reasons:
put_file()and the async transaction write, and the async_put()source check and part windowing: these predate this PR, and are filed as Share the upload body of put_file() with the async transaction write, and check put sources once #1427.other_paths()destinations to derive the suffix. As in Act on listed identities in pairing and copy/mv/get (GH-1403) #1421,test_s3_copy_pairsand theputtests would fail if fsspec named destinations differently.put()of only empty directories under a versioned root now raises. This is intended: such a root names an object.stringify_pathguard repeated input_file/cp_file/get_file. Kept deliberately (Act on listed identities in pairing and copy/mv/get (GH-1403) #1421):stringify_pathwould convert anS3Pathif it ever gained__fspath__.Validation:
just lint,just docs lintandjust benchmark testpass.