diff --git a/docs/filesystem.md b/docs/filesystem.md index b5954d306..f3686a022 100644 --- a/docs/filesystem.md +++ b/docs/filesystem.md @@ -647,6 +647,54 @@ The opt-in S3 versioning integration tests create dedicated temporary buckets an check unversioned, enabled, and suspended states. See [Testing](testing.md) for the command and required test permissions. +## Path addressing + +### Keys that look like version paths + +A path string that ends in a version ID query names that version: +`s3://YOUR_S3_BUCKET/a/x?versionId=v1` is version `v1` of the key `a/x`. A key that +itself ends in such a query, such as `a/x?versionId=v1`, cannot be named by a path +string, and there is no escape syntax. An `S3Path` names it by its bucket, key and +version as they are: + +```python +from pyathena.filesystem.s3_path import S3Path + +path = S3Path("YOUR_S3_BUCKET", "a/x?versionId=v1") +fs.info(path) +fs.cat_file(path) +fs.cp_file(path, S3Path("YOUR_S3_BUCKET", "b/x?versionId=v1")) +fs.get_file(path, "local-file") +fs.put_file("local-file", path) +``` + +`info()`, `cat_file()`, `cp_file()`, `get_file()`, `put_file()`, `sign()`, `metadata()`, +`getxattr()` and `setxattr()`, their asynchronous counterparts, `S3File`, `S3Core` and +`S3PathPairing` accept an `S3Path`. `S3Path.of()` parses a path string and returns an +`S3Path` as it is. `S3Path("YOUR_S3_BUCKET", "")` is the bucket path, as +`S3Path("YOUR_S3_BUCKET")` is. + +`find()`, `walk()`, `tree()`, `glob()` and `expand_path()` list such keys by their +buckets and keys, and `rm()`, `chmod()`, `cat()`, `du()`, `copy()`, `mv()` and `get()` +act on the keys that they list in the same way. `put()` writes a local file to the key +named after the file, also when its name ends in such a query. The names that these +methods return are strings, so the name of such a key, passed back to a method as a +path string, names the version. The same holds for the compositions that pass path +strings, such as `fsspec.open()`, `fsspec.open_files()` and `get_mapper()` (`FSMap`). + +A file opened with an `S3Path` of such a key, without a version, has the name of the +key as its `path`. Its `url()`, `metadata()`, `getxattr()` and `setxattr()` address its +bucket, key and version, and a pickled copy of the file reopens its `path`, which names +the version. + +### Bucket paths with a trailing double slash + +`s3://YOUR_S3_BUCKET//` names the key `/` for `cat_file()`, `rm_file()` and a +non-recursive `chmod()`, and the bucket for `info()` and the listings, such as `ls()` +and `find()`, which remove trailing slashes. A recursive `chmod()` of it changes the ACLs +of the objects that `find()` lists, including the key `/`, and not the ACL of the +bucket. A write to it, such as `pipe_file()`, raises `ValueError`. + ## Bucket lifecycle Bucket creation and deletion are infrastructure-level changes and are disabled by diff --git a/pyathena/filesystem/s3.py b/pyathena/filesystem/s3.py index 501dafe00..0889ecc76 100644 --- a/pyathena/filesystem/s3.py +++ b/pyathena/filesystem/s3.py @@ -3818,7 +3818,9 @@ def put( **kwargs: Additional parameters passed to ``put_file()``. Raises: - ValueError: If two files have the same destination, or + ValueError: If two files have the same destination, the + destination of a local file names a version, also when + ``rpath`` names one and the file is named below it, or ``batch_size`` is neither positive, -1, nor None. """ lpath, rpath = self._stringify_paths(lpath), self._stringify_paths(rpath) @@ -3830,14 +3832,15 @@ def put( call_kwargs = self._batch_kwargs(concurrency, kwargs) locked = _S3LockedCallback(callback, threading.Lock()) - def put_pair(pair: tuple[str, str]) -> None: + def put_pair(pair: tuple[str, str | S3Path]) -> None: """Upload a pair with a branch of the callback. Args: pair: The local source and its S3 destination. """ lp, rp = pair - with locked.branched(lp, rp) as child: + # Named after the destination as a string. + with locked.branched(lp, str(rp)) as child: self.put_file(lp, rp, callback=child, **call_kwargs) locked.relative_update(1) @@ -3846,12 +3849,20 @@ def put_pair(pair: tuple[str, str]) -> None: def _put_pairs( self, lpath, rpath, recursive=False, maxdepth=None, **kwargs - ) -> list[tuple[str, str]]: + ) -> list[tuple[str, str | S3Path]]: """Pair the local sources of ``put()`` with their S3 destinations as fsspec does. The files are uploaded in parallel, so no two files may have the same destination; a local directory uploads nothing. + The destination of a local file named after it below ``rpath`` is an + ``S3Path``: ``rpath`` parsed, with the rest of the local name added to + its key as it is (see :meth:`S3Path.with_key_suffix`), so that a file + named, e.g., ``x?versionId=v1`` is written to that key instead of + naming a version. Any other destination, such as ``rpath`` itself, + one of a list of destinations, or that of a local directory, is a + string without the protocol. + Args: lpath: Local source path, glob pattern, or list of them. rpath: S3 destination path, or list of paths when ``lpath`` is a @@ -3866,10 +3877,13 @@ def _put_pairs( with their destinations without the protocol. Raises: - ValueError: If two files have the same destination. + ValueError: If two files have the same destination, or ``rpath`` + names a version and a local file is named below it. """ if isinstance(lpath, list) and isinstance(rpath, list): - pairs = [(lp, self._strip_protocol(rp)) for lp, rp in zip(lpath, rpath, strict=False)] + pairs: list[tuple[str, str | S3Path]] = [ + (lp, self._strip_protocol(rp)) for lp, rp in zip(lpath, rpath, strict=False) + ] else: source_is_str = isinstance(lpath, str) if source_is_str: @@ -3888,7 +3902,24 @@ def _put_pairs( (has_magic(lpath) and len(lpaths) == 1) or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath)) ) - rpaths = other_paths(lpaths, rpath, exists=exists, flatten=not source_is_str) + rpaths: list[str | S3Path] = other_paths( + lpaths, rpath, exists=exists, flatten=not source_is_str + ) + # The files named after their local names below rpath; a local + # directory, which put_file() skips, keeps its string. + named = [ + rp != rpath and not os.path.isdir(lp) for lp, rp in zip(lpaths, rpaths, strict=True) + ] + if isinstance(rpath, str) and any(named): + root = S3Path.parse(rpath) + if root.version_id: + raise ValueError("Cannot write to the file with the version specified.") + # Every destination starts with rpath, which has no trailing + # slash, followed by the rest of the local name. + rpaths = [ + root.with_key_suffix(cast(str, rp)[len(rpath) :]) if typed else rp + for rp, typed in zip(rpaths, named, strict=True) + ] pairs = list(zip(lpaths, rpaths, strict=True)) # put_file() uploads nothing for a local directory. files = [rp for lp, rp in pairs if not os.path.isdir(lp)] @@ -3899,7 +3930,7 @@ def _put_pairs( 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, @@ -3914,7 +3945,8 @@ def put_file( 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" (default) or "create". With "create", the file is written as with ``open()`` in ``xb`` mode: raise @@ -3936,12 +3968,13 @@ def put_file( the method returns without performing any operation. Bucket-only destinations (without key) are also not supported. """ - rpath = stringify_path(rpath) + target: str | S3Path = rpath if isinstance(rpath, S3Path) else stringify_path(rpath) if os.path.isdir(lpath): # No support for directory uploads. return - if not S3Path.parse(rpath).key: + s3_path = S3Path.of(target) + if not s3_path.key: # No support for bucket copy. return @@ -3960,15 +3993,15 @@ def put_file( # The local file is opened first, so that an unreadable one fails # before the remote file is opened. with open(lpath, "rb") as local: - self.open( - rpath, + self._open_path( + target, "xb" if mode == "create" else "wb", block_size=block_size, max_workers=max_workers, s3_additional_kwargs=s3_additional_kwargs, )._write_file_and_close(local, callback) - self.invalidate_cache(rpath) + self._invalidate(s3_path) def get_file( self, @@ -4044,11 +4077,7 @@ def get_file( # The remote file is opened first so that no local file is created # when open() finds no object at the path. with contextlib.ExitStack() as stack: - remote = stack.enter_context( - self._open(rpath, "rb", **kwargs) - if isinstance(rpath, S3Path) - else self.open(rpath, "rb", **kwargs) - ) + remote = stack.enter_context(self._open_path(rpath, "rb", **kwargs)) reader: Any = None if codec is not None: # As fsspec's open() wraps the file, but closed with it. @@ -4095,7 +4124,7 @@ def checksum(self, path: str | os.PathLike[str], **kwargs): return int(info.get("etag").strip('"').split("-")[0], 16) return int(tokenize(info), 16) - def sign(self, path: str | os.PathLike[str], expiration: int = 3600, **kwargs): + def sign(self, path: str | os.PathLike[str] | S3Path, expiration: int = 3600, **kwargs): """Generate a presigned URL for S3 object access. Creates a presigned URL that allows temporary access to an S3 object @@ -4103,7 +4132,8 @@ def sign(self, path: str | os.PathLike[str], expiration: int = 3600, **kwargs): time-limited access to resources. Args: - path: S3 path (s3://bucket/key) to generate URL for. + path: S3 path (s3://bucket/key) to generate URL for, or an + ``S3Path``, whose bucket, key and version are used as they are. expiration: URL expiration time in seconds. Defaults to 3600 (1 hour). **kwargs: Additional parameters including: client_method: S3 operation ('get_object', 'put_object', etc.). @@ -4124,17 +4154,16 @@ def sign(self, path: str | os.PathLike[str], expiration: int = 3600, **kwargs): ... client_method="put_object" ... ) """ - path = stringify_path(path) + s3_path = S3Path.of(path if isinstance(path, S3Path) else stringify_path(path)) client_method = kwargs.pop("client_method", "get_object") - return self.core.generate_presigned_url( - S3Path.parse(path), client_method, expiration, **kwargs - ) + return self.core.generate_presigned_url(s3_path, client_method, 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. Args: - path: S3 path (s3://bucket/key) to get metadata for. + path: S3 path (s3://bucket/key) to get metadata for, or an + ``S3Path``, whose bucket, key and version are used as they are. **kwargs: Additional parameters passed to the HeadObject API. Returns: @@ -4143,18 +4172,20 @@ def metadata(self, path: str | os.PathLike[str], **kwargs) -> S3Metadata: system-defined metadata (content type, encryption settings, etc.) as typed properties. """ - path = stringify_path(path) - s3_path = S3Path.parse(path) + s3_path = S3Path.of(path if isinstance(path, S3Path) else stringify_path(path)) if not s3_path.key: raise ValueError("Cannot get metadata of a bucket.") _logger.debug(f"Head object metadata: {s3_path.uri}") return self.core.head_object(s3_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. 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``, as for :meth:`metadata`. attr_name: The name of the attribute. **kwargs: Additional parameters passed to :meth:`metadata`. @@ -4164,7 +4195,10 @@ def getxattr(self, path: str | os.PathLike[str], attr_name: str, **kwargs) -> st return self.metadata(path, **kwargs).get(attr_name) def setxattr( - self, path: str | os.PathLike[str], copy_kwargs: dict[str, Any] | None = None, **kw_args + self, + path: str | os.PathLike[str] | S3Path, + copy_kwargs: dict[str, Any] | None = None, + **kw_args, ) -> None: """Set the user-defined metadata of the path. @@ -4178,9 +4212,10 @@ def setxattr( ``Expires`` value that botocore cannot parse as a date is not kept. Args: - path: S3 path (s3://bucket/key) to set metadata for. A path with - a version ID is rejected, since copying a version onto the - key would replace the current object with it. + path: S3 path (s3://bucket/key) to set metadata for, or an + ``S3Path``, as for :meth:`metadata`. A path with a version ID + is rejected, since copying a version onto the key would + replace the current object with it. copy_kwargs: Additional parameters to use for the underlying CopyObject API call. They take precedence over the kept system-defined metadata and storage class. Any encryption @@ -4204,8 +4239,7 @@ def setxattr( Raises: ValueError: If the path is a bucket or has a version ID. """ - path = stringify_path(path) - s3_path = S3Path.parse(path) + s3_path = S3Path.of(path if isinstance(path, S3Path) else stringify_path(path)) if not s3_path.key: raise ValueError("Cannot set metadata of a bucket.") if s3_path.version_id: @@ -4213,7 +4247,7 @@ def setxattr( copy_kwargs = copy_kwargs or {} # Looked up with the parameters that authorize the access to the # object as the source of the copy, such as its customer-provided key. - head = self.metadata(path, **self.core.copy_source_params(copy_kwargs)) + head = self.metadata(s3_path, **self.core.copy_source_params(copy_kwargs)) metadata = dict(head) for k, v in kw_args.items(): if v is None: @@ -4221,7 +4255,7 @@ def setxattr( else: metadata[k] = v self.core.replace_object_metadata(s3_path, head, metadata, **copy_kwargs) - self.invalidate_cache(path) + self._invalidate(s3_path) def get_tags(self, path: str | os.PathLike[str]) -> dict[str, str]: """Retrieve the tag key/values for the given path. @@ -4772,6 +4806,30 @@ def _ls_from_cache(self, path: S3Path) -> list[S3Object] | S3Object | None: # so a bucket missing from it is looked up with HeadBucket. return None + def _open_path(self, path: str | os.PathLike[str] | S3Path, mode: str, **kwargs) -> S3File: + """Open a binary file as ``open()`` does, also for an ``S3Path``. + + A path string is opened with ``open()``. An ``S3Path`` is opened by + its bucket, key and version, and a file written in a transaction of + the filesystem joins it, as with ``open()``. + + Args: + path: S3 path (s3://bucket/key), or an ``S3Path``. + mode: A binary mode of ``open()``. + **kwargs: The other arguments of ``open()``, except + ``compression``. + + Returns: + The file. + """ + if not isinstance(path, S3Path): + return cast(S3File, self.open(path, mode, **kwargs)) + autocommit = kwargs.pop("autocommit", not self._intrans) + file = self._open(path, mode, autocommit=autocommit, **kwargs) + if not autocommit and "r" not in mode: + self.transaction.files.append(file) + return file + def _open( self, path: str | S3Path, @@ -5202,6 +5260,11 @@ def __init__( self.append_block = True self._append_size = self.loc = target.appended.get("size", 0) + @property + def _s3_path(self) -> S3Path: + """The bucket, key and version of the object that the file reads or writes.""" + return S3Path(self.bucket, self.key, self.version_id) + def _get_request_kwargs(self, method: str) -> dict[str, Any]: """Select the parameters of the file that an S3 operation accepts. @@ -5809,7 +5872,7 @@ def url(self, expiration: int = 3600, **kwargs) -> str: params = self.fs.core.operation_params( kwargs.get("client_method", "get_object"), self._lookup_kwargs() ) - return cast(str, self.fs.sign(self.path, expiration=expiration, **{**params, **kwargs})) + return cast(str, self.fs.sign(self._s3_path, expiration=expiration, **{**params, **kwargs})) def metadata(self, **kwargs) -> S3Metadata: """Return the metadata of the file. @@ -5827,7 +5890,7 @@ def metadata(self, **kwargs) -> S3Metadata: user-defined metadata and exposes the system-defined metadata as typed properties. """ - return self.fs.metadata(self.path, **{**self._lookup_kwargs(), **kwargs}) + return self.fs.metadata(self._s3_path, **{**self._lookup_kwargs(), **kwargs}) def getxattr(self, xattr_name: str, **kwargs) -> str | None: """Get an attribute from the user-defined metadata of the file. @@ -5843,7 +5906,7 @@ def getxattr(self, xattr_name: str, **kwargs) -> str | None: Returns: The value of the attribute, or None if the attribute is not set. """ - return self.fs.getxattr(self.path, xattr_name, **{**self._lookup_kwargs(), **kwargs}) + return self.fs.getxattr(self._s3_path, xattr_name, **{**self._lookup_kwargs(), **kwargs}) def setxattr(self, copy_kwargs: dict[str, Any] | None = None, **kwargs) -> None: """Set the user-defined metadata of the file. @@ -5875,7 +5938,7 @@ def setxattr(self, copy_kwargs: dict[str, Any] | None = None, **kwargs) -> None: k: v for k, v in lookup_kwargs.items() if not k.startswith("SSECustomer") } self.fs.setxattr( - self.path, + self._s3_path, copy_kwargs={ **destination, **self.fs.core.copy_from_source_params(lookup_kwargs), diff --git a/pyathena/filesystem/s3_async.py b/pyathena/filesystem/s3_async.py index 555c01445..328736f8f 100644 --- a/pyathena/filesystem/s3_async.py +++ b/pyathena/filesystem/s3_async.py @@ -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,7 +981,9 @@ 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( @@ -1009,15 +991,94 @@ async def _put( ) 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( + 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,13 +1862,14 @@ 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: @@ -1814,13 +1877,16 @@ def metadata(self, path: str | os.PathLike[str], **kwargs) -> S3Metadata: """ 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 diff --git a/pyathena/filesystem/s3_path.py b/pyathena/filesystem/s3_path.py index 84249c9e4..8477163bb 100644 --- a/pyathena/filesystem/s3_path.py +++ b/pyathena/filesystem/s3_path.py @@ -177,6 +177,30 @@ def target(self) -> S3Path: """ return self.with_version_id(None) if self.version_id == "null" else self + def with_key_suffix(self, suffix: str) -> S3Path: + """Return the path that a suffix names below this one, with the suffix as it is. + + The suffix, such as ``/x?versionId=null`` taken from a listed key or + a local file name, is appended to the key without being parsed, so + that it names a key that ends in what looks like a version ID query. + A bucket path takes the suffix without its leading slash as its key, + and an empty suffix names this path. + + Args: + suffix: The suffix of the key, such as ``/x``. + + Returns: + The path. + + Raises: + ValueError: If this path has a version, which names an object + and no paths below it. + """ + if self.version_id: + raise ValueError(f"Cannot name a path below the versioned path {self}.") + key = f"{self.key}{suffix}" if self.key else suffix.removeprefix("/") + return S3Path(self.bucket, key) + def with_version_id(self, version_id: str | None) -> S3Path: """Return the path with another version ID. diff --git a/pyathena/filesystem/s3_path_pairing.py b/pyathena/filesystem/s3_path_pairing.py index 52a5bf805..69cfe828b 100644 --- a/pyathena/filesystem/s3_path_pairing.py +++ b/pyathena/filesystem/s3_path_pairing.py @@ -159,8 +159,9 @@ def s3_copy_pairs( The destination of an ``S3Path`` source, when ``path2`` is a string, is an ``S3Path`` too: ``path2`` parsed, with the suffix that - :meth:`copy_pairs` appends to it added to its key as it is, so that a - key such as ``a/x?versionId=null`` is copied to the key + :meth:`copy_pairs` appends to it added to its key as it is (see + :meth:`~pyathena.filesystem.s3_path.S3Path.with_key_suffix`), so that + a key such as ``a/x?versionId=null`` is copied to the key ``b/x?versionId=null`` instead of being parsed as a version. The other destinations are strings, as :meth:`copy_pairs` returns them. @@ -185,15 +186,10 @@ def s3_copy_pairs( root = S3Path.parse(root_name) if root.version_id: raise ValueError("Cannot copy to a versioned file.") - typed: list[tuple[str | S3Path, str | S3Path]] = [] - for p1, p2 in pairs: - if isinstance(p1, S3Path): - suffix = p2[len(root_name) :] - key = f"{root.key}{suffix}" if root.key else suffix.removeprefix("/") - typed.append((p1, S3Path(root.bucket, key))) - else: - typed.append((p1, p2)) - return typed + return [ + (p1, root.with_key_suffix(p2[len(root_name) :]) if isinstance(p1, S3Path) else p2) + for p1, p2 in pairs + ] def conflict_candidates( self, diff --git a/tests/pyathena/filesystem/test_s3.py b/tests/pyathena/filesystem/test_s3.py index c9a6d3ecd..9d2f124cb 100644 --- a/tests/pyathena/filesystem/test_s3.py +++ b/tests/pyathena/filesystem/test_s3.py @@ -1369,6 +1369,91 @@ def test_expansion_acts_on_an_object_once(self, call, sent): call(fs) assert [t for t in s3_request_targets(requests) if t[0] != "head_object"] == sent + @pytest.mark.parametrize( + ("source", "kwargs", "sent", "labels"), + [ + pytest.param( + "x?versionId=v1", + {}, + [("put_object", "up/x?versionId=v1", None)], + ["bucket/up/x?versionId=v1"], + id="file", + ), + pytest.param( + "", + {"recursive": True}, + [("put_object", "up/x?versionId=v1", None)], + # The directory itself is paired with the destination root. + ["bucket/up", "bucket/up/x?versionId=v1"], + id="dir", + ), + pytest.param( + "x?versionId=v1", + {"mode": "create"}, + [ + ("head_object", "up/x?versionId=v1", None), + ("put_object", "up/x?versionId=v1", "*"), + ], + ["bucket/up/x?versionId=v1"], + id="create", + ), + ], + ) + def test_put_names_destinations_after_local_files(self, tmp_path, source, kwargs, sent, labels): + # GH-1404: put() writes a local file to the key named after it as it + # is, also when its name ends in what looks like a version ID query, + # and names the branch of the callback after the key as a string. + fs = S3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + store, requests = serve_s3_keys(fs, set()) + (tmp_path / "x?versionId=v1").write_bytes(b"aa") + callback = BranchRecordingCallback() + fs.put(f"{tmp_path}/{source}", "s3://bucket/up/", callback=callback, **kwargs) + assert store == {"up/x?versionId=v1"} + assert [ + (name, request.get("Key"), request.get("IfNoneMatch")) + for name, request in requests + if name != "list_objects_v2" + ] == sent + assert sorted(callback.destinations) == labels + + @pytest.mark.parametrize("with_file", [False, True]) + def test_put_below_versioned_root(self, tmp_path, with_file): + # GH-1404: a file named below a root that names a version raises + # before anything is uploaded; local directories, which upload + # nothing, do not. + fs = S3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + store, requests = serve_s3_keys(fs, set()) + (tmp_path / "src" / "empty").mkdir(parents=True) + if with_file: + (tmp_path / "src" / "x").write_bytes(b"aa") + put = lambda: fs.put( # noqa: E731 + f"{tmp_path}/src/", "s3://bucket/up?versionId=v1/", recursive=True + ) + if with_file: + with pytest.raises(ValueError, match="version"): + put() + else: + put() + assert store == set() + assert [name for name, _ in requests if name != "list_objects_v2"] == [] + + def test_put_in_transaction_names_destinations_after_local_files(self, tmp_path): + # GH-1404: the file of a destination named after a local file joins + # the transaction, as one opened with open() does. + fs = S3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + store, _ = serve_s3_keys(fs, set()) + (tmp_path / "x?versionId=v1").write_bytes(b"aa") + with fs.transaction: + fs.put(str(tmp_path / "x?versionId=v1"), "s3://bucket/up/") + assert store == set() + assert store == {"up/x?versionId=v1"} + def test_expand_path_expands_below_listed_matches(self): # GH-1402: a recursive glob expands below each match by its key prefix. fs = S3FileSystem( @@ -3214,7 +3299,8 @@ def test_put_directories_with_one_destination(self, tmp_path): "s3://bucket/x/", recursive=True, ) - files = [c.args[1] for c in fs.put_file.call_args_list if not os.path.isdir(c.args[0])] + # The destinations named after the local files are S3Path objects. + files = [str(c.args[1]) for c in fs.put_file.call_args_list if not os.path.isdir(c.args[0])] assert sorted(files) == ["bucket/x/f1", "bucket/x/f2"] def test_copy_skipped_directory_does_not_conflict(self): @@ -8496,6 +8582,59 @@ def test_pandas_write_csv(self, line_count): class TestS3File: + def test_append_to_path_as_it_is(self): + # GH-1404: a file opened in append mode with an S3Path looks up, + # reads and writes the key as it is. + fs = S3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + _, requests = serve_s3_keys(fs, {"a/x", "a/x?versionId=null"}) + with S3File(fs, S3Path("bucket", "a/x?versionId=null"), "ab") as f: + f.write(b"bb") + assert s3_request_targets(requests) == [ + ("get_object", "a/x?versionId=null", None), + ("head_object", "a/x?versionId=null", None), + ("put_object", "a/x?versionId=null", None), + ] + + @pytest.mark.parametrize( + ("call", "sent"), + [ + pytest.param( + lambda f: f.url(), + [("generate_presigned_url", S3Path("bucket", "a/x?versionId=null"))], + id="url", + ), + pytest.param( + lambda f: f.metadata(), [("head_object", "a/x?versionId=null")], id="metadata" + ), + pytest.param( + lambda f: f.getxattr("m"), [("head_object", "a/x?versionId=null")], id="getxattr" + ), + pytest.param( + lambda f: f.setxattr(n="2"), + [("head_object", "a/x?versionId=null"), ("copy_object", "a/x?versionId=null")], + id="setxattr", + ), + ], + ) + def test_path_methods_address_path_as_it_is(self, call, sent): + # GH-1404: the methods of a file opened with an S3Path address its + # bucket, key and version, not its path string, which would name the + # null version of a/x. + fs = S3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + _, requests = serve_s3_keys(fs, {"a/x", "a/x?versionId=null"}) + with S3File(fs, S3Path("bucket", "a/x?versionId=null"), "rb") as f: + del requests[:] + call(f) + assert [ + (name, request["args"][0] if "args" in request else request.get("Key")) + for name, request in requests + if request.get("VersionId") is None and name != "list_objects_v2" + ] == sent + @pytest.mark.parametrize("mode", ["wb", "ab"]) def test_repeated_creation_interrupt(self, mode): # GH-1077: an interrupt of the write's wait for the creation of its diff --git a/tests/pyathena/filesystem/test_s3_async.py b/tests/pyathena/filesystem/test_s3_async.py index eb0b020d6..1cdb8d889 100644 --- a/tests/pyathena/filesystem/test_s3_async.py +++ b/tests/pyathena/filesystem/test_s3_async.py @@ -797,6 +797,169 @@ async def test_get_downloads_listed_keys(self, tmp_path): ] assert sorted(callback.sources) == ["bucket/a", "bucket/a/x", "bucket/a/x?versionId=null"] + @pytest.mark.parametrize( + ("source", "kwargs", "sent"), + [ + pytest.param( + "x?versionId=v1", {}, [("put_object", "up/x?versionId=v1", None)], id="file" + ), + pytest.param( + "", {"recursive": True}, [("put_object", "up/x?versionId=v1", None)], id="dir" + ), + pytest.param( + "x?versionId=v1", + {"mode": "create"}, + [ + ("head_object", "up/x?versionId=v1", None), + ("put_object", "up/x?versionId=v1", "*"), + ], + id="create", + ), + ], + ) + @pytest.mark.asyncio + async def test_put_names_destinations_after_local_files(self, tmp_path, source, kwargs, sent): + # GH-1404: _put() writes the keys named after local files as put() + # does, with the branches of the callback named after them as strings. + fs = AioS3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + store, requests = serve_s3_keys(fs._sync_fs, set()) + (tmp_path / "x?versionId=v1").write_bytes(b"aa") + callback = BranchRecordingCallback() + await await_bounded( + fs._put(f"{tmp_path}/{source}", "s3://bucket/up/", callback=callback, **kwargs) + ) + assert store == {"up/x?versionId=v1"} + assert [ + (name, request.get("Key"), request.get("IfNoneMatch")) + for name, request in requests + if name != "list_objects_v2" + ] == sent + assert callback.destinations == ["bucket/up/x?versionId=v1"] + + def test_put_in_transaction_names_destinations_after_local_files(self, tmp_path): + # GH-1404: in a transaction, the file of a destination named after a + # local file joins the transaction of this filesystem. + fs = AioS3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + store, _ = serve_s3_keys(fs._sync_fs, set()) + (tmp_path / "x?versionId=v1").write_bytes(b"aa") + with fs.transaction: + fs.put(str(tmp_path / "x?versionId=v1"), "s3://bucket/up/") + assert store == set() + assert store == {"up/x?versionId=v1"} + + @pytest.mark.asyncio + async def test_transfers_run_through_branch_coro(self, tmp_path): + # GH-1404: as in fsspec, each download and upload runs through the + # callback's branch_coro(), with the paths named as strings. + fs = AioS3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + serve_s3_keys(fs._sync_fs, {"a/x?versionId=null"}) + (tmp_path / "x?versionId=v1").write_bytes(b"aa") + finished = [] + + class Recording(Callback): + def branch_coro(self, fn): + run = super().branch_coro(fn) + + async def recorded(path1, path2, **kwargs): + result = await run(path1, path2, **kwargs) + finished.append((path1, path2)) + return result + + return recorded + + await await_bounded( + fs._get("s3://bucket/a/*", str(tmp_path / "out") + "/", callback=Recording()) + ) + await await_bounded( + fs._put(str(tmp_path / "x?versionId=v1"), "s3://bucket/up/", callback=Recording()) + ) + assert finished == [ + ("bucket/a/x?versionId=null", str(tmp_path / "out" / "x?versionId=null")), + (str(tmp_path / "x?versionId=v1"), "bucket/up/x?versionId=v1"), + ] + + @pytest.mark.asyncio + async def test_transfers_are_wrapped_before_they_run(self, tmp_path): + # GH-1404: as in fsspec, the callback wraps every transfer before any + # runs, also when batch_size lets one run at a time. + fs = AioS3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + store, _ = serve_s3_keys(fs._sync_fs, set()) + for name in ("x", "y"): + (tmp_path / name).write_bytes(b"aa") + wrapped = asyncio.Event() + + class AllWrapped(Callback): + count = 0 + + def branch_coro(self, fn): + run = super().branch_coro(fn) + self.count += 1 + if self.count == 2: + wrapped.set() + + async def wait_then_run(path1, path2, **kwargs): + await wrapped.wait() + return await run(path1, path2, **kwargs) + + return wait_then_run + + await await_bounded( + fs._put( + [str(tmp_path / "x"), str(tmp_path / "y")], + ["s3://bucket/up/x", "s3://bucket/up/y"], + callback=AllWrapped(), + batch_size=1, + ) + ) + assert store == {"up/x", "up/y"} + + @pytest.mark.asyncio + async def test_cancelled_put_starts_no_waiting_transfer(self, tmp_path): + # GH-1404: a transfer whose branch_coro() wrapper waits before it + # starts belongs to the batch, so a cancellation of _put() stops it + # and it uploads nothing afterwards. + fs = AioS3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + store, _ = serve_s3_keys(fs._sync_fs, set()) + (tmp_path / "x").write_bytes(b"aa") + waiting, release = asyncio.Event(), asyncio.Event() + stopped = [] + + class Waiting(Callback): + def branch_coro(self, fn): + run = super().branch_coro(fn) + + async def wait_then_run(path1, path2, **kwargs): + waiting.set() + try: + await release.wait() + except asyncio.CancelledError: + stopped.append(path2) + raise + return await run(path1, path2, **kwargs) + + return wait_then_run + + task = asyncio.ensure_future( + fs._put(str(tmp_path / "x"), "s3://bucket/up/", callback=Waiting()) + ) + await await_bounded(waiting.wait()) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await await_bounded(task) + # The waiting wrapper was cancelled, and waited for, before _put() raised. + assert stopped == ["bucket/up/x"] + assert store == set() + @pytest.mark.asyncio async def test_du_cancellation_sends_no_further_lookup(self): # GH-1402: as fsspec's _du(), the lookups of the found entries are diff --git a/tests/pyathena/filesystem/test_s3_path.py b/tests/pyathena/filesystem/test_s3_path.py index c72749c67..3cad9d81e 100644 --- a/tests/pyathena/filesystem/test_s3_path.py +++ b/tests/pyathena/filesystem/test_s3_path.py @@ -62,6 +62,22 @@ def test_of(self): assert S3Path.of(listed) is listed assert S3Path.of("s3://bucket/a/x?versionId=null") == S3Path("bucket", "a/x", "null") + @pytest.mark.parametrize( + ("path", "suffix", "expected"), + [ + (S3Path("bucket", "up"), "/x?versionId=v1", S3Path("bucket", "up/x?versionId=v1")), + (S3Path("bucket"), "/x?versionId=v1", S3Path("bucket", "x?versionId=v1")), + (S3Path("bucket", "up"), "", S3Path("bucket", "up")), + ], + ) + def test_with_key_suffix(self, path, suffix, expected): + # GH-1404: the suffix is added to the key as it is, never parsed. + assert path.with_key_suffix(suffix) == expected + + def test_with_key_suffix_of_version(self): + with pytest.raises(ValueError, match="versioned"): + S3Path("bucket", "up", "v1").with_key_suffix("/x") + def test_empty_key_is_the_bucket(self): # GH-1401: an empty key names the bucket, which the path prints as. assert S3Path("bucket", "") == S3Path("bucket") diff --git a/tests/pyathena/util.py b/tests/pyathena/util.py index 143912293..41dc237a4 100644 --- a/tests/pyathena/util.py +++ b/tests/pyathena/util.py @@ -1815,14 +1815,16 @@ def __fspath__(self): class BranchRecordingCallback(Callback): - """A progress callback that records the source paths of its branches.""" + """A progress callback that records the source and destination paths of its branches.""" def __init__(self): super().__init__() self.sources = [] + self.destinations = [] def branched(self, path_1, path_2, **kwargs): self.sources.append(path_1) + self.destinations.append(path_2) return super().branched(path_1, path_2, **kwargs)