diff --git a/docs/fsspec.rst b/docs/fsspec.rst index f2886084..c4a70ecd 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -255,9 +255,16 @@ repeated lookups. After an external move or deletion, use When listing a single Drive folder, ``ls()`` returns entries in page order. A file renamed during pagination can appear under both names. -For sequential reads, pass a positive ``block_size`` to ``fs.open()`` to set -the Drive download request size in bytes. A writer buffers data locally, -using a temporary file for larger uploads. Calling ``flush()`` flushes the +A file opened for reading downloads ``fs.blocksize`` bytes (4 MiB by +default) per request. Pass a positive ``block_size`` to ``fs.open()`` to +set another request size in bytes. A program that reads large files from +start to end makes fewer requests with a larger size, such as 64 MiB. +``fs.head()``, ``fs.tail()`` and ``fs.cat_file(path, start, end)`` +download only the bytes they return, with three exceptions. A negative +``end`` downloads from ``start`` to the end of the file. A read with +``compression`` downloads blocks from the beginning of the file. Drive +exports a Google Workspace file whole. A writer buffers data locally, using a +temporary file for larger uploads. Calling ``flush()`` flushes the local buffer. Closing the writer uploads the file to Drive and reports any upload error. diff --git a/pydrive2/files.py b/pydrive2/files.py index a1766669..947b3713 100644 --- a/pydrive2/files.py +++ b/pydrive2/files.py @@ -519,6 +519,32 @@ def open_stream(request, content_type): request = files.export_media(fileId=file_id, mimeType=export_type) return open_stream(request, export_type) + @LoadAuth + def _GetContentRange(self, first, last=None, acknowledge_abuse=False): + """Bytes first to last of the content, both included, in one request. + + As in an HTTP range, last=None reads to the end, and a negative first + with last=None reads the last -first bytes. Google Workspace files + cannot be read this way: Drive answers 403 fileNotDownloadable. + """ + request = self.auth.service.files().get_media( + fileId=self._FileId(), + acknowledgeAbuse=acknowledge_abuse, + supportsAllDrives=True, + ) + if first < 0: + request.headers["Range"] = f"bytes={first}" + else: + end = "" if last is None else last + request.headers["Range"] = f"bytes={first}-{end}" + try: + return self._Execute(request) + except ApiRequestError as error: + # The range starts past the end, as for any range of an empty file. + if error.error.get("code") == 416: + return b"" + raise + @LoadAuth def FetchMetadata(self, fields=None, fetch_all=False): """Download file's metadata from id using Files.get(). diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index ac47994b..61e55071 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -266,6 +266,17 @@ def _file_entry(name, item, detail=True): return name +def _content_size(size, checksum): + """The size of a file's stored bytes, or None if Drive stores none. + + Drive gives no checksum to Google Workspace files and shortcuts, and + their size is not the length of an export. + """ + if checksum is None or size is None: + return None + return int(size) + + def _quote_query_value(value): escaped = value.replace("\\", "\\\\").replace("'", "\\'") return f"'{escaped}'" @@ -1399,7 +1410,8 @@ def _gdrive_open_file(self, item_id, block_size=None): param = {"id": item_id} # it does not create a file on the remote gdrive_file = self.client.CreateFile(param) - options = {} + # Each read() asks Drive for one block, so a short read stays short. + options = {"chunksize": self.blocksize} if block_size not in (None, "default") and block_size > 0: options["chunksize"] = block_size fd = _gdrive_retry_read(gdrive_file.GetContentIOBuffer)( @@ -1407,6 +1419,84 @@ def _gdrive_open_file(self, item_id, block_size=None): ) return IterStream(iter(_gdrive_retry_read(fd.read), None)) + def cat_file(self, path, start=None, end=None, **kwargs): + """Return the file's bytes, or bytes start to end, as a slice would. + + A range is read with one request, not by downloading the whole file. + """ + # Options such as compression change the bytes, so fsspec reads them. + if (start is None and end is None) or kwargs.get("compression"): + return super().cat_file(path, start=start, end=end, **kwargs) + first, last = start or 0, end + # Only a range from the end to a position from the start needs the + # size, and a Google Workspace file has none that fits its export. + need_size = first < 0 and last is not None and last >= 0 + with _translate_not_found(path): + item_id, size = self._file_for_range(path, need_size) + if need_size and size is None: + return super().cat_file(path, **kwargs)[start:end] + if need_size: + first, last, _ = slice(first, last).indices(size) + # Bounds on the same side of the file are empty if out of order. + same_side = last is not None and (first < 0) == (last < 0) + if same_side and last <= first: + return b"" + # A negative end is cut from the bytes read to the end. + cut = last if last is not None and last < 0 else None + file = self.client.CreateFile({"id": item_id}) + try: + data = _gdrive_retry_repeatable(file._GetContentRange)( + first, + None if last is None or cut else last - 1, + acknowledge_abuse=self._acknowledge_abuse, + ) + except ApiRequestError as error: + if error.GetField("reason") != "fileNotDownloadable": + raise + else: + return data[:cut] + if item_id == self.root: + # A folder opened by its ID cannot be downloaded either. + self._file_for_range(path, need_size=True) + return super().cat_file(path, **kwargs)[start:end] + + def _file_for_range(self, path, need_size): + """The ID of the file at the path and, when needed, its size.""" + _, base = self._split_mounted_path(path) + if base or self.root in _ROOT_ALIASES: + match, _ = self._lookup_path(base) + item_id = _select_item_id(path, match.ids) + if item_id in match.folders: + raise IsADirectoryError( + errno.EISDIR, os.strerror(errno.EISDIR), path + ) + file = next(file for file in match.files if file.id == item_id) + return item_id, _content_size(file.size, file.checksum) + if not need_size: + return self.root, None + item = self._get_root_metadata( + fresh=True, fields=f"driveId,trashed,{_INFO_FIELDS}" + ) + if item.get("trashed"): + raise FileNotFoundError( + errno.ENOENT, os.strerror(errno.ENOENT), path + ) + if item["mimeType"] == FOLDER_MIME_TYPE: + raise IsADirectoryError( + errno.EISDIR, os.strerror(errno.EISDIR), path + ) + size = _content_size(item.get("size"), item.get("md5Checksum")) + return self.root, size + + def head(self, path, size=1024): + return self.cat_file(path, 0, size) + + def tail(self, path, size=1024): + # As in fsspec, no size or a negative one returns nothing. + if size <= 0: + return b"" + return self.cat_file(path, -size) + def rmdir(self, path): """Remove one empty Drive folder, honoring the trash_only setting.""" root, base = self._split_mounted_path(path) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 1e853a3a..244adc91 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -1,4 +1,5 @@ import errno +import gzip import os import posixpath import secrets @@ -734,3 +735,153 @@ 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"] + + +@pytest.fixture +def downloads(service_auth, monkeypatch): + """The range asked for and the bytes received in each download.""" + http = service_auth.Get_Http_Object() + send = http.request + seen = [] + + def request(uri, method="GET", body=None, headers=None, **kwargs): + response, content = send( + uri, method, body=body, headers=headers, **kwargs + ) + if "alt=media" in uri: + asked = {k.lower(): v for k, v in (headers or {}).items()} + seen.append((asked.get("range"), len(content))) + return response, content + + monkeypatch.setattr(http, "request", request) + monkeypatch.setattr(service_auth.thread_local, "http", http, raising=False) + return seen + + +@pytest.fixture(scope="module") +def two_mib_file(fs_factory, base_remote_dir): + """A file that the read tests share and do not change.""" + data = os.urandom(2 * 1024 * 1024) + path = f"{base_remote_dir}/{uuid.uuid4().hex}.bin" + fs_factory()[0].pipe_file(path, data) + return path, data + + +def test_head_downloads_only_the_bytes_asked_for(fs, two_mib_file, downloads): + path, data = two_mib_file + assert fs.head(path, 10) == data[:10] + assert downloads == [("bytes=0-9", 10)] + + +def test_tail_downloads_only_the_bytes_asked_for(fs, two_mib_file, downloads): + path, data = two_mib_file + assert fs.tail(path, 10) == data[-10:] + assert downloads == [("bytes=-10", 10)] + + +@pytest.mark.parametrize("size", [0, -5]) +def test_tail_of_no_bytes_downloads_nothing(fs, two_mib_file, downloads, size): + path, _ = two_mib_file + assert fs.tail(path, size) == b"" + assert downloads == [] + + +@pytest.mark.parametrize( + ("start", "end"), + [ + (5, 15), + (-10, -5), + (5, -5), + (-10, 2 * 1024 * 1024 - 5), + (2 * 1024 * 1024 - 3, None), + (3 * 1024 * 1024, None), + ], + ids=[ + "middle", + "from-the-end", + "start-to-before-the-end", + "end-to-a-position", + "to-the-end", + "past-the-end", + ], +) +def test_cat_file_of_a_range_returns_those_bytes(fs, two_mib_file, start, end): + path, data = two_mib_file + assert fs.cat_file(path, start, end) == data[start:end] + + +def test_head_of_an_empty_file_is_empty(fs, remote_dir): + fs.pipe_file(remote_dir + "/empty", b"") + assert fs.head(remote_dir + "/empty") == b"" + + +def test_cat_file_of_a_range_of_a_compressed_file_returns_uncompressed_bytes( + fs, remote_dir +): + path = remote_dir + "/data.gz" + fs.pipe_file(path, gzip.compress(b"abcdefghij")) + assert fs.cat_file(path, end=5, compression="gzip") == b"abcde" + + +# Drive gives a Google Doc a size that is not the length of its export. +@pytest.mark.parametrize( + ("start", "end"), + [(0, 5), (-3, -1), (-3, None), (-3, 10)], + ids=["head", "before-the-end", "tail", "end-to-a-position"], +) +def test_cat_file_of_a_range_of_a_google_doc_slices_its_export( + fs, workspace_files, start, end +): + path = "root/" + workspace_files + assert fs.cat_file(path, start, end) == fs.cat_file(path)[start:end] + + +@pytest.mark.parametrize( + ("start", "end"), [(0, 5), (-10, -5)], ids=["from-start", "from-end"] +) +def test_cat_file_of_a_range_of_a_folder_raises_is_a_directory_error( + fs, remote_dir, start, end +): + fs.makedirs(remote_dir + "/dir") + with pytest.raises(IsADirectoryError): + fs.cat_file(remote_dir + "/dir", start, end) + + +def test_head_of_a_folder_opened_by_its_id_raises_is_a_directory_error( + service_auth, fs_factory +): + _, base = fs_factory() + with pytest.raises(IsADirectoryError): + GDriveFileSystem(base["id"], service_auth).head(base["id"]) + + +def test_head_of_a_deleted_file_id_raises_file_not_found_error( + service_auth, fs_factory +): + _, base = fs_factory() + file = GoogleDrive(service_auth).CreateFile( + {"name": uuid.uuid4().hex, "parents": [base["id"]]} + ) + file.SetContentString("data") + pydrive_retry(file.Upload) + pydrive_retry(file.Delete) + with pytest.raises(FileNotFoundError): + GDriveFileSystem(file["id"], service_auth).head(file["id"], 1) + + +@pytest.mark.parametrize( + ("block_size", "asked"), + [ + (None, 4 * 1024 * 1024), + ("default", 4 * 1024 * 1024), + (512 * 1024, 512 * 1024), + ], + ids=["none", "default", "512KiB"], +) +def test_open_reads_one_block_per_request( + fs, two_mib_file, downloads, block_size, asked +): + path, data = two_mib_file + with fs.open(path, "rb", block_size=block_size) as stream: + assert stream.read(10) == data[:10] + assert downloads == [(f"bytes=0-{asked - 1}", min(asked, len(data)))] diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index d9492b21..75c0e043 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -19,7 +19,6 @@ from google.auth.exceptions import TransportError from google.oauth2 import service_account from google.oauth2.credentials import Credentials -from googleapiclient.http import DEFAULT_CHUNK_SIZE from httplib2 import Response, ServerNotFoundError from pydrive2.files import ApiRequestError @@ -3162,16 +3161,6 @@ def test_open_uses_requested_download_block_size(mock_drive): assert [r[3]["range"] for r in requests] == ["bytes=0-1", "bytes=2-3"] -@pytest.mark.parametrize("block_size", [None, "default"]) -def test_open_uses_default_download_block_size(mock_drive, block_size): - drive, requests = mock_drive(({"status": "200"}, b"data")) - fs = filesystem(drive, "FileID") - with fs.open("FileID", block_size=block_size) as stream: - assert stream.read() == b"data" - (request,) = requests - assert request[3]["range"] == f"bytes=0-{DEFAULT_CHUNK_SIZE - 1}" - - @pytest.mark.parametrize("mode", ["wb", "wt"]) def test_flush_then_write_uploads_once_on_close(mock_drive, monkeypatch, mode): drive, _ = mock_drive()