diff --git a/docs/fsspec.rst b/docs/fsspec.rst index f2886084..a90e2f49 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -65,9 +65,15 @@ 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. Writing to the path of an existing file +replaces its content and keeps the file, with its ID, type and sharing. +When several files share the path, the write replaces the one that reads +return. Writing to the path of a folder raises ``IsADirectoryError``, and +to the path of a Google Docs file or a shortcut ``PermissionError``. +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. All reads require credentials, +including files shared by link. Listings -------- diff --git a/docs/upgrading.rst b/docs/upgrading.rst index 9f28692a..967d4fba 100644 --- a/docs/upgrading.rst +++ b/docs/upgrading.rst @@ -65,6 +65,12 @@ Filesystem directories Both raise ``FileExistsError`` if the folder already exists. Use ``fs.makedirs(path, exist_ok=True)`` when repeating a setup step. +Writing to the path of an existing file, with ``pipe_file()``, +``put_file()`` or ``open(path, "wb")``, now replaces that file's content. +It used to add a second file with the same name. Writing to the path of a +folder raises ``IsADirectoryError``, and to the path of a Google Docs file +or a shortcut ``PermissionError``. + 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/spec.py b/pydrive2/fs/spec.py index ac47994b..d61a5b55 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -50,6 +50,8 @@ _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 @@ -86,7 +88,7 @@ class _ListedChild: id: str parent: str | None name: str - is_folder: bool + mime_type: str ambiguous: bool size: int | None checksum: str | None @@ -98,12 +100,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 @@ -1218,14 +1225,64 @@ def find( return contents def upload_fobj(self, stream, rpath, callback=None, **kwargs): + """Write a file. A file already at the path gets the new content.""" + _, base = self._split_mounted_path(rpath) parent, name = self._split_file_path(rpath) - parent_id = self._get_item_id(parent, create=True) + _, parent_base = self._split_mounted_path(parent) + resolver = self._resolver() + parents = ( + resolver.directory(parent_base, create=True).folders + if parent_base + else [self.root] + ) + 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): + existing = self._file_to_replace( + resolver, rpath, base, parents, name + ) + with _unwrap_not_retried(): + if existing is None: + item = self._gdrive_upload_fobj(name, parent_id, stream) + self._dirs.file_added(parent_id, name) + return item + with _translate_not_found(rpath): + return self._gdrive_replace_content(existing, stream) + + def _file_to_replace(self, resolver, path, base, parents, name): + """The file a write to the path replaces, as reads find it.""" + match, _ = resolver.child(parents, base, name, folders_only=False) + if match.folders: + raise IsADirectoryError( + errno.EISDIR, os.strerror(errno.EISDIR), path + ) + if not match.files: + return None + # Reads of a name that several files share use the lowest ID. + existing = min(match.files, key=attrgetter("id")) + if existing.mime_type.startswith(_WORKSPACE_TYPE_PREFIX): + raise PermissionError( + errno.EPERM, + "Drive cannot replace a Google Workspace file or a " + "shortcut with bytes", + path, + ) + return existing + + def _gdrive_replace_content(self, existing, stream): + def send(): + # Without the type, Drive sets it from the uploaded content. + item = self.client.CreateFile( + {"id": existing.id, "mimeType": existing.mime_type} + ) + item.content = stream + item.Upload() + return item + + # Sending the same content to the same file again changes nothing. + return _gdrive_retry_repeatable(send)() def put_file(self, lpath, rpath, callback=None, **kwargs): if os.path.isdir(lpath): diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 1e853a3a..194d7931 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -13,6 +13,7 @@ from googleapiclient.http import HttpRequest from pydrive2.drive import GoogleDrive +from pydrive2.files import FOLDER_MIME_TYPE from pydrive2.fs import GDriveFileSystem from pydrive2.test.test_util import ( GDRIVE_USER_CREDENTIALS_DATA, @@ -238,7 +239,8 @@ def record_listing(request, *args, **kwargs): leaf = remote_dir + "/a/b/c" path = leaf + "/test.txt" fs.touch(path) - assert len(queries) == 5 + # One lookup for each missing folder, and one for the file name. + assert len(queries) == 6 for operation, target, expected in ( (fs.exists, path, True), @@ -734,3 +736,167 @@ def test_cp_file_of_a_shortcut_after_the_answer_was_lost_leaves_one_copy( fs.cp_file(f"root/{workspace_files}-link", remote_dir + "/copy") assert len(lost) == 1 assert items_below(fs_factory()[0], remote_dir) == ["copy"] + + +def create_on_drive(service_auth, parent_id, name, content=None, **extra): + """Create a file, or a folder without content, as another client would.""" + metadata = {"name": name, "parents": [parent_id], **extra} + if content is None: + metadata["mimeType"] = FOLDER_MIME_TYPE + file = GoogleDrive(service_auth).CreateFile(metadata) + if content is not None: + file.SetContentString(content) + pydrive_retry(file.Upload) + return file["id"] + + +@pytest.fixture +def remote_dir_id(service_auth, fs_factory, remote_dir): + """Create remote_dir with the core API and return its ID.""" + _, base = fs_factory() + return create_on_drive( + service_auth, base["id"], posixpath.basename(remote_dir) + ) + + +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): + query = f"'{folder_id}' in parents and trashed=false" + listing = GoogleDrive(service_auth).ListFile({"q": query}) + return [item["id"] for item in pydrive_retry(listing.GetList)] + + +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) + + +@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_to_a_file_path_replaces_the_content_and_keeps_the_file( + 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", + ) + + 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_to_a_file_path_empties_the_file( + service_auth, fs, remote_dir, remote_dir_id, write +): + file_id = create_on_drive(service_auth, remote_dir_id, "file", "old") + + 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_to_a_path_two_files_share_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"): b"one", + create_on_drive(service_auth, remote_dir_id, "file", "two"): b"two", + } + read_id, other_id = sorted(files) + + 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_below_two_folders_with_one_name_replaces_the_file_in_either( + service_auth, fs, remote_dir, remote_dir_id +): + folders = sorted( + create_on_drive(service_auth, remote_dir_id, "dup") 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") + + 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") + 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 test_write_to_a_folder_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/"] + + +@pytest.mark.parametrize("suffix", ["", "-link"], ids=["doc", "shortcut"]) +def test_write_to_a_google_doc_or_shortcut_path_raises_permission_error( + fs, workspace_files, suffix +): + with pytest.raises(PermissionError): + fs.pipe_file(f"root/{workspace_files}{suffix}", b"data") diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index d9492b21..b82a687f 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 @@ -889,6 +890,7 @@ def test_warm_calls_below_a_folder_with_a_same_name_file_reuse_its_id( listing(sub), listing(note), listing(note), + listing(), # No file of that name yet. response({"id": "uploaded"}), ) fs = filesystem(drive, mount) @@ -901,7 +903,7 @@ def test_warm_calls_below_a_folder_with_a_same_name_file_reuse_its_id( ["('S' in parents) and trashed=false and name='note'"] ] fs.touch("root/data/uploaded") - assert [req[1] for req in requests[before + 1 :]] == ["POST"] + assert [req[1] for req in requests[before + 1 :]] == ["GET", "POST"] def test_find_caches_only_the_new_path_for_a_folder_moved_between_batches( @@ -1124,11 +1126,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"), [ @@ -1446,6 +1443,7 @@ def test_nested_file_operations_reuse_resolved_directories(mock_drive): response(b), listing(), response(c), + listing(), # No file of that name yet. response({"id": "file"}), listing(file), listing(a), @@ -1458,14 +1456,10 @@ def test_nested_file_operations_reuse_resolved_directories(mock_drive): leaf = parent + "/a/b/c" path = leaf + "/test.txt" fs.touch(path) - assert [r[1] for r in requests] == [ - "GET", - *(["GET", "POST"] * 4), - "POST", - ] + assert [r[1] for r in requests] == ["GET", *(["GET", "POST"] * 5)] assert [ query(r)["q"][0].split("name=")[-1] for r in requests if r[1] == "GET" - ] == ["'mount'", "'run'", "'a'", "'b'", "'c'"] + ] == ["'mount'", "'run'", "'a'", "'b'", "'c'", "'test.txt'"] for operation, target, expected in ( (fs.exists, path, True), @@ -2202,45 +2196,87 @@ 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 - fs.mkdir("root/item") - - with ThreadPoolExecutor(max_workers=1) as pool: - pending = pool.submit(create) + with ThreadPoolExecutor(max_workers=2) as pool: + pending = pool.submit(first, pause) try: assert started.wait(5) - fs.touch("root/item") + 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 - with fs.open("root/item", "rb") as stream: - assert stream.read() == b"x" - assert urlsplit(requests[-1][0]).path.endswith("/files/A") + +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"} + first, _ = mock_drive(listing(), response(file)) + second, second_requests = mock_drive(listing(file), 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] == ["GET", "PATCH"] def overlap_requests( @@ -2970,7 +3006,10 @@ def send(request): "", ) drive, _ = mock_drive( - *[session] * attempts, response({"id": "file"}), on_request=send + listing(), + *[session] * attempts, + response({"id": "file"}), + on_request=send, ) progress = ProgressSteps() filesystem(drive).put_file(str(source), "root/source", callback=progress) @@ -3001,6 +3040,7 @@ def test_recursive_put_uploads_files_and_creates_empty_folders( listing(), listing(), response({"id": "U"}), + listing(), # No a.txt in the new folder. response({"id": "A"}), listing(), response({"id": "E"}), @@ -3957,7 +3997,7 @@ def fail(size, value): reports.append(value) raise TimeoutError("The progress report timed out") - drive, requests = mock_drive() + drive, requests = mock_drive(listing()) with pytest.raises(TimeoutError, match="progress report"): filesystem(drive).upload_fobj( io.BytesIO(b"data"), @@ -3965,7 +4005,7 @@ def fail(size, value): callback=Callback(hooks={"f": fail}), ) assert reports == [4] - assert requests == [] + assert [r[1] for r in requests] == ["GET"] sleep.assert_not_called()