diff --git a/docs/fsspec.rst b/docs/fsspec.rst index f2886084..b4aa34f4 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -65,9 +65,29 @@ A filesystem instance is scoped to one root. Use URLs under the same folder ID or root alias in a single ``fsspec.open_files`` call. Sibling URLs reuse the filesystem and its directory ID cache. Reads by file ID skip name lookups. Reads are sequential. To create a file, use a folder ID or root -alias followed by a filename. As with the direct PyDrive2 filesystem, -a write creates a Drive item even when a sibling has the same name. All -reads require credentials, including files shared by link. +alias followed by a filename. All reads require credentials, including +files shared by link. + +.. _fsspec-writing-files: + +Writing files +------------- + +A write replaces the content of a file at that path that the filesystem +knows, and keeps the file, with its ID, type and sharing. The filesystem +knows the latest 10,000 files it wrote or copied, or found by their path, +for example with ``exists()``, ``info()`` or a read. Listings do not count. +Any other write creates a new file without asking Drive first, even if a +file with that name exists. To replace a file that another client or an +earlier process wrote, call ``fs.exists(path)`` before writing. + +Writing to the path of a known folder raises ``IsADirectoryError``, and to +the path of a known Google Docs file or shortcut ``PermissionError``. If +another client has removed, trashed, moved or renamed the known file, the +write sends the new content to that file and then creates a new file at the +path. Threads that write one path through the same filesystem instance take +turns. Other instances and other clients do not wait, so two of them can +still create two files with the same name. Listings -------- @@ -95,7 +115,9 @@ client moves, trashes, or deletes a folder, call The next lookup checks Drive for all folders with that name, including any same-name folder that still exists. -Only folder IDs are cached between calls. Both ``ls()`` and ``find()`` +Between calls the filesystem keeps folder IDs and the files that writes +can replace (see `Writing files`_), about 350 bytes for each file. +``invalidate_cache()`` forgets those files. Both ``ls()`` and ``find()`` build their results in memory, so larger listings use more memory during the call. diff --git a/docs/upgrading.rst b/docs/upgrading.rst index 7909ba55..f4553c9c 100644 --- a/docs/upgrading.rst +++ b/docs/upgrading.rst @@ -65,6 +65,15 @@ Filesystem directories Both raise ``FileExistsError`` if the folder already exists. Use ``fs.makedirs(path, exist_ok=True)`` when repeating a setup step. +Writing with ``pipe_file()``, ``put_file()`` or ``open(path, "wb")`` to +the path of a file that the filesystem wrote, copied or found by that path +now replaces that file's content. It used to add a second file with the +same name. Other writes still create a file without asking Drive first, so +call ``fs.exists(path)`` before writing to replace a file that another +client or an earlier process wrote. Writing to the path of a known folder +raises ``IsADirectoryError``, and to the path of a known Google Docs file +or shortcut ``PermissionError``. See :ref:`fsspec-writing-files`. + The :doc:`fsspec filesystem ` now caches folders returned by ``ls()``. Later calls such as ``exists("root/data")`` can reuse those IDs. If another client moves or removes a folder, list its parent again or diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index bff5af79..3f995454 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -1,9 +1,9 @@ """Directory edges learned from Drive queries, scoped to one filesystem.""" -from collections import defaultdict +from collections import OrderedDict, defaultdict from contextlib import contextmanager from itertools import count -from threading import RLock +from threading import Lock, RLock from typing import NamedTuple @@ -208,6 +208,13 @@ def has_directory(self, path, mount): for parent in parents ) + def has_child_folder(self, parents, name): + """Whether a folder of this name is known under one of these parents.""" + with self.lock: + return any( + self.children.get(parent, {}).get(name) for parent in parents + ) + def _parents_of_path(self, path): parent, _, name = path.rpartition("/") return self._known_folder_ids(parent), name @@ -432,3 +439,76 @@ def _relink(self, groups, revision): for (parent, name), leaving in moved.items(): self._unlink(parent, name, leaving) return True + + +class KnownFiles: + """The latest files written or found by path, by parent ID and name.""" + + def __init__(self, limit: int): + self.limit = limit + self._lock = Lock() + # Counts changes, so a lookup can tell which ones came after it began. + self.revision = 0 + self._files: OrderedDict[ + tuple[str, str], tuple[str, str | None, int] + ] = OrderedDict() + # The revision of the latest removal under each name. + self._removed: OrderedDict[tuple[str, str], int] = OrderedDict() + + def add(self, parent, name, file_id, mime_type): + """Remember a file; it does not displace a lower ID, as reads pick.""" + with self._lock: + self._add((parent, name), file_id, mime_type) + + def found(self, parents, name, files, revision): + """Record a lookup's answer in one step, so readers see all or none. + + It replaces what was known under each parent it read, except files + stored after the lookup started at this revision. A file removed + since then stays forgotten. + """ + with self._lock: + for parent in parents: + known = self._files.get((parent, name)) + if known is not None and known[2] <= revision: + del self._files[parent, name] + for parent, file_id, mime_type in files: + if self._removed.get((parent, name), 0) <= revision: + self._add((parent, name), file_id, mime_type) + + def _add(self, key, file_id, mime_type): + known = self._files.get(key) + if known is None or file_id < known[0]: + self.revision += 1 + self._files[key] = (file_id, mime_type, self.revision) + self._files.move_to_end(key) + if len(self._files) > self.limit: + self._files.popitem(last=False) + + def get(self, parents, name): + """Return (ID, type, parent) of the lowest known ID, as reads pick.""" + found: list[tuple[str, str | None, str]] = [] + with self._lock: + for parent in parents: + key = (parent, name) + if key in self._files: + self._files.move_to_end(key) + file_id, mime_type, _ = self._files[key] + found.append((file_id, mime_type, parent)) + return min(found, default=None) + + def discard(self, parent, name): + """Forget a file, and when, so an older lookup cannot bring it back.""" + key = (parent, name) + with self._lock: + self._files.pop(key, None) + self.revision += 1 + self._removed[key] = self.revision + self._removed.move_to_end(key) + if len(self._removed) > self.limit: + self._removed.popitem(last=False) + + def clear(self): + with self._lock: + self._files.clear() + self._removed.clear() diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 57c3cbbc..c5c02bb6 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -39,7 +39,7 @@ ApiRequestError, _FileMetadataPages, ) -from pydrive2.fs.cache import DirectoryCache +from pydrive2.fs.cache import DirectoryCache, KnownFiles from pydrive2.fs.utils import IterStream from pydrive2.settings import InvalidConfigError @@ -49,11 +49,15 @@ _LIST_FIELDS = ( f"nextPageToken,incompleteSearch,files(id,name,parents,{_INFO_FIELDS})" ) +# Folders, Google Docs, Sheets and the like, and shortcuts. +_WORKSPACE_TYPE_PREFIX = "application/vnd.google-apps." _NAME_FIELDS = "nextPageToken,incompleteSearch,files(id,name,parents,mimeType)" _MAX_QUERY_TERMS = 50 _CONNECTION_RETRIES = 3 # One request for IDs covers this many new files and folders. _NEW_ID_BATCH = 100 +# Writes replace only these latest files, about 350 bytes each. +_KNOWN_FILES_LIMIT = 10_000 _CONNECTION_ERRORS = ( TimeoutError, ConnectionError, @@ -85,7 +89,7 @@ class _ListedChild: id: str parent: str | None name: str - is_folder: bool + mime_type: str ambiguous: bool size: int | None checksum: str | None @@ -97,12 +101,17 @@ def from_drive(cls, parent, item): id=item["id"], parent=parent, name=item["name"], - is_folder=item["mimeType"] == FOLDER_MIME_TYPE, + # Listed items share a few types, so they share the strings. + mime_type=sys.intern(item["mimeType"]), ambiguous=len(item.get("parents", ())) > 1, size=int(size) if size is not None else None, checksum=item.get("md5Checksum"), ) + @property + def is_folder(self): + return self.mime_type == FOLDER_MIME_TYPE + def entry(self, name, detail=True): if not detail: return name @@ -115,6 +124,8 @@ def entry(self, name, detail=True): class _PathMatch: folders: list[str] files: list[_ListedChild] = field(default_factory=list) + # The parents whose items of this name a listing has just read. + searched: list[str] = field(default_factory=list) def __bool__(self): return bool(self.folders or self.files) @@ -150,7 +161,7 @@ def child(self, parents, path, name, *, folders_only, create=False): if folders: return _PathMatch(folders), False - match = _PathMatch([]) + match = _PathMatch([], searched=list(parents)) with cache.listing(self.generation, parents, name=name) as listing: for item in self.fs._list_children(listing): if item.is_folder: @@ -193,7 +204,7 @@ def directory(self, path, *, create=False): return match blocked = posixpath.join(self.fs.root, last) if self.fresh: - self.fs.invalidate_cache(blocked) + self.fs._dirs.invalidate(last) if match: raise NotADirectoryError( errno.ENOTDIR, os.strerror(errno.ENOTDIR), blocked @@ -607,6 +618,8 @@ def __init__( self._root_lock = threading.RLock() self._root_metadata: dict = {} self._creation_locks: WeakValueDictionary = WeakValueDictionary() + self._known_files = KnownFiles(_KNOWN_FILES_LIMIT) + self._alias_ids: dict[str, str] = {} self._forget_new_ids() if not google_auth: @@ -694,6 +707,7 @@ def invalidate_cache(self, path=None): base = self._split_mounted_path(path)[1] if path else "" super().invalidate_cache(path) with self._dirs.lock: + self._known_files.clear() if not base: self._root_metadata = {} self._dirs.invalidate(base) @@ -868,10 +882,36 @@ def _creation_lock(self, parent_id, name): def _lookup_path(self, path, *, folders_only=False): if not path: return _PathMatch([self.root]), self._dirs.generation + revision = self._known_files.revision resolver = self._resolver() match = resolver.resolve(path, folders_only=folders_only) + files = [ + (item.parent, item.id, item.mime_type) + for item in match.files + if item.parent is not None + ] + with self._dirs.lock: + # A lookup that a change overtook must not bring back old files. + # A folder lookup, as ls() makes, does not make files replaceable. + if ( + resolver.generation == self._dirs.generation + and not folders_only + ): + self._known_files.found( + match.searched, posixpath.basename(path), files, revision + ) return match, resolver.generation + def _canonical_id(self, folder_id): + """Return the ID that Drive reports as the parent for a root alias.""" + if folder_id not in _ROOT_ALIASES: + return folder_id + if folder_id not in self._alias_ids: + item = self.client.CreateFile({"id": folder_id}) + _gdrive_retry_repeatable(item.FetchMetadata)(fields="id") + self._alias_ids[folder_id] = item["id"] + return self._alias_ids[folder_id] + def _get_item_id(self, path, create=False): _, base = self._split_mounted_path(path) if create and base: @@ -1218,14 +1258,79 @@ def find( return contents def upload_fobj(self, stream, rpath, callback=None, **kwargs): + """Write a file, replacing one this filesystem knows at the path.""" parent, name = self._split_file_path(rpath) - parent_id = self._get_item_id(parent, create=True) + _, parent_base = self._split_mounted_path(parent) + parents = ( + self._resolver().directory(parent_base, create=True).folders + if parent_base + else [self._get_item_id(parent, create=True)] + ) + parent_id = min(parents) if callback: stream = _ReadProgress(stream, callback.relative_update) - with _unwrap_not_retried(): - item = self._gdrive_upload_fobj(name, parent_id, stream) - self._dirs.file_added(parent_id, name) - return item + # Threads of this filesystem that write the same path take turns. + with self._creation_lock(parent_id, name): + if self._dirs.has_child_folder(parents, name): + raise IsADirectoryError( + errno.EISDIR, os.strerror(errno.EISDIR), rpath + ) + known = self._known_files.get(parents, name) + with _unwrap_not_retried(): + if known is not None: + item = self._gdrive_replace_known( + rpath, name, known, stream + ) + if item is not None: + return item + item = self._gdrive_upload_fobj(name, parent_id, stream) + self._dirs.file_added(parent_id, name) + if parent_id in _ROOT_ALIASES and item.get("parents"): + self._alias_ids.setdefault(parent_id, item["parents"][0]) + self._known_files.add( + parent_id, name, item["id"], item.get("mimeType") + ) + return item + + def _gdrive_replace_known(self, path, name, known, stream): + """Replace a known file's content, or return None if it has left.""" + file_id, mime_type, parent = known + if (mime_type or "").startswith(_WORKSPACE_TYPE_PREFIX): + raise PermissionError( + errno.EPERM, + "Drive cannot replace a Google Workspace file or a " + "shortcut with bytes", + path, + ) + + metadata = {"id": file_id} + if mime_type: + # Drive would otherwise set the type from the uploaded content. + metadata["mimeType"] = mime_type + + def send(): + item = self.client.CreateFile(metadata) + item.content = stream + item.Upload() + return item + + try: + # Sending the same content to the same file again changes nothing. + item = _gdrive_retry_repeatable(send)() + except ApiRequestError as exc: + if not _is_not_found(exc): + raise + item = None + if ( + item is not None + and not item.get("trashed") + and item.get("name") == name + and self._canonical_id(parent) in item.get("parents", ()) + ): + return item + # Another client deleted, trashed, moved or renamed the file. + self._known_files.discard(parent, name) + return None def put_file(self, lpath, rpath, callback=None, **kwargs): if os.path.isdir(lpath): @@ -1256,14 +1361,17 @@ def cp_file(self, lpath, rpath, **kwargs): 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) + item = self._gdrive_copy_file(source_id, parent_id, name) self._dirs.file_added(parent_id, name) + self._known_files.add( + parent_id, name, item["id"], item.get("mimeType") + ) def _gdrive_copy_file(self, source_id, parent_id, name): source = self.client.CreateFile({"id": source_id}) - self._gdrive_create( + return self._gdrive_create( lambda new_id: source._Copy( - {"id": parent_id}, name, {"fields": "id"}, new_id + {"id": parent_id}, name, {"fields": "id,mimeType"}, new_id ) ) @@ -1346,6 +1454,13 @@ def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs): self._dirs.file_added( destination_parent, dst_name, parent_path=parent_path ) + moved = next(item for item in match.files if item.id == file1_id) + self._known_files.discard(moved.parent, moved.name) + # A rename keeps every parent, including the one it was found in. + if (parent := destination_parent or moved.parent) is not None: + self._known_files.add( + parent, dst_name, file1_id, moved.mime_type + ) def get_file(self, rpath, lpath, callback=None, block_size=None, **kwargs): with _translate_not_found(rpath): @@ -1494,8 +1609,17 @@ def _check_empty_folder(self, item_id, path): ) def rm_file(self, path): - item_id, known_folder = self._lookup_item(path) + _, base = self._split_mounted_path(path) + match, _ = self._lookup_path(base) + item_id = _select_item_id(path, match.ids) + known_folder = item_id in match.folders + if not base and self.root not in _ROOT_ALIASES: + # Drive would trash a trashed root again, or delete it for good. + self._get_root_metadata(path) self._gdrive_delete_file(item_id) + for item in match.files: + if item.id == item_id: + self._known_files.discard(item.parent, item.name) self._invalidate_folder(item_id, path, known_folder=known_folder) def _gdrive_delete_file(self, item_id, *, empty_directory=None): diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index a79ea3b9..9abdf0f4 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -172,10 +172,10 @@ def test_invalidating_parent_reloads_replaced_mount(fs, remote_dir): assert reader.ls(mount) == [mount + "/after"] -def create_on_drive(service_auth, parent_id, name, content=None): +def create_on_drive(service_auth, parent_id, name, content=None, **extra): """Create a file, or a folder without content, as another client would.""" file = GoogleDrive(service_auth).CreateFile( - {"name": name, "parents": [parent_id]} + {"name": name, "parents": [parent_id], **extra} | ({"mimeType": FOLDER_MIME_TYPE} if content is None else {}) ) if content is not None: @@ -824,6 +824,334 @@ def test_cp_file_of_a_shortcut_after_the_answer_was_lost_leaves_one_copy( assert items_below(fs_factory()[0], remote_dir) == ["copy"] +def content_on_drive(service_auth, file_id): + file = GoogleDrive(service_auth).CreateFile({"id": file_id}) + return b"".join(pydrive_retry(file.GetContentIOBuffer)) + + +def metadata_on_drive(service_auth, file_id, fields): + file = GoogleDrive(service_auth).CreateFile({"id": file_id}) + pydrive_retry(file.FetchMetadata, fields=fields) + return file + + +def ids_in(service_auth, folder_id, name=None): + query = f"'{folder_id}' in parents and trashed=false" + if name is not None: + query += f" and name='{name}'" + listing = GoogleDrive(service_auth).ListFile({"q": query}) + return [item["id"] for item in pydrive_retry(listing.GetList)] + + +@pytest.fixture +def drive_methods(monkeypatch): + """The Drive API methods of the requests sent from here on.""" + sent = [] + execute = HttpRequest.execute + + def record(request, *args, **kwargs): + sent.append(request.methodId) + return execute(request, *args, **kwargs) + + monkeypatch.setattr(HttpRequest, "execute", record) + return sent + + +def pipe(fs, path, data, tmp_path): + fs.pipe_file(path, data) + + +def put(fs, path, data, tmp_path): + source = tmp_path / "source" + source.write_bytes(data) + fs.put_file(str(source), path) + + +def write_through_open(fs, path, data, tmp_path): + with fs.open(path, "wb") as stream: + stream.write(data) + + +def test_write_after_makedirs_of_the_parent_creates_the_file_in_one_request( + fs, remote_dir, drive_methods +): + fs.makedirs(remote_dir) + drive_methods.clear() + + fs.pipe_file(remote_dir + "/file", b"data") + + assert drive_methods == ["drive.files.create"] + + +def test_write_after_a_write_to_the_path_replaces_the_file_in_one_request( + fs, fs_factory, remote_dir, drive_methods +): + path = remote_dir + "/file" + fs.pipe_file(path, b"old") + drive_methods.clear() + + fs.pipe_file(path, b"new") + + assert drive_methods == ["drive.files.update"] + other, _ = fs_factory() + assert items_below(other, remote_dir) == ["file"] + assert other.cat_file(path) == b"new" + + +@pytest.mark.parametrize( + "look", + [lambda fs, path: None, lambda fs, path: fs.ls(path)], + ids=["unseen", "ls"], +) +def test_write_after_another_client_made_the_file_adds_a_second_file( + service_auth, fs, remote_dir, remote_dir_id, look +): + file_id = create_on_drive(service_auth, remote_dir_id, "file", "old")["id"] + look(fs, remote_dir + "/file") + + fs.pipe_file(remote_dir + "/file", b"new") + + assert len(ids_in(service_auth, remote_dir_id, "file")) == 2 + assert content_on_drive(service_auth, file_id) == b"old" + + +@pytest.mark.parametrize( + ("write", "size"), + [ + (pipe, 3), + (write_through_open, 3), + # Larger than one request, so the upload is resumable. + (put, 2 * 1024 * 1024), + ], + ids=["pipe_file", "open", "put_file-2MiB"], +) +def test_write_after_exists_found_the_file_replaces_it_and_keeps_its_type( + service_auth, fs, remote_dir, remote_dir_id, tmp_path, write, size +): + data = (b"0123456789abcdef" * (size // 16 + 1))[:size] + file_id = create_on_drive( + service_auth, + remote_dir_id, + "a.json", + "{}", + mimeType="application/json", + )["id"] + assert fs.exists(remote_dir + "/a.json") + + write(fs, remote_dir + "/a.json", data, tmp_path) + + assert ids_in(service_auth, remote_dir_id) == [file_id] + assert content_on_drive(service_auth, file_id) == data + kept = metadata_on_drive(service_auth, file_id, "mimeType") + assert kept["mimeType"] == "application/json" + + +@pytest.mark.parametrize( + "write", + [ + lambda fs, path: fs.touch(path), + lambda fs, path: fs.pipe_file(path, b""), + ], + ids=["touch", "pipe_file"], +) +def test_empty_write_after_exists_found_the_file_empties_it( + service_auth, fs, remote_dir, remote_dir_id, write +): + file_id = create_on_drive(service_auth, remote_dir_id, "file", "old")["id"] + assert fs.exists(remote_dir + "/file") + + write(fs, remote_dir + "/file") + + assert ids_in(service_auth, remote_dir_id) == [file_id] + assert content_on_drive(service_auth, file_id) == b"" + + +def test_write_after_exists_found_two_files_replaces_the_one_reads_return( + service_auth, fs, fs_factory, remote_dir, remote_dir_id +): + files = { + create_on_drive(service_auth, remote_dir_id, "file", "one")[ + "id" + ]: b"one", + create_on_drive(service_auth, remote_dir_id, "file", "two")[ + "id" + ]: b"two", + } + read_id, other_id = sorted(files) + assert fs.exists(remote_dir + "/file") + + fs.pipe_file(remote_dir + "/file", b"new") + + assert fs_factory()[0].cat_file(remote_dir + "/file") == b"new" + assert content_on_drive(service_auth, read_id) == b"new" + assert content_on_drive(service_auth, other_id) == files[other_id] + + +def test_write_after_exists_found_the_file_below_two_same_name_folders_replaces_it( + service_auth, fs, remote_dir, remote_dir_id +): + folders = sorted( + create_on_drive(service_auth, remote_dir_id, "dup")["id"] + for _ in range(2) + ) + # Writes would create a new file in the folder with the lower ID. + file_id = create_on_drive(service_auth, folders[1], "file", "old")["id"] + assert fs.exists(remote_dir + "/dup/file") + + fs.pipe_file(remote_dir + "/dup/file", b"new") + + assert ids_in(service_auth, folders[0]) == [] + assert ids_in(service_auth, folders[1]) == [file_id] + assert content_on_drive(service_auth, file_id) == b"new" + + +def test_replace_after_drive_did_it_and_the_answer_was_lost_keeps_one_file( + service_auth, fs, remote_dir, remote_dir_id, lose_answers +): + file_id = create_on_drive(service_auth, remote_dir_id, "file", "old")["id"] + assert fs.exists(remote_dir + "/file") + lost = lose_answers("PATCH", "") + + fs.pipe_file(remote_dir + "/file", b"new") + + assert len(lost) == 1 + assert ids_in(service_auth, remote_dir_id) == [file_id] + assert content_on_drive(service_auth, file_id) == b"new" + + +def trash(service_auth, file_id, folder_id): + pydrive_retry(GoogleDrive(service_auth).CreateFile({"id": file_id}).Trash) + + +def delete(service_auth, file_id, folder_id): + pydrive_retry(GoogleDrive(service_auth).CreateFile({"id": file_id}).Delete) + + +def rename(service_auth, file_id, folder_id): + file = GoogleDrive(service_auth).CreateFile({"id": file_id}) + file["name"] = "renamed" + pydrive_retry(file.Upload) + + +def move_to_a_subfolder(service_auth, file_id, folder_id): + file = GoogleDrive(service_auth).CreateFile({"id": file_id}) + file["parents"] = [ + create_on_drive(service_auth, folder_id, "elsewhere")["id"] + ] + pydrive_retry(file.Upload) + + +@pytest.mark.parametrize( + "change", [trash, delete, rename, move_to_a_subfolder] +) +def test_write_after_another_client_changed_the_known_file_creates_a_new_one( + service_auth, fs, remote_dir, remote_dir_id, change +): + path = remote_dir + "/file" + fs.pipe_file(path, b"old") + [old_id] = ids_in(service_auth, remote_dir_id) + change(service_auth, old_id, remote_dir_id) + + fs.pipe_file(path, b"new") + + [new_id] = ids_in(service_auth, remote_dir_id, "file") + assert new_id != old_id + assert content_on_drive(service_auth, new_id) == b"new" + + +def test_write_after_another_client_moved_a_known_root_file_creates_a_new_one( + service_auth, fs, remote_dir_id, request +): + name = uuid.uuid4().hex + request.addfinalizer( + lambda: [ + delete(service_auth, file_id, "root") + for file_id in ids_in(service_auth, "root", name) + ] + ) + fs.pipe_file(f"root/{name}", b"old") + [old_id] = ids_in(service_auth, "root", name) + move_to_a_subfolder(service_auth, old_id, remote_dir_id) + + fs.pipe_file(f"root/{name}", b"new") + + [new_id] = ids_in(service_auth, "root", name) + assert new_id != old_id + assert content_on_drive(service_auth, new_id) == b"new" + + +def test_write_after_rm_file_of_the_path_creates_a_file_in_one_request( + fs, fs_factory, remote_dir, drive_methods +): + path = remote_dir + "/file" + fs.pipe_file(path, b"old") + fs.rm_file(path) + drive_methods.clear() + + fs.pipe_file(path, b"new") + + assert drive_methods == ["drive.files.create"] + assert fs_factory()[0].cat_file(path) == b"new" + + +def test_write_after_rmdir_of_a_missing_folder_replaces_the_known_file( + fs, remote_dir, drive_methods +): + path = remote_dir + "/file" + fs.pipe_file(path, b"old") + with pytest.raises(FileNotFoundError): + fs.rmdir(remote_dir + "/missing") + drive_methods.clear() + + fs.pipe_file(path, b"new") + + assert drive_methods == ["drive.files.update"] + + +def test_write_after_mv_to_the_path_replaces_the_moved_file( + fs, fs_factory, remote_dir, drive_methods +): + fs.pipe_file(remote_dir + "/source", b"old") + fs.mv(remote_dir + "/source", remote_dir + "/target") + drive_methods.clear() + + fs.pipe_file(remote_dir + "/target", b"new") + + assert drive_methods == ["drive.files.update"] + other, _ = fs_factory() + assert items_below(other, remote_dir) == ["target"] + assert other.cat_file(remote_dir + "/target") == b"new" + + +def test_write_after_makedirs_of_the_path_raises_and_creates_no_file( + fs, fs_factory, remote_dir +): + fs.makedirs(remote_dir + "/dir") + with pytest.raises(IsADirectoryError): + fs.pipe_file(remote_dir + "/dir", b"data") + assert fs_factory()[0].ls(remote_dir) == [remote_dir + "/dir/"] + + +def test_write_after_mv_of_a_folder_to_the_path_raises_and_creates_no_file( + fs, fs_factory, remote_dir +): + fs.makedirs(remote_dir + "/old") + fs.mv(remote_dir + "/old", remote_dir + "/dir") + with pytest.raises(IsADirectoryError): + fs.pipe_file(remote_dir + "/dir", b"data") + assert fs_factory()[0].ls(remote_dir) == [remote_dir + "/dir/"] + + +@pytest.mark.parametrize("suffix", ["", "-link"], ids=["doc", "shortcut"]) +def test_write_after_exists_found_a_doc_or_shortcut_raises_permission_error( + fs, workspace_files, suffix +): + path = f"root/{workspace_files}{suffix}" + assert fs.exists(path) + with pytest.raises(PermissionError): + fs.pipe_file(path, b"data") + + @pytest.fixture def folder_with_a_file(service_auth, fs_factory, request): drive = GoogleDrive(service_auth) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 71c9d786..33a10537 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -7,6 +7,7 @@ import ssl import sys import tempfile +import time import tracemalloc from concurrent.futures import ThreadPoolExecutor from http.client import IncompleteRead @@ -1162,11 +1163,6 @@ def list_after_lookup_starts(request): @pytest.mark.parametrize( ("write", "responses"), [ - pytest.param( - lambda fs: fs.touch("root/dest/item"), - [response(WRITTEN_FILE)], - id="touch", - ), pytest.param( lambda fs: fs.cp_file("root/source", "root/dest/item"), [ @@ -2240,47 +2236,279 @@ def test_rmdir_checks_emptiness_again_after_transient_failure(mock_drive): assert [r[1] for r in requests] == ["GET", "GET", "DELETE", "GET"] -def test_upload_while_mkdir_is_waiting_for_drive_keeps_both_matches( - mock_drive, -): +def reporting(http, on_request): + """A mock connection that reports each request before answering it.""" + http.on_request = on_request + return http + + +def run_while_paused(first, second, pause_method): + """Start second while first waits for Drive's answer to pause_method. + + Return the methods second sent before first was answered. + """ started, release = Event(), Event() + early = [] - def pause_create(request): - if request[1] == "POST": + def pause(request): + if request[1] == pause_method: started.set() assert release.wait(5) - directory = folder("item", "Z") - file = {"id": "A", "name": "item", "mimeType": "text/plain"} - creator, _ = mock_drive( - listing(), response(directory), on_request=pause_create - ) - drive, requests = mock_drive( - response(file), - listing(file, directory), - ({"status": "200", "content-length": "1"}, b"x"), - ) - fs = filesystem(drive) - http = creator.auth.thread_local.http + def record(request): + if not release.is_set(): + early.append(request[1]) - def create(): - drive.auth.thread_local.http = http + with ThreadPoolExecutor(max_workers=2) as pool: + pending = pool.submit(first, pause) + try: + assert started.wait(5) + later = pool.submit(second, record) + # Give the second thread time to send a request if it can. + time.sleep(0.2) + finally: + release.set() + pending.result(timeout=5) + return early, later + + +def test_write_waits_for_mkdir_of_the_same_name_and_raises_is_a_directory_error( + mock_drive, +): + creator, _ = mock_drive(listing(), response(folder("item", "Z"))) + writer, _ = mock_drive() + fs = filesystem(creator) + threads = creator.auth.thread_local + creator_http = creator.auth.thread_local.http + writer_http = writer.auth.thread_local.http + + def make_folder(on_request): + threads.http = reporting(creator_http, on_request) fs.mkdir("root/item") + def write(on_request): + threads.http = reporting(writer_http, on_request) + fs.touch("root/item") + + early, later = run_while_paused(make_folder, write, "POST") + assert early == [] + with pytest.raises(IsADirectoryError): + later.result(timeout=5) + + +def test_two_threads_writing_one_new_path_create_one_file(mock_drive): + file = { + "id": "A", + "name": "new", + "mimeType": "text/plain", + "parents": ["RealRoot"], + } + first, _ = mock_drive(response(file)) + second, second_requests = mock_drive(response(file)) + fs = filesystem(first) + threads = first.auth.thread_local + first_http = first.auth.thread_local.http + second_http = second.auth.thread_local.http + + def write_first(on_request): + threads.http = reporting(first_http, on_request) + fs.pipe_file("root/new", b"one") + + def write_second(on_request): + threads.http = reporting(second_http, on_request) + fs.pipe_file("root/new", b"two") + + early, later = run_while_paused(write_first, write_second, "POST") + later.result(timeout=5) + assert early == [] + assert [r[1] for r in second_requests] == ["PATCH"] + + +def test_write_after_invalidate_cache_during_a_lookup_creates_a_file( + mock_drive, +): + found = {"id": "A", "name": "item", "mimeType": "text/plain"} + finder, _ = mock_drive(listing(found)) + writer, writer_requests = mock_drive(response(dict(found, id="B"))) + fs = filesystem(finder) + threads = finder.auth.thread_local + finder_http = finder.auth.thread_local.http + writer_http = writer.auth.thread_local.http + + def look_up(on_request): + threads.http = reporting(finder_http, on_request) + assert fs.exists("root/item") + + def invalidate(on_request): + fs.invalidate_cache() + + _, later = run_while_paused(look_up, invalidate, "GET") + later.result(timeout=5) + threads.http = writer_http + + fs.pipe_file("root/item", b"new") + + assert [r[1] for r in writer_requests] == ["POST"] + + +def test_write_after_rm_file_during_a_lookup_of_the_path_creates_a_file( + mock_drive, +): + found = {"id": "A", "name": "item", "mimeType": "text/plain"} + finder, _ = mock_drive(listing(found)) + remover, remover_requests = mock_drive(listing(found), response({})) + writer, writer_requests = mock_drive(response(dict(found, id="B"))) + fs = filesystem(finder) + threads = finder.auth.thread_local + finder_http = finder.auth.thread_local.http + remover_http = remover.auth.thread_local.http + writer_http = writer.auth.thread_local.http + started, release = Event(), Event() + lookups = [] + + def pause(request): + started.set() + assert release.wait(5) + + def look_up(): + threads.http = reporting(finder_http, pause) + return fs.exists("root/item") + with ThreadPoolExecutor(max_workers=1) as pool: - pending = pool.submit(create) + + def look_up_before_the_trash(request): + if request[1] == "PATCH": + lookups.append(pool.submit(look_up)) + assert started.wait(5) + + threads.http = reporting(remover_http, look_up_before_the_trash) try: - assert started.wait(5) - fs.touch("root/item") + fs.rm_file("root/item") finally: release.set() - pending.result(timeout=5) + assert lookups[0].result(timeout=5) + threads.http = writer_http - with fs.open("root/item", "rb") as stream: - assert stream.read() == b"x" + fs.pipe_file("root/item", b"new") + + assert [r[1] for r in remover_requests] == ["GET", "PATCH"] + assert [r[1] for r in writer_requests] == ["POST"] + + +def test_write_after_exists_no_longer_finds_a_known_file_replaces_the_other( + mock_drive, +): + first = {"id": "A", "name": "file", "mimeType": "text/plain"} + second = dict(first, id="B") + drive, requests = mock_drive( + listing(folder("dup", "P"), folder("dup", "Q")), + listing(dict(first, parents=["P"]), dict(second, parents=["Q"])), + listing(dict(second, parents=["Q"])), + response(dict(second, parents=["Q"])), + ) + fs = filesystem(drive) + assert fs.exists("root/dup/file") + # Another client has removed A since. + assert fs.exists("root/dup/file") + + fs.pipe_file("root/dup/file", b"new") + + assert requests[-1][1] == "PATCH" + assert urlsplit(requests[-1][0]).path.endswith("/files/B") + + +def test_write_after_exists_found_a_lower_id_file_with_two_parents_replaces_it( + mock_drive, +): + first = { + "id": "A", + "name": "file", + "mimeType": "text/plain", + "parents": ["P", "X"], + } + second = dict(first, id="B", parents=["P"]) + drive, requests = mock_drive( + listing(folder("dir", "P")), + listing(first, second), + response(first), + ) + fs = filesystem(drive) + assert fs.exists("root/dir/file") + + fs.pipe_file("root/dir/file", b"new") + + assert requests[-1][1] == "PATCH" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + +def test_write_after_mv_renamed_a_file_with_two_parents_replaces_it( + mock_drive, +): + old = { + "id": "A", + "name": "old", + "mimeType": "text/plain", + "parents": ["P", "X"], + } + new = dict(old, name="new") + drive, requests = mock_drive( + listing(folder("dir", "P")), + listing(), + listing(old), + response(new), + response(new), + ) + fs = filesystem(drive) + fs.mv("root/dir/old", "root/dir/new") + + fs.pipe_file("root/dir/new", b"data") + + assert requests[-1][1] == "PATCH" assert urlsplit(requests[-1][0]).path.endswith("/files/A") +def test_write_after_cp_file_onto_a_found_file_replaces_the_one_reads_return( + mock_drive, +): + found = {"id": "A", "name": "item", "mimeType": "text/plain"} + drive, requests = mock_drive( + listing(found), + listing(dict(found, id="S", name="source")), + response(dict(found, id="B")), + response(dict(found, parents=["RealRoot"])), + response({"id": "RealRoot"}), + ) + fs = filesystem(drive) + assert fs.exists("root/item") + fs.cp_file("root/source", "root/item") + + fs.pipe_file("root/item", b"new") + + assert [ + (method, urlsplit(uri).path.rsplit("/", 1)[-1]) + for uri, method, *_ in requests[3:] + ] == [("PATCH", "A"), ("GET", "root")] + + +def test_write_after_10000_writes_to_other_paths_creates_a_second_file( + mock_drive, +): + others = 10_000 + drive, requests = mock_drive( + *( + response({"id": f"F{i}", "name": f"f{i}"}) + for i in range(others + 2) + ) + ) + fs = filesystem(drive) + for i in range(others + 1): + fs.pipe_file(f"root/f{i}", b"") + + fs.pipe_file("root/f0", b"") + + assert requests[-1][1] == "POST" + + def overlap_requests( mock_drive, *, first, first_responses, pause_on, second, second_responses ):