Skip to content
12 changes: 12 additions & 0 deletions docs/fsspec.rst
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,18 @@ Only folder IDs are cached between calls. Both ``ls()`` and ``find()``
build their results in memory, so larger listings use more memory during
the call.

A recursive ``get()`` or ``copy()``, or one given a glob, downloads or
copies each file by the Drive ID its listing returned, without looking
the file up again. The IDs take about 160 bytes per file and are dropped
when the call returns. If another client trashes a listed file or puts a
new file at its path during the call, the call still reads the listed
file, because Drive serves a trashed file by its ID. A listed file deleted
for good makes ``get()`` raise ``FileNotFoundError``. A recursive
``copy()`` skips it, because fsspec ignores missing files there unless
``on_error="raise"`` is passed. If the listing finds an item with more
than one parent folder, which older Drive files can have, the call looks
each file up by its path instead.

Trashed items
-------------

Expand Down
131 changes: 126 additions & 5 deletions pydrive2/fs/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,77 @@ def _select_item_id(path, ids):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), path)


class _ListedTransfer:
"""Run one fsspec get() or copy() by the IDs that its own listings return.

Callbacks still get the filesystem, so their calls look paths up again.
"""

def __init__(self, fs, destination=None):
self._fs = fs
self._destination = destination
self._ids: dict[str, tuple[str, bool]] | None = {}
self._unreachable: set[str] = set()

def __getattr__(self, name):
return getattr(self._fs, name)

# fsspec expands paths with these, and they must call find() on this object.
def expand_path(self, *args, **kwargs):
return AbstractFileSystem.expand_path(self, *args, **kwargs)
Comment thread
shcheklein marked this conversation as resolved.
Resolved

def glob(self, *args, **kwargs):
return AbstractFileSystem.glob(self, *args, **kwargs)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ID map retains entries the glob rejected. I tested get(["root/*.csv", "root/manual.txt"], local_dir). The directory listing included manual.txt with ID OLD. By transfer time that file had been deleted and ID NEW existed at the same path. The base commit resolved the explicit path to NEW and completed both downloads. This revision tried OLD and raised FileNotFoundError. A selective glob also kept all 5,000 ID entries alive during a one-file download in my test. Please keep only the IDs selected by each glob when merging its results into the transfer. Falling back to ordinary expansion for mixed source lists would also fix the wrong-ID case.


def find(
self, path, maxdepth=None, withdirs=False, detail=False, **kwargs
):
return self._fs._find(path, maxdepth, withdirs, detail, self)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This entry point skips the boolean-depth validation in public find(). With get("root", target, recursive=True, maxdepth=True), the base commit raises TypeError before contacting Drive. This revision treats True as depth 1 and downloads the top-level file, silently omitting deeper entries. Move the existing guard into _find() so the public and optimized paths share it, and cover the recursive transfer entry point.


def listed(self, parent, path, item):
"""Keep the lowest ID at a path, as a lookup of the path would."""
if self._ids is None:
return
if item.ambiguous:
# A listing of several folders places such an item under only one.
self._ids = None
return
if parent in self._unreachable or "/" in item.name:
# A lookup splits paths at slashes and cannot reach it.
if item.is_folder:
self._unreachable.add(path)
return
known = self._ids.get(path)
if known is None or item.id < known[0]:
self._ids[path] = (item.id, item.is_folder)

def _known(self, path):
return self._ids.get(path) if self._ids else None

def isdir(self, path):
# fsspec places a copy by the destination's current type.
known = None if path == self._destination else self._known(path)
return self._fs.isdir(path) if known is None else known[1]

def get_file(self, rpath, lpath, callback=None, block_size=None, **kwargs):
listed = self._known(rpath)
return self._fs._get_file(rpath, lpath, listed, callback, block_size)

def cp_file(self, path1, path2, **kwargs):
return self._fs._cp_file(path1, path2, self._known(path1))


# A subclass that changes one of these keeps fsspec's own transfer.
_TRANSFER_HOOKS = (
"expand_path",
"glob",
"find",
"isdir",
"get_file",
"cp_file",
)


class GDriveAuthError(AuthError):
pass

Expand Down Expand Up @@ -883,9 +954,11 @@ def _get_item_id(self, path, create=False):
match, _ = self._lookup_path(base)
return _select_item_id(path, match.ids)

def _lookup_item(self, path):
def _lookup_item(self, path, listed=None):
"""Return the ID at a path and whether it is a folder."""
_, base = self._split_mounted_path(path)
if listed is not None:
return listed
match, _ = self._lookup_path(base)
item_id = _select_item_id(path, match.ids)
if base or self.root in _ROOT_ALIASES:
Expand Down Expand Up @@ -1155,6 +1228,9 @@ def find(
"find() takes maxdepth as its second argument. "
f"Pass detail by keyword: find(path, detail={maxdepth})."
)
return self._find(path, maxdepth, withdirs, detail)

def _find(self, path, maxdepth, withdirs, detail, transfer=None):
root, base = self._split_mounted_path(path)
if maxdepth is not None and maxdepth < 1:
raise ValueError("maxdepth must be at least 1")
Expand Down Expand Up @@ -1198,11 +1274,13 @@ def find(
check_empty_root = False
preferred = _preferred_ids(children, withdirs) if detail else {}
for item in _drain(children):
name = posixpath.join(parent, item.name)
if transfer is not None:
transfer.listed(parent, name, item)
if item.is_folder and not withdirs:
continue
if preferred and item.id != preferred.get(item.name, item.id):
continue
name = posixpath.join(parent, item.name)
contents.append(item.entry(name, detail))

if check_empty_root:
Expand All @@ -1217,6 +1295,25 @@ def find(
contents.sort()
return contents

def _transfer(self, destination=None):
"""Return the object that fsspec's get() or copy() should run on."""
cls = type(self)
for name in _TRANSFER_HOOKS:
if getattr(cls, name) is not getattr(GDriveFileSystem, name):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checking these six class methods still misses behavior that fsspec previously honored. I tested a subclass whose info() identifies .pkg paths as directories. fs.isdir(path) returns True and the base commit skips the package in a nonrecursive glob. The optimized get() downloads it. I also verified that assigning a get_file wrapper on a filesystem instance works on the base commit and is silently bypassed here, even with paired path lists. A simpler compatibility rule would use ordinary fsspec dispatch for subclasses and for instances with customized transfer hooks.

return self
return _ListedTransfer(self, destination)

@wraps(AbstractFileSystem.get)
def get(self, *args, **kwargs):
# Each listed file is downloaded by its listed ID, without a lookup.
return AbstractFileSystem.get(self._transfer(), *args, **kwargs)

@wraps(AbstractFileSystem.copy)
def copy(self, path1, path2, *args, **kwargs):
# Each listed file is copied by its listed ID, without a lookup.
transfer = self._transfer(destination=path2)
return AbstractFileSystem.copy(transfer, path1, path2, *args, **kwargs)

def upload_fobj(self, stream, rpath, callback=None, **kwargs):
parent, name = self._split_file_path(rpath)
parent_id = self._get_item_id(parent, create=True)
Expand Down Expand Up @@ -1249,16 +1346,37 @@ def send(new_id):

def cp_file(self, lpath, rpath, **kwargs):
"""Ask Drive to copy the file directly into the destination folder."""
self._cp_file(lpath, rpath)

def _cp_file(self, lpath, rpath, listed=None):
self._split_mounted_path(rpath)
source_id, is_folder = self._lookup_item(lpath)
source_id, is_folder = self._lookup_item(lpath, listed)
if is_folder:
self.makedirs(rpath, exist_ok=True)
return
parent, name = self._split_file_path(rpath)
parent_id = self._get_item_id(parent, create=True)
self._gdrive_copy_file(source_id, parent_id, name)
try:
self._gdrive_copy_file(source_id, parent_id, name)
except ApiRequestError as exc:
# A missing destination folder is also a 404 on the copy.
if _is_not_found(exc) and not self._gdrive_exists(source_id):
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), lpath
) from exc
raise
self._dirs.file_added(parent_id, name)

def _gdrive_exists(self, item_id):
item = self.client.CreateFile({"id": item_id})
try:
_gdrive_retry_repeatable(item.FetchMetadata)(fields="id")
except ApiRequestError as exc:
if _is_not_found(exc):
return False
raise
return True

def _gdrive_copy_file(self, source_id, parent_id, name):
source = self.client.CreateFile({"id": source_id})
self._gdrive_create(
Expand Down Expand Up @@ -1348,8 +1466,11 @@ def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs):
)

def get_file(self, rpath, lpath, callback=None, block_size=None, **kwargs):
return self._get_file(rpath, lpath, None, callback, block_size)

def _get_file(self, rpath, lpath, listed, callback, block_size):
with _translate_not_found(rpath):
item_id, is_folder = self._lookup_item(rpath)
item_id, is_folder = self._lookup_item(rpath, listed)
if is_folder:
os.makedirs(lpath, exist_ok=True)
return None
Expand Down
169 changes: 169 additions & 0 deletions pydrive2/test/test_fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,175 @@ def test_recursive_get_downloads_a_folder_addressed_by_its_id(
assert (target / "a.txt").read_bytes() == b"a"


def add_item(drive, name, parent, content=None):
"""Create a file with this content, or a folder, as another client can."""
metadata = {"name": name, "parents": [parent]}
if content is None:
metadata["mimeType"] = FOLDER_MIME_TYPE
item = drive.CreateFile(metadata)
if content is not None:
item.SetContentString(content)
pydrive_retry(item.Upload)
return item["id"]


@pytest.fixture(scope="module")
def listed_tree(fs_factory, base_remote_dir):
"""A folder with a file, a subfolder and two files of one name."""
fs, base_item = fs_factory()
name = uuid.uuid4().hex
folder = add_item(fs.client, name, base_item["id"])
add_item(fs.client, "a.txt", folder, "a")
add_item(fs.client, "b.txt", add_item(fs.client, "nested", folder), "b")
add_item(fs.client, "same.txt", folder, "first")
add_item(fs.client, "same.txt", folder, "second")
return f"{base_remote_dir}/{name}"


@pytest.fixture
def answered_requests(service_auth, monkeypatch):
"""The method and URL of every request of this thread that Drive did.

A request that Drive refused, for example with a rate limit, and that
the filesystem then repeated, counts once.
"""
http = service_auth.Get_Http_Object()
send = http.request
answered = []

def request(uri, method="GET", **kwargs):
response, content = send(uri, method, **kwargs)
if response.status < 400:
answered.append((method, uri))
return response, content

monkeypatch.setattr(http, "request", request)
monkeypatch.setattr(service_auth.thread_local, "http", http, raising=False)
return answered


def downloads(requests):
return [
uri
for _, uri in requests
if dict(parse_qsl(urlsplit(uri).query)).get("alt") == "media"
]


def test_recursive_get_after_making_a_tree_sends_only_its_listing_and_downloads(
fs_factory, listed_tree, tmp_path, answered_requests
):
target = tmp_path / "target"
lister, _ = fs_factory()
lister.find(listed_tree, withdirs=True)
listing = len(answered_requests)
answered_requests.clear()

getter, _ = fs_factory()
getter.get(listed_tree, str(target), recursive=True)

assert len(downloads(answered_requests)) == 3
assert len(answered_requests) == listing + 3
assert (target / "a.txt").read_bytes() == b"a"
assert (target / "nested" / "b.txt").read_bytes() == b"b"
same = getter.cat_file(listed_tree + "/same.txt")
assert (target / "same.txt").read_bytes() == same


def test_recursive_copy_after_making_a_tree_searches_for_no_file_name(
fs, listed_tree, answered_requests
):
target = listed_tree + "-copy"

fs.copy(listed_tree, target, recursive=True)

queries = [
dict(parse_qsl(urlsplit(uri).query)).get("q", "")
for _, uri in answered_requests
]
names = ("'a.txt'", "'b.txt'", "'same.txt'")
assert [q for q in queries if any(name in q for name in names)] == []
paths = [urlsplit(uri).path for _, uri in answered_requests]
assert len([path for path in paths if path.endswith("/copy")]) == 3
assert fs.cat_file(target + "/a.txt") == b"a"
assert fs.cat_file(target + "/nested/b.txt") == b"b"
same = fs.cat_file(listed_tree + "/same.txt")
assert fs.cat_file(target + "/same.txt") == same


def test_get_of_a_glob_after_making_a_tree_sends_only_its_listing_and_downloads(
fs_factory, listed_tree, tmp_path, answered_requests
):
target = tmp_path / "target"
lister, _ = fs_factory()
lister.glob(listed_tree + "/*.txt")
listing = len(answered_requests)
answered_requests.clear()

getter, _ = fs_factory()
getter.get(listed_tree + "/*.txt", str(target))

assert len(downloads(answered_requests)) == 2
assert len(answered_requests) == listing + 2
assert (target / "a.txt").read_bytes() == b"a"
same = getter.cat_file(listed_tree + "/same.txt")
assert (target / "same.txt").read_bytes() == same


def test_recursive_copy_after_making_names_with_slashes_copies_what_a_lookup_finds(
fs_factory, base_remote_dir
):
fs, base_item = fs_factory()
name = uuid.uuid4().hex
folder = add_item(fs.client, name, base_item["id"])
add_item(fs.client, "a.txt", folder, "a")
add_item(fs.client, "../escaped.txt", folder, "escaped")
add_item(fs.client, "c.txt", add_item(fs.client, "x/y", folder), "c")
source = f"{base_remote_dir}/{name}"
target = source + "-copy"

fs.copy(source, target, recursive=True)

assert fs.find(target) == [target + "/a.txt"]


class RemoveBeforeTransfer(fsspec.Callback):
"""Remove a file through another filesystem just before its transfer."""

def __init__(self, path, other):
super().__init__()
self.path = path
self.other = other

def branched(self, path_1, path_2, **kwargs):
if path_1 == self.path:
self.other.rm_file(path_1)
return fsspec.Callback()


def test_recursive_get_after_another_client_deletes_a_listed_file_raises(
fs_factory, base_remote_dir, tmp_path
):
fs, base_item = fs_factory()
name = uuid.uuid4().hex
add_item(
fs.client, "a.txt", add_item(fs.client, name, base_item["id"]), "a"
)
source = f"{base_remote_dir}/{name}"
other = GDriveFileSystem(
base_remote_dir,
fs.client.auth,
trash_only=False,
skip_instance_cache=True,
)
removal = RemoveBeforeTransfer(source + "/a.txt", other)

with pytest.raises(FileNotFoundError):
fs.get(
source, str(tmp_path / "target"), recursive=True, callback=removal
)


def test_get_file_callback(fs, tmpdir, remote_dir):
src_file = tmpdir / "a.txt"
dest_file = tmpdir / "b.txt"
Expand Down
Loading
Loading