diff --git a/docs/fsspec.rst b/docs/fsspec.rst index f2886084..f4838ea8 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -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()`` of one path, or one given one 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 ------------- diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 57c3cbbc..a72e44f1 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -228,6 +228,76 @@ 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): + paths = AbstractFileSystem.expand_path(self, *args, **kwargs) + if self._ids: + # Only the paths that fsspec will transfer keep their listed IDs. + self._ids = {p: self._ids[p] for p in paths if p in self._ids} + return paths + + def glob(self, *args, **kwargs): + return AbstractFileSystem.glob(self, *args, **kwargs) + + def find( + self, path, maxdepth=None, withdirs=False, detail=False, **kwargs + ): + return self._fs._find(path, maxdepth, withdirs, detail, self) + + 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 filesystem that sets one of these on itself keeps fsspec's own transfer. +_TRANSFER_HOOKS = frozenset( + ("expand_path", "glob", "find", "isdir", "info", "get_file", "cp_file") +) + + class GDriveAuthError(AuthError): pass @@ -883,9 +953,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: @@ -1149,6 +1221,9 @@ def _walk_folders(self, start, start_ids, generation, maxdepth, fields): def find( self, path, maxdepth=None, withdirs=False, detail=False, **kwargs ): + return self._find(path, maxdepth, withdirs, detail) + + def _find(self, path, maxdepth, withdirs, detail, transfer=None): # PyDrive2 1.x took detail as the second argument, and True is 1. if isinstance(maxdepth, bool): raise TypeError( @@ -1198,11 +1273,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: @@ -1217,6 +1294,29 @@ def find( contents.sort() return contents + def _transfer(self, source, destination=None): + """Return the object that fsspec's get() or copy() should run on.""" + # Listed IDs need PyDrive2's own methods and one source path or glob. + if ( + type(self) is GDriveFileSystem + and isinstance(source, str) + and _TRANSFER_HOOKS.isdisjoint(vars(self)) + ): + return _ListedTransfer(self, destination) + return self + + @wraps(AbstractFileSystem.get) + def get(self, rpath, *args, **kwargs): + # Each listed file is downloaded by its listed ID, without a lookup. + transfer = self._transfer(rpath) + return AbstractFileSystem.get(transfer, rpath, *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(path1, 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) @@ -1249,16 +1349,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( @@ -1348,8 +1469,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 diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index a79ea3b9..4df17dda 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -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" diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 71c9d786..6025ce2e 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -613,6 +613,17 @@ def test_find_with_a_depth_that_is_not_a_positive_number_raises_before_listing( assert requests == [] +def test_recursive_get_with_a_boolean_depth_raises_before_listing( + mock_drive, tmp_path +): + drive, requests = mock_drive() + with pytest.raises(TypeError, match="detail=True"): + filesystem(drive).get( + "root", str(tmp_path / "out"), recursive=True, maxdepth=True + ) + assert requests == [] + + @pytest.mark.parametrize("bare", [True, False]) def test_find_missing_path_uses_one_lookup(mock_drive, bare): drive, requests = mock_drive( @@ -3016,18 +3027,263 @@ def send(request): assert (progress.size, progress.value) == (size, size) -def test_recursive_get_makes_one_lookup_and_one_download_per_file( +def test_recursive_get_makes_one_download_per_file_and_no_lookup( mock_drive, tmp_path ): drive, requests = mock_drive( listing(folder("source", "S")), listing(TEXT_FILE), - listing(TEXT_FILE), DOWNLOAD, ) filesystem(drive).get("root/source", str(tmp_path / "out"), recursive=True) assert (tmp_path / "out" / "a.txt").read_bytes() == b"data" - assert len(requests) == 4 + assert len(requests) == 3 + + +def test_recursive_get_after_listing_a_name_with_a_slash_looks_it_up( + mock_drive, tmp_path +): + slashed = dict(TEXT_FILE, name="a/b.txt", id="E") + drive, requests = mock_drive( + listing(folder("source", "S")), + listing(slashed), + listing(), + ) + with pytest.raises(FileNotFoundError): + filesystem(drive).get( + "root/source", str(tmp_path / "out"), recursive=True + ) + assert "name='a'" in query(requests[-1])["q"][0] + + +def test_cp_file_after_the_source_is_deleted_raises_file_not_found(mock_drive): + drive, requests = mock_drive( + listing(TEXT_FILE), + error_response(404, "notFound"), + error_response(404, "notFound"), + ) + with pytest.raises(FileNotFoundError): + filesystem(drive).cp_file("root/a.txt", "root/b.txt") + copy, check = (urlsplit(uri).path for uri, *_ in requests[-2:]) + assert (copy, check) == ("/drive/v3/files/A/copy", "/drive/v3/files/A") + + +def test_cp_file_after_the_destination_folder_is_deleted_raises_drive_error( + mock_drive, +): + drive, requests = mock_drive( + listing(TEXT_FILE), + error_response(404, "notFound"), + response({"id": "A"}), + ) + with pytest.raises(ApiRequestError) as error: + filesystem(drive).cp_file("root/a.txt", "root/b.txt") + assert not isinstance(error.value, FileNotFoundError) + assert error.value.error["code"] == 404 + assert urlsplit(requests[-1][0]).path == "/drive/v3/files/A" + + +def test_recursive_copy_after_a_listed_file_is_deleted_copies_the_rest( + mock_drive, +): + second = dict(TEXT_FILE, name="b.txt", id="B") + drive, requests = mock_drive( + listing(folder("source", "S")), + listing(TEXT_FILE, second), + response({"mimeType": FOLDER_MIME_TYPE}), + error_response(404, "notFound"), + error_response(404, "notFound"), + response({"id": "copy"}), + ) + filesystem(drive).copy("root/source/", "root", recursive=True) + paths = [urlsplit(uri).path for uri, *_ in requests[-3:]] + assert paths == [ + "/drive/v3/files/A/copy", + "/drive/v3/files/A", + "/drive/v3/files/B/copy", + ] + + +class ListAndGetBeforeTransfer(Callback): + """List the folder and download one file through the filesystem first.""" + + def __init__(self, fs, path, source, target): + super().__init__() + self.fs = fs + self.path = path + self.source = source + self.target = target + + def branched(self, path_1, path_2, **kwargs): + if path_1 == self.path: + self.fs.find(self.source) + self.fs.get_file(self.path, self.target) + return Callback() + + +def test_recursive_get_after_a_callback_lists_a_replaced_file_keeps_the_listed_id( + mock_drive, tmp_path +): + listed = dict(TEXT_FILE, id="Z") + replaced = dict(TEXT_FILE, id="B") + drive, requests = mock_drive( + listing(folder("source", "S")), + listing(listed), + listing(replaced), + listing(replaced), + ({"status": "200"}, b"new"), + DOWNLOAD, + ) + fs = filesystem(drive) + callback = ListAndGetBeforeTransfer( + fs, "root/source/a.txt", "root/source", str(tmp_path / "new.txt") + ) + + fs.get( + "root/source", str(tmp_path / "out"), recursive=True, callback=callback + ) + + assert (tmp_path / "new.txt").read_bytes() == b"new" + assert (tmp_path / "out" / "a.txt").read_bytes() == b"data" + assert "name='a.txt'" in query(requests[3])["q"][0] + downloads = [urlsplit(uri).path for uri, *_ in requests[-2:]] + assert downloads == ["/drive/v3/files/B", "/drive/v3/files/Z"] + + +def test_get_file_after_a_recursive_get_looks_the_path_up_again( + mock_drive, tmp_path +): + replaced = dict(TEXT_FILE, id="B") + drive, requests = mock_drive( + listing(folder("source", "S")), + listing(TEXT_FILE), + DOWNLOAD, + listing(replaced), + ({"status": "200"}, b"new"), + ) + fs = filesystem(drive) + fs.get("root/source", str(tmp_path / "out"), recursive=True) + + fs.get_file("root/source/a.txt", str(tmp_path / "again.txt")) + + assert (tmp_path / "again.txt").read_bytes() == b"new" + assert "name='a.txt'" in query(requests[-2])["q"][0] + assert urlsplit(requests[-1][0]).path == "/drive/v3/files/B" + + +def test_recursive_get_after_listing_a_file_with_two_parents_looks_it_up( + mock_drive, tmp_path +): + shared = dict(TEXT_FILE, parents=["P", "Q"]) + other = dict(TEXT_FILE, id="Z", parents=["Q"]) + drive, requests = mock_drive( + listing(folder("source", "S")), + listing(folder("p", "P"), folder("q", "Q")), + listing(shared, other), + listing(shared), + DOWNLOAD, + listing(shared, other), + DOWNLOAD, + ) + + filesystem(drive).get("root/source", str(tmp_path / "out"), recursive=True) + + assert (tmp_path / "out" / "q" / "a.txt").read_bytes() == b"data" + paths = [urlsplit(uri).path for uri, *_ in requests] + assert paths[4] == paths[6] == "/drive/v3/files/A" + + +def test_recursive_copy_after_a_listed_destination_file_became_a_folder_copies_into_it( + mock_drive, +): + listed = {"name": "out", "id": "O", "mimeType": "text/plain"} + drive, requests = mock_drive( + listing(folder("source", "S")), + listing(listed), + listing(folder("out", "D")), + response(folder("out", "D")), + listing(), + response({"id": "new-1"}), + response({"id": "new-2"}), + ) + + filesystem(drive).copy("root/source", "root/source/out", recursive=True) + + created, copied = (json.loads(body) for _, _, body, *_ in requests[-2:]) + assert (created["name"], created["parents"]) == ("source", ["D"]) + assert urlsplit(requests[-1][0]).path == "/drive/v3/files/O/copy" + assert copied["parents"] == [created["id"]] + + +class CsvOnlyFileSystem(GDriveFileSystem): + def glob(self, path, **kwargs): + matches = super().glob(path, **kwargs) + return [match for match in matches if match.endswith(".csv")] + + +def test_get_after_a_subclass_changes_glob_downloads_only_its_matches( + mock_drive, tmp_path +): + csv = {"name": "a.csv", "id": "A", "mimeType": "text/csv"} + text = {"name": "b.txt", "id": "B", "mimeType": "text/plain"} + drive, _ = mock_drive( + listing(csv, text), + listing(csv), + response(dict(csv, size="4")), + listing(csv), + DOWNLOAD, + ) + fs = CsvOnlyFileSystem( + "root", google_auth=drive.auth, skip_instance_cache=True + ) + + fs.get("root/*", str(tmp_path / "out")) + + assert [path.name for path in (tmp_path / "out").iterdir()] == ["a.csv"] + + +def test_get_of_a_glob_and_a_path_after_the_path_was_replaced_downloads_the_new_file( + mock_drive, tmp_path +): + csv = {"name": "a.csv", "id": "A", "mimeType": "text/csv"} + old = {"name": "manual.txt", "id": "OLD", "mimeType": "text/plain"} + new = dict(old, id="NEW") + drive, requests = mock_drive( + listing(csv, old), + listing(csv), + DOWNLOAD, + listing(new), + DOWNLOAD, + ) + + filesystem(drive).get( + ["root/*.csv", "root/manual.txt"], str(tmp_path / "out") + "/" + ) + + assert urlsplit(requests[-1][0]).path == "/drive/v3/files/NEW" + + +def test_get_after_replacing_get_file_on_the_instance_calls_it( + mock_drive, tmp_path +): + drive, _ = mock_drive( + listing(folder("source", "S")), + listing(TEXT_FILE), + listing(TEXT_FILE), + DOWNLOAD, + ) + fs = filesystem(drive) + get_file = fs.get_file + called = [] + + def recording_get_file(rpath, lpath, **kwargs): + called.append(rpath) + return get_file(rpath, lpath, **kwargs) + + fs.get_file = recording_get_file + fs.get("root/source", str(tmp_path / "out"), recursive=True) + + assert called == ["root/source", "root/source/a.txt"] def test_recursive_put_uploads_files_and_creates_empty_folders( @@ -3058,10 +3314,10 @@ def test_recursive_copy_puts_the_contents_of_a_folder_into_the_root( listing(folder("source", "S")), listing(TEXT_FILE), response({"mimeType": FOLDER_MIME_TYPE}), - listing(TEXT_FILE), response({"id": "copy"}), ) filesystem(drive).copy("root/source/", "root", recursive=True) + assert len(requests) == 4 copy = requests[-1] assert urlsplit(copy[0]).path == "/drive/v3/files/A/copy" assert json.loads(copy[2]) == {