diff --git a/docs/fsspec.rst b/docs/fsspec.rst index 9195391..8ce4b06 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -66,10 +66,17 @@ argument specifies traversal depth. Directory names returned by ``ls()`` and ``info()`` end in a slash. ``find(withdirs=True)`` returns directory paths without a trailing slash, like fsspec's other traversal methods. -Named directory lookups reuse cached Drive IDs. If another client moves, -trashes, or deletes a folder, call ``fs.invalidate_cache("root/empty")`` -before looking up its old path again. The next lookup checks Drive for all -folders with that name, including any same-name folder that still exists. +Named directory lookups reuse cached Drive IDs. Listing a parent refreshes +the folders seen under that parent. If a listing discovers a folder under +a new name, its cached children follow the folder's Drive ID. If another +client moves, trashes, or deletes a folder, call +``fs.invalidate_cache("root/empty")`` before looking up its old path again. +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()`` +build their results in memory, so larger listings use more memory during +the call. Drive queries for directory entries exclude trashed items. For a bare file ID, ``exists()`` returns false and ``info()`` raises ``FileNotFoundError`` @@ -188,6 +195,9 @@ repeated lookups. After an external move or deletion, use ``fs.invalidate_cache(path)`` for the affected path or ``fs.invalidate_cache()`` to clear the whole cache. +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 diff --git a/docs/upgrading.rst b/docs/upgrading.rst index ecc8b33..a9961c7 100644 --- a/docs/upgrading.rst +++ b/docs/upgrading.rst @@ -15,14 +15,25 @@ during sign-in and provision the resulting token JSON. See :doc:`oauth`. The fsspec backend uses a separate default cache for 2.0. Its first interactive connection prompts for a login. If you pass an explicit user -cache path, choose a new path. For DVC remotes that use -``GDRIVE_CREDENTIALS_DATA`` for a user account, replace its value with the -newly saved credentials. +cache path, choose a new path. If you pass user credentials through +``client_json``, use the newly saved token JSON. Service accounts use their configured JSON or PKCS12 signing key. Keep the key available to the application. Deployments that relied solely on a saved service-account token need to provision the signing key. +Filesystem directory lookups +---------------------------- + +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 +call ``fs.invalidate_cache("root/data")`` before checking the old path. + +Filesystem listings and path lookups read Drive metadata pages directly. +If your application intercepts requests through ``GoogleDrive.ListFile()``, +use the HTTP transport to observe those filesystem requests. + Drive API fields and requests ----------------------------- diff --git a/pydrive2/files.py b/pydrive2/files.py index bcc8e1c..9d2edc0 100644 --- a/pydrive2/files.py +++ b/pydrive2/files.py @@ -20,6 +20,7 @@ ) from .auth import LoadAuth +FOLDER_MIME_TYPE = "application/vnd.google-apps.folder" DEFAULT_FILE_FIELDS = ( "id,name,mimeType,description,parents,trashed,size,md5Checksum," "resourceKey,webViewLink,createdTime,modifiedTime" @@ -99,22 +100,11 @@ def _decorated(self, *args, **kwargs): return _decorated -class GoogleDriveFileList(ApiResourceList): - """Google Drive FileList instance. - - Equivalent to Files.list() in Drive APIs. - """ - - def __init__(self, auth=None, param=None): - """Create an instance of GoogleDriveFileList.""" - super().__init__(auth=auth, metadata=param) +class _FileMetadataPages(ApiResourceList): + """Drive file metadata, one API response per iteration.""" @LoadAuth def _GetList(self): - """Overwritten method which actually makes API call to list files. - - :returns: list -- list of pydrive2.files.GoogleDriveFile. - """ params = dict( self, supportsAllDrives=True, includeItemsFromAllDrives=True ) @@ -130,9 +120,19 @@ def _GetList(self): except errors.HttpError as error: raise ApiRequestError(error) + return self.metadata.get("files", []) + + +class GoogleDriveFileList(_FileMetadataPages): + """GoogleDriveFile objects returned by Drive's files.list API.""" + + def __init__(self, auth=None, param=None): + super().__init__(auth=auth, metadata=param) + + def _GetList(self): return [ GoogleDriveFile(self.auth, metadata, uploaded=True) - for metadata in self.metadata.get("files", []) + for metadata in super()._GetList() ] @@ -485,7 +485,7 @@ def FetchContent(self, mimetype=None, remove_bom=False): if not self.uploaded and not self._SourceMimeType(): self.FetchMetadata() if self._SourceMimeType() in { - "application/vnd.google-apps.folder", + FOLDER_MIME_TYPE, "application/vnd.google-apps.shortcut", }: raise FileNotDownloadableError( diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py new file mode 100644 index 0000000..bff5af7 --- /dev/null +++ b/pydrive2/fs/cache.py @@ -0,0 +1,434 @@ +"""Directory edges learned from Drive queries, scoped to one filesystem.""" + +from collections import defaultdict +from contextlib import contextmanager +from itertools import count +from threading import RLock +from typing import NamedTuple + + +class FolderLocation(NamedTuple): + parent: str + name: str + revision: int + + +class FolderListing: + """Accumulate one logical listing across all pages and parent batches.""" + + def __init__(self, parents, name, generation, revision): + self.revision = revision + self.name = name + self.generation = generation + self.folders: dict[str, dict[str, list[str]]] = { + p: {} for p in parents + } + self.files: set[tuple[str, str]] = set() + self.complete = True + + def overlaps(self, parents, name): + return ( + name is None or self.name is None or self.name == name + ) and not self.folders.keys().isdisjoint(parents) + + def observe(self, children): + if not self.complete: + return + for child in children: + if child.parent is None or ( + child.ambiguous and (child.is_folder or len(self.folders) > 1) + ): + self.complete = False + return + if child.is_folder: + self.folders[child.parent].setdefault(child.name, []).append( + child.id + ) + + if not any(self.folders.values()): + return + + # A named lookup can find a folder under another same-name parent. + # For a full listing only names shared within one parent can collide. + for child in children: + if not child.is_folder and ( + self.name is not None + or child.name in self.folders[child.parent] + ): + self.files.add((child.parent, child.name)) + + +class DirectoryCache: + """Keep children attached to Drive IDs across moves. + + Mutations can invalidate an operation's generation. Reads are ordered by + when each listing started, including when an ID appears under a new name. + """ + + def __init__(self, root: str): + self.root = root + self.lock = RLock() + self.generation = 0 + self._revisions = count() + # Publication compares overlapping reads in their start order. + self._pending: dict[FolderListing, None] = {} + self.children: dict[str, dict[str, tuple[str, ...]]] = {} + # A full listing accounts for absent folder names under this parent. + self._listed_parents: set[str] = set() + # Each child records its parent/name and the revision that placed it. + self.parents: dict[str, FolderLocation] = {} + # A mutation can leave the set of matching folders uncertain. + self.incomplete: set[tuple[str, str]] = set() + + # A file with this name matters only when selecting the final item ID. + self.file_collisions: set[tuple[str, str]] = set() + + def _folders(self, parents, name, *, folders_only): + result: list[str] = [] + for parent in parents: + ids = self.children.get(parent, {}).get(name) + if ids is None and folders_only and parent in self._listed_parents: + continue + edge = (parent, name) + if ( + ids is None + or edge in self.incomplete + or (not folders_only and edge in self.file_collisions) + ): + return None + result.extend(ids) + return result or None + + def lookup(self, parents, name, generation, *, folders_only): + with self.lock: + if generation == self.generation: + return self._folders(parents, name, folders_only=folders_only) + return None + + def prefix(self, path, generation, *, folders_only=False): + parts = path.split("/") if path else [] + folders = [self.root] + with self.lock: + if generation != self.generation: + return "", folders, parts + for i, name in enumerate(parts): + found = self._folders( + folders, + name, + folders_only=folders_only or i < len(parts) - 1, + ) + if not found: + return "/".join(parts[:i]), folders, parts[i:] + folders = found + return path, folders, [] + + def contains(self, path, generation): + return not self.prefix(path, generation, folders_only=True)[2] + + def warm_parents(self, roots, maxdepth, generation): + """Include only parents whose contents can contribute to this walk.""" + with self.lock: + parents = dict.fromkeys(roots) + if generation != self.generation: + return parents + frontier = list(parents) + depth = 1 + while frontier and (maxdepth is None or depth < maxdepth): + following = [] + for parent in frontier: + for ids in self.children.get(parent, {}).values(): + for child in ids: + if child not in parents: + parents[child] = None + following.append(child) + frontier = following + depth += 1 + return parents + + def _remove_name(self, parent, name): + self.incomplete.discard((parent, name)) + self.file_collisions.discard((parent, name)) + names = self.children.get(parent) + if not names: + return () + ids = names.pop(name, ()) + if not names: + del self.children[parent] + return ids + + def _unlink(self, parent, name, leaving): + ids = self.children[parent][name] + if len(ids) == len(leaving): + self._remove_name(parent, name) + else: + self.children[parent][name] = tuple( + i for i in ids if i not in leaving + ) + + def _drop_subtrees(self, roots): + pending = list(roots) + while pending: + parent = pending.pop() + self.parents.pop(parent, None) + self._listed_parents.discard(parent) + for name, ids in self.children.pop(parent, {}).items(): + self.incomplete.discard((parent, name)) + self.file_collisions.discard((parent, name)) + pending.extend(ids) + + def _known_folder_ids(self, path, *, verified=False) -> tuple[str, ...]: + ids: tuple[str, ...] = (self.root,) + for part in path.split("/") if path else (): + if len(ids) == 1: + if verified and (ids[0], part) in self.incomplete: + return () + ids = self.children.get(ids[0], {}).get(part, ()) + else: + ids = tuple( + child + for parent in ids + if not verified or (parent, part) not in self.incomplete + for child in self.children.get(parent, {}).get(part, ()) + ) + if not ids: + break + return ids + + def has_directory(self, path, mount): + # One known folder suffices for exists and makedirs. Operations that + # select a specific Drive ID must resolve all same-name matches. + with self.lock: + if mount and not self._known_folder_ids(mount, verified=True): + return False + parent_path, _, name = path.rpartition("/") + parents = self._known_folder_ids(parent_path, verified=True) + return any( + (parent, name) not in self.incomplete + and 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 + + def invalidate(self, path): + with self.lock: + self.generation += 1 + if not path: + self.children.clear() + self._listed_parents.clear() + self.parents.clear() + self.incomplete.clear() + self.file_collisions.clear() + return + parents, name = self._parents_of_path(path) + for parent in parents: + self._listed_parents.discard(parent) + self._drop_subtrees(self._remove_name(parent, name)) + + def removed(self, item_id, path): + """Discard this folder and recheck any same-name siblings.""" + with self.lock: + self.generation += 1 + if old := self.parents.get(item_id): + self._unlink(old.parent, old.name, (item_id,)) + self._drop_subtrees([item_id]) + self._recheck_path(path) + + def _recheck_name(self, parent, name): + # An uncertain empty match tells us nothing. A surviving folder still + # anchors its cached descendants while Drive rechecks its siblings. + if self.children.get(parent, {}).get(name): + self.incomplete.add((parent, name)) + else: + self._listed_parents.discard(parent) + self._remove_name(parent, name) + + def _recheck_path(self, path): + parents, name = self._parents_of_path(path) + for parent in parents: + self._recheck_name(parent, name) + + def _discard_empty_siblings(self, path): + """An empty sibling is useful only while another parent has this folder.""" + parents, name = self._parents_of_path(path) + if len(parents) > 1 and not any( + self.children.get(parent, {}).get(name) for parent in parents + ): + for parent in parents: + self._remove_name(parent, name) + + def moved(self, generation, item_id, parent, source, destination): + """Relink the folder by ID, keeping its descendants warm.""" + name = destination.rpartition("/")[2] + with self.lock: + old = self.parents.get(item_id) + if parent is None and old is not None: + parent = old.parent + if ( + generation != self.generation + or old is None + or ( + parent != old.parent + and not self._rooted_moves({item_id: parent}) + ) + ): + self.removed(item_id, source) + self._recheck_path(destination) + # A caller can resolve a physical parent through an uncached path. + if parent is not None: + self._recheck_name(parent, name) + return + self._unlink(old.parent, old.name, (item_id,)) + names = self.children.setdefault(parent, {}) + names[name] = (*names.get(name, ()), item_id) + self.parents[item_id] = FolderLocation( + parent, name, next(self._revisions) + ) + self.incomplete.add((parent, name)) + self._discard_empty_siblings(source) + self.generation += 1 + + def created(self, listing, parent, item_id): + # The empty name lookup and the folder POST share this listing. A + # concurrent file write can supersede it until the POST has finished. + with self.lock: + self._invalidate_pending_reads( + (parent,), listing.name, keep=listing + ) + if listing.generation != self.generation: + self._recheck_name(parent, listing.name) + self._listed_parents.discard(parent) + listing.folders[parent][listing.name] = [item_id] + + def _invalidate_pending_reads(self, parents, name, *, keep=None): + for pending in self._pending: + if pending is not keep and pending.overlaps(parents, name): + pending.generation = None + + def file_added(self, parent_id, name, *, parent_path=None): + with self.lock: + # A rename can leave the physical parent unchanged without ever + # requesting its ID. Recheck the name under each possible parent. + parents = ( + self._known_folder_ids(parent_path) + if parent_id is None + else (parent_id,) + ) + self._invalidate_pending_reads(parents, name) + for parent in parents: + if name in self.children.get(parent, {}): + self.file_collisions.add((parent, name)) + + @contextmanager + def listing(self, generation, parents, *, name=None): + with self.lock: + listing = FolderListing( + parents, name, generation, next(self._revisions) + ) + self._pending[listing] = None + try: + yield listing + with self.lock: + if listing.generation == self.generation: + if listing.complete: + self._publish(listing) + else: + self._listed_parents.difference_update(listing.folders) + finally: + with self.lock: + del self._pending[listing] + + def _publish(self, listing): + name = listing.name + # Only publish under parents that are still attached to this root. + groups = { + parent: names + for parent, names in listing.folders.items() + if parent == self.root or parent in self.parents + } + if not groups or not self._relink(groups, listing.revision): + listing.generation = None + return + + retired = [] + has_folder = any(groups.values()) + for parent, names in groups.items(): + previous = self.children.get(parent, {}) + if name is None: + self._listed_parents.add(parent) + for missing in previous.keys() - names.keys(): + retired.extend(self._remove_name(parent, missing)) + elif has_folder: + # An empty sibling matters only when another parent has this folder. + names.setdefault(name, []) + else: + retired.extend(self._remove_name(parent, name)) + + for key, matches in names.items(): + ids = tuple(matches) + before = previous.get(key) + if before and before != ids: + retired.extend(set(before).difference(ids)) + self.children.setdefault(parent, {})[key] = ids + location = FolderLocation(parent, key, listing.revision) + for item_id in ids: + self.parents[item_id] = location + edge = (parent, key) + self.incomplete.discard(edge) + if edge in listing.files: + self.file_collisions.add(edge) + else: + self.file_collisions.discard(edge) + self._drop_subtrees(retired) + # Retired IDs have no reverse entry left to check against an older + # result. Only reads started before this observation need that barrier. + for older in self._pending: + if older is listing: + break + if retired or older.overlaps(groups, name): + older.generation = None + + def _rooted_moves(self, moves): + """Check proposed parent changes together, following each link once.""" + rooted = {self.root} + for folder in moves: + path = set() + while folder not in rooted: + if folder in path: + return False + path.add(folder) + if folder in moves: + folder = moves[folder] + elif location := self.parents.get(folder): + folder = location.parent + else: + return False + rooted.update(path) + return self.root not in moves + + def _relink(self, groups, revision): + # Unlink moved IDs before pruning absent names. Their children stay + # attached to the same ID even when an ancestor changes name or parent. + moved = defaultdict(set) + new_parents = {} + for parent, names in groups.items(): + for name, ids in names.items(): + for item_id in ids: + old = self.parents.get(item_id) + if item_id == self.root or (old and old.parent != parent): + new_parents[item_id] = parent + if old is not None and ( + old.parent != parent or old.name != name + ): + if old.revision > revision: + return False + moved[old.parent, old.name].add(item_id) + if new_parents and not self._rooted_moves(new_parents): + # A partial view of an external move can put a folder below itself. + self.invalidate("") + return False + for (parent, name), leaving in moved.items(): + self._unlink(parent, name, leaving) + return True diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index be42598..8e747db 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -7,32 +7,32 @@ import tempfile import threading import warnings -from contextlib import contextmanager +from contextlib import contextmanager, nullcontext from dataclasses import dataclass, field +from itertools import islice from weakref import WeakValueDictionary import appdirs from fsspec.spec import AbstractFileSystem -from funcy import ( - chunks, - distinct, - retry, -) +from funcy import chunks, distinct, retry from google.oauth2 import service_account from tqdm.utils import CallbackIOWrapper from pydrive2.auth import GoogleAuth, InvalidCredentialsError from pydrive2.drive import GoogleDrive +from pydrive2.files import FOLDER_MIME_TYPE, _FileMetadataPages +from pydrive2.fs.cache import DirectoryCache from pydrive2.fs.utils import IterStream logger = logging.getLogger(__name__) -FOLDER_MIME_TYPE = "application/vnd.google-apps.folder" _INFO_FIELDS = "mimeType,size,md5Checksum" _LIST_FIELDS = ( f"nextPageToken,incompleteSearch,files(id,name,parents,{_INFO_FIELDS})" ) -_PARENT_QUERY_BATCH_SIZE = 50 +_NAME_FIELDS = "nextPageToken,incompleteSearch,files(id,name,parents,mimeType)" +_MAX_QUERY_TERMS = 50 +_ROOT_ALIASES = {"root", "appDataFolder"} _DRIVE_SCOPE = "https://www.googleapis.com/auth/drive" _LIST_ALL_SCOPES = { _DRIVE_SCOPE + suffix @@ -49,36 +49,134 @@ } -@dataclass -class _DirectoryCache: - by_path: dict[str, list[str]] = field(default_factory=dict) - by_id: dict[str, str] = field(default_factory=dict) - mount_checked: bool = False +@dataclass(slots=True) +class _ListedChild: + id: str + parent: str | None + name: str + is_folder: bool + ambiguous: bool + size: int | None + checksum: str | None + + @classmethod + def from_drive(cls, parent, item): + size = item.get("size") + return cls( + id=item["id"], + parent=parent, + name=item["name"], + is_folder=item["mimeType"] == FOLDER_MIME_TYPE, + ambiguous=len(item.get("parents", ())) > 1, + size=int(size) if size is not None else None, + checksum=item.get("md5Checksum"), + ) - def without_subtrees(self, roots, *, keep_roots=False): - kept = _DirectoryCache(mount_checked=self.mount_checked) - for path, ids in self.by_path.items(): - if (keep_roots and path in roots) or not _in_subtrees(path, roots): - kept.by_path[path] = ids.copy() - kept.by_id.update(dict.fromkeys(ids, path)) - return kept + def entry(self, name, detail=True): + if not detail: + return name + if self.is_folder: + return _directory_entry(name) + return _regular_file_entry(name, self.size, self.checksum) @dataclass class _PathMatch: folders: list[str] - files: list[dict] = field(default_factory=list) + files: list[_ListedChild] = field(default_factory=list) + + def __bool__(self): + return bool(self.folders or self.files) @property def ids(self): - return self.folders + [item["id"] for item in self.files] + return self.folders + [item.id for item in self.files] -def _in_subtrees(path: str, roots: tuple[str, ...]) -> bool: - return any( - not root or path == root or path.startswith(root + "/") - for root in roots - ) +class _PathResolver: + """Resolve paths for one operation. A superseded lookup finishes uncached.""" + + def __init__(self, fs, *, fresh=False): + self.fs = fs + self.fresh = fresh + self.generation = None if fresh else fs._dirs.generation + self.mount: _PathMatch | None = None + + def child(self, parents, path, name, *, folders_only, create=False): + if path == self.fs.base and self.mount is not None: + return self.mount, False + + cache = self.fs._dirs + # Hold the name lock across both the lookup and a possible creation. + parent = min(parents) if create else None + lock = ( + self.fs._creation_lock(parent, name) if create else nullcontext() + ) + with lock: + folders = cache.lookup( + parents, name, self.generation, folders_only=folders_only + ) + if folders: + return _PathMatch(folders), False + + match = _PathMatch([]) + with cache.listing(self.generation, parents, name=name) as listing: + for item in self.fs._list_children(listing): + if item.is_folder: + match.folders.append(item.id) + else: + match.files.append(item) + created = create and not match + if created: + item_id = self.fs._gdrive_create_dir(parent, name)["id"] + cache.created(listing, parent, item_id) + match.folders.append(item_id) + self.generation = listing.generation + return match, created + + def _walk(self, path, *, folders_only, create=False): + parent, folders, remaining = self.fs._dirs.prefix( + path, self.generation, folders_only=folders_only + ) + match = _PathMatch(folders) + for name in remaining: + parent = posixpath.join(parent, name) + match, _ = self.child( + match.folders, + parent, + name, + folders_only=folders_only or parent != path, + create=create, + ) + if not match.folders: + break + return parent, match + + def resolve(self, path, *, folders_only=False): + last, match = self._walk(path, folders_only=folders_only) + return match if last == path else _PathMatch([]) + + def directory(self, path, *, create=False): + last, match = self._walk(path, folders_only=True, create=create) + if match.folders: + return match + blocked = posixpath.join(self.fs.root, last) + if self.fresh: + self.fs.invalidate_cache(blocked) + if match: + raise NotADirectoryError( + errno.ENOTDIR, os.strerror(errno.ENOTDIR), blocked + ) + raise FileNotFoundError( + errno.ENOENT, os.strerror(errno.ENOENT), blocked + ) + + +def _drain(items): + """Consume a list in order so each row can be freed as its result is built.""" + items.reverse() + while items: + yield items.pop() def _select_item_id(path, ids): @@ -95,16 +193,33 @@ def _directory_entry(name): return {"name": name, "type": "directory", "size": 0} -def _file_entry(name, item): +@dataclass +class _FileEntry: + """Instance dictionaries share their keys across a detailed listing.""" + + name: str + type: str + size: int | None + checksum: str | None + + +def _regular_file_entry(name, size, checksum): + return vars( + _FileEntry( + name, "file", int(size) if size is not None else None, checksum + ) + ) + + +def _file_entry(name, item, detail=True): if item["mimeType"] == FOLDER_MIME_TYPE: - return _directory_entry(name.rstrip("/") + "/") - size = item.get("size") - return { - "name": name, - "type": "file", - "size": int(size) if size is not None else None, - "checksum": item.get("md5Checksum"), - } + name = name.rstrip("/") + "/" + return _directory_entry(name) if detail else name + if detail: + return _regular_file_entry( + name, item.get("size"), item.get("md5Checksum") + ) + return name def _quote_query_value(value): @@ -298,14 +413,13 @@ def __init__( :raises: GDriveAuthError """ super().__init__(**kwargs) - self._cache_lock = threading.RLock() - self._directory_ids = _DirectoryCache() + self.path = path + self.root, self.base = self.split_path(path) + self._dirs = DirectoryCache(self.root) self._mount_lock = threading.RLock() self._root_lock = threading.RLock() self._root_metadata: dict = {} self._creation_locks: WeakValueDictionary = WeakValueDictionary() - self.path = path - self.root, self.base = self.split_path(self.path) if not google_auth: if ( @@ -369,79 +483,38 @@ def _split_file_path(self, path): parent, name = posixpath.split(base) return posixpath.join(root, parent), name - def _directory_cache(self): - with self._cache_lock: - cache = self._directory_ids - if cache.mount_checked: - return cache, None - with self._mount_lock: - with self._cache_lock: - cache = self._directory_ids - if cache.mount_checked: - return cache, None - mount, cache = self._resolve_path(self.base, cache) - if not mount.ids: - raise FileNotFoundError( - errno.ENOENT, - os.strerror(errno.ENOENT), - f"Confirm {self.path} exists and you can access it", - ) - with self._cache_lock: - cache.mount_checked = True - return cache, mount - - def _cache_path_id(self, cache, path, *item_ids): - with self._cache_lock: - for item_id in item_ids: - old_path = cache.by_id.get(item_id) - if old_path == path: - continue - if old_path is not None: - # Either name can also belong to a different folder. - # Recheck their descendants against the remaining IDs. - kept = cache.without_subtrees( - (old_path, path), keep_roots=True + def _resolver(self): + resolver = _PathResolver(self) + if self.base and not self._dirs.contains( + self.base, resolver.generation + ): + with self._mount_lock: + resolver.generation = self._dirs.generation + resolver.mount = resolver.resolve(self.base) + if not resolver.mount: + raise FileNotFoundError( + errno.ENOENT, + os.strerror(errno.ENOENT), + f"Confirm {self.path} exists and you can access it", ) - if cache is self._directory_ids: - self._directory_ids = kept - if _in_subtrees(self.base, (old_path,)): - kept.mount_checked = False - cache = kept - cache.by_path[old_path].remove(item_id) - if not cache.by_path[old_path]: - del cache.by_path[old_path] - cache.by_id[item_id] = path - cache.by_path.setdefault(path, []).append(item_id) - return cache + return resolver def invalidate_cache(self, path=None): - self._invalidate_paths(path) - - def _invalidate_paths(self, *paths): - subtrees = tuple( - self._split_mounted_path(p)[1] if p else "" for p in paths - ) - for path in paths: - super().invalidate_cache(path) - with self._cache_lock: - if "" in subtrees: + base = self._split_mounted_path(path)[1] if path else "" + super().invalidate_cache(path) + with self._dirs.lock: + if not base: self._root_metadata = {} - if _in_subtrees(self.base, subtrees): - self._directory_ids = _DirectoryCache() - else: - self._directory_ids = self._directory_ids.without_subtrees( - subtrees - ) + self._dirs.invalidate(base) - def _invalidate_folder(self, item_id, *paths, known_folder=False): - with self._cache_lock: - # A lookup may have found this ID under a new name during the mutation. - cached_path = self._directory_ids.by_id.get(item_id) - if cached_path is not None: - paths = (*paths, posixpath.join(self.root, cached_path)) - elif not known_folder and item_id != self.root: - return - self._invalidate_paths(*dict.fromkeys(paths)) + def _invalidate_folder(self, item_id, path, *, known_folder): + with self._dirs.lock: + if item_id == self.root: + self.invalidate_cache(self.root) + elif known_folder or item_id in self._dirs.parents: + super().invalidate_cache(path) + _, base = self._split_mounted_path(path) + self._dirs.removed(item_id, base) @property def _list_params(self): @@ -475,11 +548,11 @@ def _get_root_metadata( with _translate_not_found(self.root): item.FetchMetadata(f"{fields},spaces") except FileNotFoundError: - with self._cache_lock: + with self._dirs.lock: if self._root_metadata is cached: self.invalidate_cache(self.root) raise - with self._cache_lock: + with self._dirs.lock: if self._root_metadata is cached: if item.get("trashed"): self.invalidate_cache(self.root) @@ -491,116 +564,116 @@ def _get_root_metadata( } return item.metadata - def _gdrive_list(self, query): - param = { - "q": query, - "pageSize": 1000, - "fields": _LIST_FIELDS, - } - param.update(self._list_params) - file_list = self.client.ListFile(param) - - get_list = _gdrive_retry(lambda: next(file_list, None)) - for page in iter(get_list, None): - if file_list.metadata.get("incompleteSearch"): + def _query_children(self, parents, names=(), *, fields=_LIST_FIELDS): + parent_query = " or ".join( + f"{_quote_query_value(p)} in parents" for p in parents + ) + query = f"({parent_query}) and trashed=false" + if names: + terms = " or ".join(f"name={_quote_query_value(n)}" for n in names) + query += f" and {terms}" if len(names) == 1 else f" and ({terms})" + pages = _FileMetadataPages( + self.client.auth, + dict(self._list_params, q=query, pageSize=1000, fields=fields), + ) + get_page = _gdrive_retry(lambda: next(pages, None)) + for page in iter(get_page, None): + if pages.metadata.get("incompleteSearch"): raise OSError(errno.EIO, "Incomplete Drive listing") yield from page - def _gdrive_list_ids(self, query_ids, *, name=None): - filters = "trashed=false" - if name is not None: - filters += f" and name={_quote_query_value(name)}" - # Drive can reject large parent queries. Query each parent only once. - seen_ids = set() - for batch in chunks(_PARENT_QUERY_BATCH_SIZE, distinct(query_ids)): - parents = " or ".join( - f"{_quote_query_value(parent)} in parents" for parent in batch + def _list_children( + self, listing, *, require_parent=False, fields=_LIST_FIELDS + ): + # A later page or batch may report a new location for the same ID. + rows = {} + names = (listing.name,) if listing.name is not None else () + for batch in chunks(_MAX_QUERY_TERMS, listing.folders): + # Reuse the queried parent string for all children in a large folder. + batch_ids = {parent: parent for parent in batch} + # Drive may report the canonical ID instead of the requested root alias. + root_alias = ( + batch_ids.get(self.root) + if self.root in _ROOT_ALIASES + else None ) - for item in self._gdrive_list(f"({parents}) and {filters}"): + unplaced = {} + for item in self._query_children(batch, names, fields=fields): + if names and item["name"] != listing.name: + continue # Drive matches case-insensitively. file_id = item["id"] - if file_id in seen_ids: + if len(batch) == 1: + parent = batch[0] + else: + parents = item.get("parents", ()) + parent = next( + (batch_ids[p] for p in parents if p in batch_ids), + root_alias if parents else None, + ) + if parent is None and require_parent: + unplaced[file_id] = item["name"] continue - # Only a full batch can be followed by another parent query. - if len(batch) == _PARENT_QUERY_BATCH_SIZE: - seen_ids.add(file_id) - yield item - - def _match_child(self, cache, parent_ids, path, name, mount=None): - if path == self.base and mount is not None: - return mount, cache - match = _PathMatch([]) - for item in self._gdrive_list_ids(parent_ids, name=name): - if item["name"] != name: # Drive matches case-insensitively. - continue - if item["mimeType"] == FOLDER_MIME_TYPE: - match.folders.append(item["id"]) - else: - match.files.append(item) - return match, self._cache_path_id(cache, path, *match.folders) - - def _cached_prefix(self, path, cache): - parent = path - remaining = [] - with self._cache_lock: - while parent and parent not in cache.by_path: - parent, name = posixpath.split(parent) - remaining.append(name) - folders = cache.by_path[parent].copy() if parent else [self.root] - return parent, folders, reversed(remaining) - - def _resolve_prefix(self, path, cache, mount=None): - """Return the deepest existing component, its matches and lookup cache.""" - parent, folders, remaining = self._cached_prefix(path, cache) - match = _PathMatch(folders) - for name in remaining: - child = posixpath.join(parent, name) - found, cache = self._match_child( - cache, match.folders, child, name, mount + unplaced.pop(file_id, None) + rows[file_id] = _ListedChild.from_drive(parent, item) + + if unplaced: + self._locate_children(batch, unplaced, rows, fields) + if unplaced: + # Later observations supersede earlier pages, even if the + # item disappeared before its new parent could be found. + listing.complete = False + for file_id in unplaced: + rows.pop(file_id, None) + + listing.observe(rows.values()) + return rows.values() + + def _locate_children(self, parents, missing, rows, fields): + """Place rows with hidden parent IDs using Drive's parent query.""" + size = 1 + while parents and missing: + probe, parents = parents[:size], parents[size:] + # Stop once the names no longer fit in a single Drive query. + names = list( + islice(distinct(missing.values()), _MAX_QUERY_TERMS + 1) ) - if not found.folders and not found.files: - break - parent, match = child, found - if not match.folders: - break - return parent, match, cache - - def _resolve_path( - self, path, cache, mount=None - ) -> tuple[_PathMatch, _DirectoryCache]: - prefix, match, cache = self._resolve_prefix(path, cache, mount) - return (match if prefix == path else _PathMatch([])), cache - - def _ensure_dirs(self, path, cache, mount=None): - parent, folders, remaining = self._cached_prefix(path, cache) - for name in remaining: - parent = posixpath.join(parent, name) - match, cache = self._get_or_create_child( - cache, folders, parent, name, mount - ) - if not match.folders: - raise NotADirectoryError(posixpath.join(self.root, parent)) - folders = match.folders - return folders, cache + if len(names) > _MAX_QUERY_TERMS: + names.clear() + for item in self._query_children(probe, names, fields=fields): + item_id = item["id"] + if item_id not in missing: + continue + if size > 1: + parents = probe + break + del missing[item_id] + rows[item_id] = _ListedChild.from_drive(probe[0], item) + # For one remaining ID, narrow the search by halves. Only a + # single-parent query can confirm where to place the item. + size = (len(parents) + 1) // 2 if len(missing) == 1 else 1 + + def _creation_lock(self, parent_id, name): + key = (parent_id, name) + with self._dirs.lock: + lock = self._creation_locks.get(key) + if lock is None: + lock = self._creation_locks[key] = threading.RLock() + return lock - def _lookup_path(self, path): + def _lookup_path(self, path, *, folders_only=False): if not path: - with self._cache_lock: - return _PathMatch([self.root]), self._directory_ids - cache, mount = self._directory_cache() - return self._resolve_path(path, cache, mount) - - def _path_to_item_ids(self, path, create=False): - if create and path: - cache, mount = self._directory_cache() - folders, _ = self._ensure_dirs(path, cache, mount) - return folders - match, _ = self._lookup_path(path) - return match.ids + return _PathMatch([self.root]), self._dirs.generation + resolver = self._resolver() + match = resolver.resolve(path, folders_only=folders_only) + return match, resolver.generation def _get_item_id(self, path, create=False): _, base = self._split_mounted_path(path) - ids = self._path_to_item_ids(base, create=create) - return _select_item_id(path, ids) + if create and base: + match = self._resolver().directory(base, create=True) + return _select_item_id(path, match.folders) + match, _ = self._lookup_path(base) + return _select_item_id(path, match.ids) @_gdrive_retry def _gdrive_create_dir(self, parent_id, name): @@ -614,35 +687,6 @@ def _gdrive_create_dir(self, parent_id, name): item.Upload() return item - def _get_or_create_child( - self, cache, parents, path, name, mount=None, *, exist_ok=True - ): - parent_id = min(parents) - key = (parent_id, name) - with self._cache_lock: - lock = self._creation_locks.get(key) - if lock is None: - lock = self._creation_locks[key] = threading.RLock() - with lock: - with self._cache_lock: - folders = cache.by_path.get(path, []).copy() - if folders: - match = _PathMatch(folders) - else: - # An invalidation can give two writers different caches. Check - # Drive under the same name lock as the create. - match, cache = self._match_child( - cache, parents, path, name, mount - ) - if match.folders or match.files: - if not exist_ok: - raise FileExistsError(posixpath.join(self.root, path)) - return match, cache - item = self._gdrive_create_dir(parent_id, name) - return _PathMatch([item["id"]]), self._cache_path_id( - cache, path, item["id"] - ) - def mkdir(self, path, create_parents=True, **kwargs): self._mkdir(path, create_parents, exist_ok=False) @@ -651,10 +695,8 @@ def makedirs(self, path, exist_ok=False): def _mkdir(self, path, create_parents, exist_ok): root, base = self._split_mounted_path(path) - with self._cache_lock: - cache = self._directory_ids - cached = cache.mount_checked and base in cache.by_path - if not cached and root not in {"root", "appDataFolder"}: + cached = base and self._dirs.has_directory(base, self.base) + if not cached and root not in _ROOT_ALIASES: metadata = self._get_root_metadata(fresh=True) if metadata.get("trashed"): raise FileNotFoundError( @@ -671,27 +713,21 @@ def _mkdir(self, path, create_parents, exist_ok): raise FileExistsError(path) return - cache, mount = self._directory_cache() + resolver = self._resolver() parent, name = posixpath.split(base) - if create_parents: - folders, cache = self._ensure_dirs(parent, cache, mount) - else: - prefix, match, cache = self._resolve_prefix(parent, cache, mount) - if not match.folders: - raise NotADirectoryError(posixpath.join(root, prefix)) - if prefix != parent: - raise FileNotFoundError(posixpath.join(root, parent)) - folders = match.folders - leaf, _ = self._get_or_create_child( - cache, folders, base, name, mount, exist_ok=exist_ok + parent_match = resolver.directory(parent, create=create_parents) + leaf, created = resolver.child( + parent_match.folders, base, name, folders_only=True, create=True ) - if not leaf.folders: + if not leaf.folders or (not exist_ok and not created): raise FileExistsError(path) def exists(self, path): root, base = self._split_mounted_path(path) + if base and self._dirs.has_directory(base, self.base): + return True try: - if not base and root not in {"root", "appDataFolder"}: + if not base and root not in _ROOT_ALIASES: self.info(path) else: with _translate_not_found(path): @@ -703,7 +739,7 @@ def exists(self, path): def info(self, path): bucket, base = self._split_mounted_path(path) - if not base and bucket not in {"root", "appDataFolder"}: + if not base and bucket not in _ROOT_ALIASES: gdrive_file = self._get_root_metadata( fresh=True, fields=f"driveId,trashed,{_INFO_FIELDS}" ) @@ -725,89 +761,79 @@ def info(self, path): def ls(self, path, detail=False): bucket, base = self._split_mounted_path(path) - match, cache = self._lookup_path(base) - dir_ids = match.ids + match, generation = self._lookup_path(base, folders_only=True) + dir_ids = match.folders or match.ids if not dir_ids: raise FileNotFoundError( errno.ENOENT, os.strerror(errno.ENOENT), path ) root_path = posixpath.join(bucket, base) - contents = [] - folders = [] - for item in self._gdrive_list_ids(dir_ids): - item_path = posixpath.join(root_path, item["name"]) - contents.append(_file_entry(item_path, item)) - if item["mimeType"] == FOLDER_MIME_TYPE: - folders.append( - (item["id"], posixpath.join(base, item["name"])) + fields = _LIST_FIELDS if detail else _NAME_FIELDS + if len(dir_ids) == 1: + with self._dirs.listing(generation, dir_ids) as listing: + return self._ls_folder( + listing, dir_ids[0], root_path, fields, detail ) - if folders: - self._invalidate_listed_renames(cache, folders) - - if detail: - return contents - else: - return [content["name"] for content in contents] - - def _invalidate_listed_renames(self, cache, folders): - with self._cache_lock: - if cache is not self._directory_ids: - return - changed: set[str] = set() - for item_id, path in folders: - old_path = cache.by_id.get(item_id) - if old_path is not None and old_path != path: - changed.update((old_path, path)) - if changed: - # Re-resolve both names so same-name siblings remain visible. - self._invalidate_paths(*(f"{self.root}/{p}" for p in changed)) - - def _walk_folders(self, base, start_ids, cache, maxdepth): - # Cache entries are hints about which parents can share a request. - # Build paths only from the parent links in the current Drive listing. - frontier = dict.fromkeys(start_ids, base) - to_list = dict.fromkeys(frontier) - if maxdepth != 1: - prefix = base + "/" if base else "" - with self._cache_lock: - for item_id, name in cache.by_id.items(): - if name.startswith(prefix) and ( - maxdepth is None - or name[len(prefix) :].count("/") + 1 < maxdepth - ): - to_list[item_id] = None + with self._dirs.listing(generation, dir_ids) as listing: + children = list(self._list_children(listing, fields=fields)) + contents = [] + for child in _drain(children): + name = posixpath.join(root_path, child.name) + if child.is_folder: + name = name.rstrip("/") + "/" + contents.append(child.entry(name, detail)) + return contents + + def _ls_folder(self, listing, parent, path, fields, detail): + """Build results as pages arrive. Only folders need cache metadata.""" + entries = [] + folders = {} + for item in self._query_children([parent], fields=fields): + name = posixpath.join(path, item["name"]) + entries.append(_file_entry(name, item, detail)) + if item["mimeType"] == FOLDER_MIME_TYPE: + folders[item["id"]] = _ListedChild.from_drive(parent, item) + elif folders: + folders.pop(item["id"], None) + + listing.observe(folders.values()) + if folders and listing.complete: + names = { + posixpath.join(path, name): name + for name in listing.folders[parent] + } + for entry in entries: + file_path = entry["name"] if detail else entry + if file_path in names: + listing.files.add((parent, names[file_path])) + return entries + + def _walk_folders(self, start, start_ids, generation, maxdepth, fields): + frontier = dict.fromkeys(start_ids, start) + to_list = self._dirs.warm_parents(frontier, maxdepth, generation) depth = 0 - children: dict[str, list[dict]] = {} + children: dict[str, list[_ListedChild]] = {} visited: set[str] = set() while frontier: depth += 1 - children.update({item_id: [] for item_id in to_list}) - for item in self._gdrive_list_ids(to_list): - parent = next( - (p for p in item.get("parents", ()) if p in to_list), None - ) - # Drive reports the canonical ID when a root alias was queried. - if ( - parent is None - and self.root in {"root", "appDataFolder"} - and self.root in to_list - ): - parent = self.root - if parent is not None: - children[parent].append(item) + if to_list: + with self._dirs.listing(generation, to_list) as listing: + children.update((parent, []) for parent in to_list) + for item in self._list_children( + listing, require_parent=True, fields=fields + ): + children[item.parent].append(item) + generation = listing.generation visited.update(frontier) following = {} for parent, parent_path in frontier.items(): - for item in children.pop(parent): - path = posixpath.join(parent_path, item["name"]) - if item["mimeType"] == FOLDER_MIME_TYPE: - item_id = item["id"] - cache = self._cache_path_id(cache, path, item_id) - if item_id not in visited: - following[item_id] = path + for item in _drain(children.pop(parent)): + path = posixpath.join(parent_path, item.name) + if item.is_folder and item.id not in visited: + following[item.id] = path yield path, item if depth == maxdepth: return @@ -833,45 +859,36 @@ def find( root, base = self._split_mounted_path(path) if maxdepth is not None and maxdepth < 1: raise ValueError("maxdepth must be at least 1") - cache, mount = self._directory_cache() - match, cache = self._resolve_path(base, cache, mount) - file = ( - min(match.files, key=lambda item: item["id"], default=None) - if not match.folders - else None - ) + resolver = self._resolver() + match = resolver.resolve(base, folders_only=True) start = posixpath.join(root, base).rstrip("/") check_empty_root = False - if not base and root not in {"root", "appDataFolder"}: + if not base and root not in _ROOT_ALIASES: if self._root_metadata.get("mimeType") == FOLDER_MIME_TYPE: check_empty_root = withdirs else: try: - metadata = self._get_root_metadata( - fresh=True, fields=f"driveId,trashed,{_INFO_FIELDS}" - ) + entry = self.info(start) except FileNotFoundError: return {} if detail else [] - if metadata.get("trashed"): - return {} if detail else [] - if metadata["mimeType"] != FOLDER_MIME_TYPE: - file = metadata - if file is not None: - return {start: _file_entry(start, file)} if detail else [start] + if entry["type"] == "file": + return {start: entry} if detail else [start] if not match.folders: + if match.files: + file = min(match.files, key=lambda item: item.id) + return {start: file.entry(start)} if detail else [start] return {} if detail else [] contents = [] - for relative, item in self._walk_folders( - base, match.folders, cache, maxdepth + if withdirs: + contents.append(_directory_entry(start) if detail else start) + fields = _LIST_FIELDS if detail else _NAME_FIELDS + for name, item in self._walk_folders( + start, match.folders, resolver.generation, maxdepth, fields ): check_empty_root = False - name = posixpath.join(root, relative) - if item["mimeType"] == FOLDER_MIME_TYPE: - if withdirs: - contents.append(_directory_entry(name)) - else: - contents.append(_file_entry(name, item)) + if withdirs or not item.is_folder: + contents.append(item.entry(name, detail)) if check_empty_root: try: @@ -879,12 +896,11 @@ def find( except FileNotFoundError: return {} if detail else [] - if withdirs: - contents.insert(0, _directory_entry(start)) - contents.sort(key=lambda entry: entry["name"]) if detail: + contents.sort(key=lambda entry: entry["name"]) return {entry["name"]: entry for entry in contents} - return [entry["name"] for entry in contents] + contents.sort() + return contents def upload_fobj(self, stream, rpath, callback=None, **kwargs): parent, name = self._split_file_path(rpath) @@ -893,7 +909,9 @@ def upload_fobj(self, stream, rpath, callback=None, **kwargs): stream = CallbackIOWrapper( callback.relative_update, stream, "read" ) - return self._gdrive_upload_fobj(name, parent_id, stream) + item = self._gdrive_upload_fobj(name, parent_id, stream) + self._dirs.file_added(parent_id, name) + return item def put_file(self, lpath, rpath, callback=None, **kwargs): if callback: @@ -914,6 +932,7 @@ def cp_file(self, lpath, rpath, **kwargs): source_id = self._get_item_id(lpath) parent_id = self._get_item_id(parent, create=True) self._gdrive_copy_file(source_id, parent_id, name) + self._dirs.file_added(parent_id, name) @_gdrive_retry def _gdrive_copy_file(self, source_id, parent_id, name): @@ -941,24 +960,54 @@ def mv(self, path1, path2, maxdepth=None, **kwargs): dst_name = posixpath.basename(path2) dst_parent = self._parent(path2) - file1_id = self._get_item_id(path1) - + _, source = self._split_mounted_path(path1) + _, parent_path = self._split_mounted_path(dst_parent) + match, generation = self._lookup_path(source) + file1_id = _select_item_id(path1, match.ids) file1 = self.client.CreateFile({"id": file1_id}) - if src_name != dst_name: file1["name"] = dst_name + destination_parent = None if src_parent != dst_parent: - file2_parent_id = self._get_item_id(dst_parent) - file1["parents"] = [file2_parent_id] + parent_match, _ = self._lookup_path(parent_path, folders_only=True) + if parent_match.files and not parent_match.folders: + raise NotADirectoryError(dst_parent) + destination_parent = _select_item_id( + dst_parent, parent_match.folders + ) + file1["parents"] = [destination_parent] file1.Upload() - if file1.get("mimeType") == FOLDER_MIME_TYPE: - self._invalidate_folder( - file1_id, - path1, - posixpath.join(dst_parent, dst_name), - known_folder=True, + if ( + file1_id in match.folders + or file1.get("mimeType") == FOLDER_MIME_TYPE + ): + destination = posixpath.join(dst_parent, dst_name) + if file1_id == self.root: + self.invalidate_cache(self.root) + else: + self._dirs.moved( + generation, + file1_id, + destination_parent, + source, + posixpath.join(parent_path, dst_name), + ) + super().invalidate_cache(path1) + super().invalidate_cache(destination) + else: + if destination_parent is None: + destination_parent = next( + ( + item.parent + for item in match.files + if item.id == file1_id and not item.ambiguous + ), + None, + ) + self._dirs.file_added( + destination_parent, dst_name, parent_path=parent_path ) def get_file(self, rpath, lpath, callback=None, block_size=None, **kwargs): @@ -1014,32 +1063,19 @@ def _gdrive_open_file(self, item_id, block_size=None): ) return IterStream(iter(fd)) - def _fresh_folder_match(self, base): - # A cached folder ID cannot establish whether the name is still unique. - prefix, match, _ = self._resolve_prefix(base, _DirectoryCache()) - if not match.folders: - blocked = posixpath.join(self.root, prefix) - self.invalidate_cache(blocked) - raise NotADirectoryError( - errno.ENOTDIR, os.strerror(errno.ENOTDIR), blocked - ) - if prefix != base: - missing = base.removeprefix(prefix).lstrip("/").partition("/")[0] - path = posixpath.join(self.root, prefix, missing) - self.invalidate_cache(path) - raise FileNotFoundError( - errno.ENOENT, os.strerror(errno.ENOENT), path - ) - return match - def rmdir(self, path): """Remove one empty Drive folder, honoring the trash_only setting.""" root, base = self._split_mounted_path(path) if base: - # Walking the target also checks the mount when it is an ancestor. - if not _in_subtrees(base, (self.base,)): - self._fresh_folder_match(self.base) - match = self._fresh_folder_match(base) + # Check uniqueness on Drive before removing a directory by name. + resolver = _PathResolver(self, fresh=True) + if ( + self.base + and base != self.base + and not base.startswith(self.base + "/") + ): + resolver.directory(self.base) + match = resolver.directory(base) if len(match.ids) != 1: raise FileExistsError( errno.EEXIST, @@ -1048,7 +1084,7 @@ def rmdir(self, path): ) item_id = match.folders[0] else: - if root in {"root", "appDataFolder"}: + if root in _ROOT_ALIASES: raise PermissionError( errno.EPERM, "Cannot remove a Drive root", path ) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index fb381a7..f47876f 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -5,9 +5,11 @@ import uuid from concurrent import futures from io import StringIO +from urllib.parse import parse_qsl, urlsplit import fsspec import pytest +from googleapiclient.http import HttpRequest from pydrive2.auth import GoogleAuth from pydrive2.fs import GDriveFileSystem @@ -213,14 +215,24 @@ def by_name(details): assert dirs == expected -def test_basic_ops_caching(fs, remote_dir, mocker): - # Count logical Drive listings. Transport retries and pages belong to - # the same ListFile call. The offline test counts individual requests. - lists = mocker.spy(fs.client, "ListFile") +def test_basic_ops_caching(fs, remote_dir, monkeypatch): + queries = [] + execute = HttpRequest.execute + + def record_listing(request, *args, **kwargs): + result = execute(request, *args, **kwargs) + if request.methodId == "drive.files.list": + params = dict(parse_qsl(urlsplit(request.uri).query)) + # Each successful first page starts one logical listing. + if "pageToken" not in params: + queries.append(params.get("q")) + return result + + monkeypatch.setattr(HttpRequest, "execute", record_listing) leaf = remote_dir + "/a/b/c" path = leaf + "/test.txt" fs.touch(path) - assert lists.call_count == 5 + assert len(queries) == 5 for operation, target, expected in ( (fs.exists, path, True), @@ -229,9 +241,9 @@ def test_basic_ops_caching(fs, remote_dir, mocker): (fs.find, leaf, [path]), (fs.find, remote_dir, [path]), ): - before = lists.call_count + queries.clear() assert operation(target) == expected - assert lists.call_count - before == 1, (operation.__name__, target) + assert len(queries) == 1, (operation.__name__, target, queries) def test_ops_work_with_duplicate_names(fs_factory, remote_dir): diff --git a/pydrive2/test/test_fs_listing.py b/pydrive2/test/test_fs_listing.py deleted file mode 100644 index 1b9fca6..0000000 --- a/pydrive2/test/test_fs_listing.py +++ /dev/null @@ -1,63 +0,0 @@ -import re -from unittest.mock import Mock - -import pytest - -from pydrive2.fs import GDriveFileSystem - - -@pytest.fixture -def listing_fs(): - return GDriveFileSystem( - "root", google_auth=Mock(), skip_instance_cache=True - ) - - -@pytest.mark.parametrize("count", [0, 1, 50, 51, 100, 251]) -@pytest.mark.parametrize("container", [list, dict.fromkeys, iter]) -def test_list_ids_batches(listing_fs, monkeypatch, count, container): - ids = [f"parent-{index}" for index in range(count)] - listed = [] - - def list_query(query): - parents = re.findall(r"'([^']+)' in parents", query) - # Model an API that rejects overly complex parent queries. - assert 0 < len(parents) <= 50 - assert query.endswith(") and trashed=false") - listed.extend(parents) - return ({"id": parent} for parent in parents) - - monkeypatch.setattr(listing_fs, "_gdrive_list", list_query) - - assert [ - item["id"] for item in listing_fs._gdrive_list_ids(container(ids)) - ] == ids - assert listed == ids - - -def test_list_ids_lazy(listing_fs, monkeypatch): - consumed = [] - - def parents(): - for index in range(51): - consumed.append(index) - yield str(index) - - list_query = Mock( - side_effect=[ - iter([{"id": "page-1"}, {"id": "page-2"}]), - iter([{"id": "last"}]), - ] - ) - monkeypatch.setattr(listing_fs, "_gdrive_list", list_query) - result = listing_fs._gdrive_list_ids(parents()) - assert consumed == [] - list_query.assert_not_called() - - assert next(result)["id"] == "page-1" - assert len(consumed) == 50 - assert next(result)["id"] == "page-2" - assert list_query.call_count == 1 - assert list(result) == [{"id": "last"}] - assert len(consumed) == 51 - assert list_query.call_count == 2 diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index f600431..08055fb 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -1,8 +1,11 @@ import errno +import gc import json import re import tempfile +import tracemalloc from concurrent.futures import ThreadPoolExecutor +from itertools import pairwise from threading import Event from urllib.parse import urlsplit @@ -11,6 +14,7 @@ from google.oauth2 import service_account from google.oauth2.credentials import Credentials from googleapiclient.http import DEFAULT_CHUNK_SIZE +from httplib2 import Response from pydrive2.fs import GDriveFileSystem from pydrive2.fs.spec import FOLDER_MIME_TYPE @@ -287,6 +291,10 @@ def test_find_wide_directory(mock_drive, detail): ) calls = requests[before:] assert len(calls) == expected_calls + for req in calls: + fields = query(req)["fields"][0] + assert ("size" in fields) == detail + assert ("md5Checksum" in fields) == detail batches = [ re.findall(r"'([^']+)' in parents", query(req)["q"][0]) for req in calls @@ -298,6 +306,105 @@ def test_find_wide_directory(mock_drive, detail): ] +@pytest.fixture +def live_heap_bytes(): + def measure(): + gc.collect() + return tracemalloc.get_traced_memory()[0] + + tracing = tracemalloc.is_tracing() + if not tracing: + tracemalloc.start() + try: + yield measure + finally: + if not tracing: + tracemalloc.stop() + + +@pytest.mark.parametrize("operation", ["ls", "find"]) +def test_listing_a_hash_prefix_releases_file_names_and_ids( + mock_drive, operation, live_heap_bytes +): + # Either field alone takes about 1 MiB if retained for every file. + page = listing( + *( + { + "id": f"{i:01024x}", + "name": f"{i:01024d}", + "mimeType": "text/plain", + } + for i in range(1000) + ) + ) + drive, requests = mock_drive(listing(folder("ab", "A")), listing(), page) + fs = filesystem(drive) + fs.ls("root") + scan = getattr(fs, operation) + assert scan("root/ab") == [] + + before = live_heap_bytes() + assert len(scan("root/ab")) == 1000 + assert live_heap_bytes() - before < 256 * 1024 + assert fs.exists("root/ab") + assert len(requests) == 3 + + +def test_ls_releases_file_ids_between_pages(mock_drive, live_heap_bytes): + pages = [] + for page in range(3): + items = [ + {"id": f"{i:08192x}", "name": str(i), "mimeType": "text/plain"} + for i in range(page * 128, (page + 1) * 128) + ] + data = {"files": items} + if page < 2: + data["nextPageToken"] = str(page + 1) + pages.append(response(data)) + + samples = [] + + def measure(request): + if "pageToken" in query(request): + samples.append(live_heap_bytes()) + + drive, _ = mock_drive(*pages, on_request=measure) + assert len(filesystem(drive).ls("root")) == 384 + first, second = samples + # Retaining another page of IDs would add 1 MiB. + assert second - first < 512 * 1024 + + +@pytest.mark.parametrize("operation", ["remove", "rename"]) +def test_folder_mutations_release_old_names_under_duplicate_parents( + mock_drive, live_heap_bytes, operation +): + # Long names make a retained entry distinguishable from test overhead. + names = [f"folder-{i}-" + "x" * 1024 for i in range(65)] + replies = [listing(folder("dup", "A"), folder("dup", "B"))] + for i, (old, new) in enumerate(pairwise(names)): + if operation == "rename": + replies.append(listing()) # The destination does not exist. + item_id = "D" if operation == "rename" else f"D{i}" + replies.append(listing(dict(folder(old, item_id), parents=["A"]))) + replies.append( + response(folder(new, item_id) if operation == "rename" else {}) + ) + drive, requests = mock_drive(*replies) + fs = filesystem(drive, trash_only=False) + fs.ls("root") + for old, new in pairwise(names): + if operation == "rename": + fs.mv(f"root/dup/{old}", f"root/dup/{new}") + else: + fs.rm_file(f"root/dup/{old}") + assert len(requests) == len(replies) + + before = live_heap_bytes() + fs.invalidate_cache() + assert before - live_heap_bytes() < 32 * 1024 + + @pytest.mark.parametrize("operation", ["find", "expand_path"]) @pytest.mark.parametrize("maxdepth", [1, 2, 3]) def test_bounded_traversal_from_root(mock_drive, operation, maxdepth): @@ -423,6 +530,198 @@ def test_recursive_remove_does_not_relist_each_directory(mock_drive): assert all("q" in query(req) for req in requests[:4]) +def batch_child(parent): + return { + "id": f"file-{parent}", + "name": parent, + "mimeType": "text/plain", + "parents": [parent], + } + + +@pytest.mark.parametrize("count", [1, 50, 51, 100, 251]) +def test_ls_queries_each_duplicate_folder_once_in_batches(mock_drive, count): + ids = [f"dir-{i}" for i in range(count)] + batches = [ids[i : i + 50] for i in range(0, count, 50)] + drive, requests = mock_drive( + listing(*(folder("dup", i) for i in ids)), + *(listing(*map(batch_child, batch)) for batch in batches), + ) + assert filesystem(drive).ls("root/dup") == [f"root/dup/{i}" for i in ids] + assert "name='dup'" in query(requests[0])["q"][0] + assert [ + re.findall(r"'([^']+)' in parents", query(req)["q"][0]) + for req in requests[1:] + ] == batches + + +@pytest.mark.parametrize("warmup", ["ls", "find"]) +def test_listed_duplicate_parents_reuse_their_child_folders( + mock_drive, warmup +): + sub = dict(folder("sub", "S"), parents=["left"]) + file = { + "name": "sub", + "id": "F", + "mimeType": "text/plain", + "parents": ["right"], + } + page = listing(sub, file) + drive, requests = mock_drive( + listing(folder("dup", "left"), folder("dup", "right")), + page, + listing(), + page, + listing(), + page, + response(file), + ) + fs = filesystem(drive) + for _ in range(2): + if warmup == "ls": + fs.ls("root/dup") + else: + fs.find("root/dup", maxdepth=1) + before = len(requests) + assert fs.ls("root/dup/sub") == [] + (children,) = requests[before:] + assert query(children)["q"] == ["('S' in parents) and trashed=false"] + + assert fs.info("root/dup/sub")["type"] == "file" + assert "name='sub'" in query(requests[-2])["q"][0] + assert urlsplit(requests[-1][0]).path.endswith("/files/F") + + +def test_incomplete_relisting_rechecks_children_of_duplicate_parents( + mock_drive, +): + first = dict(folder("sub", "S"), parents=["left"]) + second = folder("sub", "T") + drive, requests = mock_drive( + listing(folder("dup", "left"), folder("dup", "right")), + listing(first), + listing(first, second), # Drive hides the second folder's parent. + listing(first, dict(second, parents=["right"])), + listing(), + ) + fs = filesystem(drive) + fs.ls("root/dup") + fs.ls("root/dup") + assert fs.ls("root/dup/sub") == [] + assert "name='sub'" in query(requests[-2])["q"][0] + assert query(requests[-1])["q"] == [ + "('S' in parents or 'T' in parents) and trashed=false" + ] + + +def test_ls_missing_folder_only_queries_its_name(mock_drive): + drive, requests = mock_drive(listing()) + with pytest.raises(FileNotFoundError) as exc: + filesystem(drive).ls("root/dup") + assert exc.value.errno == errno.ENOENT + (request,) = requests + assert "name='dup'" in query(request)["q"][0] + + +def paged_duplicate_folders(mock_drive, last_page, *more): + return mock_drive( + listing(*(folder("dup", f"dir-{i}") for i in range(51))), + response({"files": [batch_child("dir-0")], "nextPageToken": "second"}), + last_page, + *more, + ) + + +def test_ls_finishes_all_pages_before_requesting_the_next_batch(mock_drive): + drive, requests = paged_duplicate_folders( + mock_drive, + listing(batch_child("dir-1")), + listing(batch_child("dir-50")), + ) + assert filesystem(drive).ls("root/dup") == [ + "root/dup/dir-0", + "root/dup/dir-1", + "root/dup/dir-50", + ] + _, first, second, last = requests + assert query(second)["q"] == query(first)["q"] + assert query(second)["pageToken"] == ["second"] + assert query(last)["q"] == ["('dir-50' in parents) and trashed=false"] + + +def test_ls_stops_before_the_next_batch_if_a_page_is_incomplete(mock_drive): + drive, requests = paged_duplicate_folders( + mock_drive, + response({"files": [batch_child("dir-1")], "incompleteSearch": True}), + ) + with pytest.raises(OSError, match="Incomplete Drive listing"): + filesystem(drive).ls("root/dup") + _, first, second = requests + assert query(second)["q"] == query(first)["q"] + assert query(second)["pageToken"] == ["second"] + + +@pytest.mark.parametrize( + ("detail", "fields", "expected"), + [ + ( + False, + "id,name,parents,mimeType", + ["root/initial", "root/final/", "root/final"], + ), + ( + True, + "id,name,parents,mimeType,size,md5Checksum", + [ + { + "name": "root/initial", + "type": "file", + "size": 1, + "checksum": "old", + }, + {"name": "root/final/", "type": "directory", "size": 0}, + { + "name": "root/final", + "type": "file", + "size": 2, + "checksum": "new", + }, + ], + ), + ], +) +def test_ls_requests_only_needed_fields_and_returns_rows_in_page_order( + mock_drive, detail, fields, expected +): + file = { + "id": "A", + "name": "initial", + "mimeType": "text/plain", + "size": "1", + "md5Checksum": "old", + } + updated = dict(file, name="final", size="2", md5Checksum="new") + directory = folder("final", "Z") + drive, requests = mock_drive( + response({"files": [file, directory], "nextPageToken": "next"}), + listing(updated), + listing(updated, directory), + ({"status": "200", "content-length": "1"}, b"x"), + ) + fs = filesystem(drive) + assert fs.ls("root", detail=detail) == expected + first, second = requests + assert ( + query(first)["fields"] + == query(second)["fields"] + == [f"nextPageToken,incompleteSearch,files({fields})"] + ) + assert query(second)["pageToken"] == ["next"] + with fs.open("root/final", "rb") as stream: + assert stream.read() == b"x" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + def test_ls_deduplicates_a_file_shared_across_parent_batches(mock_drive): parents = [f"parent-{i}" for i in range(51)] shared = { @@ -453,6 +752,94 @@ def test_ls_deduplicates_a_file_shared_across_parent_batches(mock_drive): ] == [parents[:50], parents[50:]] +def test_find_tracks_a_moved_file_that_now_shares_its_name_with_a_folder( + mock_drive, +): + parents = [folder(f"dir{i}", f"P{i}") for i in range(51)] + file = {"id": "A", "name": "item", "mimeType": "text/plain"} + moved = dict(file, parents=["P50"]) + directory = dict(folder("item", "Z"), parents=["P50"]) + drive, requests = mock_drive( + listing(*parents), + listing(dict(file, parents=["P0"])), + listing(moved, directory), + listing(moved, directory), + ({"status": "200", "content-length": "1"}, b"x"), + ) + fs = filesystem(drive) + assert fs.find("root", maxdepth=2) == ["root/dir50/item"] + with fs.open("root/dir50/item", "rb") as stream: + assert stream.read() == b"x" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + +@pytest.mark.parametrize("operation", ["ls", "find"]) +def test_warm_directory_listing_uses_one_request_when_a_file_shares_its_name( + mock_drive, operation +): + file = {"id": "A", "name": "data", "mimeType": "text/plain"} + drive, requests = mock_drive( + listing(file, folder("data", "Z")), + listing(dict(file, id="N", name="note")), + ) + fs = filesystem(drive) + fs.ls("root") + assert getattr(fs, operation)("root/data") == ["root/data/note"] + assert [query(r)["q"] for r in requests[1:]] == [ + ["('Z' in parents) and trashed=false"] + ] + + +@pytest.mark.parametrize("mount", ["root", "root/data", "root/data/sub"]) +def test_warm_calls_below_a_folder_with_a_same_name_file_reuse_its_id( + mock_drive, mount +): + data = folder("data", "D") + file = {"id": "A", "name": "data", "mimeType": "text/plain"} + sub = folder("sub", "S") + note = dict(file, id="N", name="note") + drive, requests = mock_drive( + listing(data, file), + listing(sub), + listing(note), + listing(note), + ({"status": "200", "location": "https://example.test/upload"}, ""), + response({"id": "uploaded"}), + ) + fs = filesystem(drive, mount) + assert fs.exists("root/data/sub/note") + before = len(requests) + fs.makedirs("root/data/sub", exist_ok=True) + assert len(requests) == before + assert fs.exists("root/data/sub/note") + assert [query(req)["q"] for req in requests[before:]] == [ + ["('S' in parents) and trashed=false and name='note'"] + ] + fs.touch("root/data/uploaded") + assert [req[1] for req in requests[before + 1 :]] == ["POST", "PUT"] + + +def test_find_caches_only_the_new_path_for_a_folder_moved_between_batches( + mock_drive, +): + parents = [folder(f"dir{i}", f"P{i}") for i in range(51)] + child = folder("before", "C") + drive, requests = mock_drive( + listing(*parents), + listing(dict(child, parents=["P0"])), + listing(dict(child, name="after", parents=["P50"])), + listing(), + ) + fs = filesystem(drive) + result = fs.find("root", maxdepth=2, withdirs=True) + assert "root/dir50/after" in result + assert "root/dir0/before" not in result + before = len(requests) + assert fs.exists("root/dir50/after") + assert len(requests) == before + assert not fs.exists("root/dir0/before") + + def test_ls_finishes_listing_parents_resolved_before_a_rename(mock_drive): parents = [folder("dir", f"id-{i}") for i in range(51)] renamed = dict(parents[-1], name="renamed") @@ -524,19 +911,422 @@ def test_ls_evicts_the_old_path_after_a_folder_rename(mock_drive): listing(folder("child", "C")), listing(folder("new", "D"), folder("new", "other")), listing(), - listing(folder("new", "D"), folder("new", "other")), listing({"id": "note", "name": "note", "mimeType": "text/plain"}), ) fs = filesystem(drive) assert fs.exists("root/old/child") assert fs.ls("root") == ["root/new/", "root/new/"] assert not fs.exists("root/old/child") + before = len(requests) assert fs.ls("root/new") == ["root/new/note"] + assert len(requests) == before + 1 assert set( re.findall(r"'([^']+)' in parents", query(requests[-1])["q"][0]) ) == {"D", "other"} +@pytest.mark.parametrize("duplicate_parents", [False, True]) +def test_second_open_of_a_name_shared_by_a_file_and_folder_reads_the_same_id( + mock_drive, duplicate_parents +): + parents = [folder("dup", "P"), folder("dup", "Q")] + file = {"id": "A", "name": "item", "mimeType": "text/plain"} + directory = folder("item", "Z") + if duplicate_parents: + file["parents"] = ["P"] + directory["parents"] = ["Q"] + found = listing(file, directory) + media = ({"status": "200", "content-length": "1"}, b"x") + drive, requests = mock_drive( + *([listing(*parents)] if duplicate_parents else []), + found, + media, + found, + media, + ) + fs = filesystem(drive) + path = "root/dup/item" if duplicate_parents else "root/item" + for _ in range(2): + with fs.open(path, "rb") as stream: + assert stream.read() == b"x" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + +@pytest.mark.parametrize("operation", ["ls", "find"]) +def test_fresh_listing_forgets_only_the_disappeared_folder( + mock_drive, operation +): + keep, gone = folder("keep", "K"), folder("gone", "G") + drive, requests = mock_drive( + listing(gone), listing(keep), listing(keep), listing() + ) + fs = filesystem(drive) + assert fs.exists("root/gone") + assert fs.exists("root/keep") + if operation == "find": + assert fs.find("root", maxdepth=1, withdirs=True) == [ + "root", + "root/keep", + ] + else: + assert fs.ls("root") == ["root/keep/"] + assert fs.exists("root/keep") + assert not fs.exists("root/gone") + assert len(requests) == 4 + assert "name='gone'" in query(requests[-1])["q"][0] + + +def test_repeated_stat_reuses_the_folder_after_a_same_name_file_is_removed( + mock_drive, +): + file = {"id": "A", "name": "item", "mimeType": "text/plain"} + directory = folder("item", "Z") + drive, requests = mock_drive( + listing(file, directory), + response({}), + listing(directory), + response(directory), + response(directory), + ) + fs = filesystem(drive) + fs.rm_file("root/item") + assert fs.info("root/item")["type"] == "directory" + before = len(requests) + assert fs.info("root/item")["type"] == "directory" + (metadata,) = requests[before:] + assert urlsplit(metadata[0]).path.endswith("/files/Z") + + +def test_local_rename_preserves_cached_child(mock_drive): + drive, requests = mock_drive( + listing(folder("old", "D")), + listing(folder("child", "C")), + listing(), + response(folder("new", "D")), + listing(folder("new", "D")), + listing(), + ) + fs = filesystem(drive) + assert fs.exists("root/old/child") + fs.mv("root/old", "root/new") + before = len(requests) + assert fs.exists("root/new/child") + assert len(requests) == before + 1 + assert "name='new'" in query(requests[-1])["q"][0] + assert not fs.exists("root/old/child") + + +def test_old_lookup_cannot_restore_folder_after_empty_listing(mock_drive): + def list_after_lookup_starts(request): + if "name='gone'" in query(request)["q"][0] and not requests: + assert fs.ls("root") == [] + + drive, requests = mock_drive( + listing(), + listing(folder("gone", "D")), + listing(), + on_request=list_after_lookup_starts, + ) + fs = filesystem(drive) + assert fs.exists("root/gone") + assert not fs.exists("root/gone") + assert len(requests) == 3 + + +WRITTEN_FILE = {"name": "item", "id": "A", "mimeType": "text/plain"} + + +@pytest.mark.parametrize( + ("write", "responses"), + [ + pytest.param( + lambda fs: fs.touch("root/dest/item"), + [ + ( + { + "status": "200", + "location": "https://example.test/upload", + }, + "", + ), + response(WRITTEN_FILE), + ], + id="touch", + ), + pytest.param( + lambda fs: fs.cp_file("root/source", "root/dest/item"), + [ + listing(dict(WRITTEN_FILE, name="source")), + response(WRITTEN_FILE), + ], + id="copy", + ), + pytest.param( + lambda fs: fs.mv("root/item", "root/dest"), + [ + listing(WRITTEN_FILE), + response({"parents": ["root"]}), + response(WRITTEN_FILE), + ], + id="move", + ), + ], +) +def test_file_written_beside_cached_folder_can_be_read( + mock_drive, write, responses +): + directory = folder("item", "Z") + drive, requests = mock_drive( + listing(folder("dest", "P")), + listing(directory), + *responses, + listing(WRITTEN_FILE, directory), + ({"status": "200", "content-length": "1"}, b"x"), + ) + fs = filesystem(drive) + assert fs.exists("root/dest/item") + write(fs) + with fs.open("root/dest/item", "rb") as stream: + assert stream.read() == b"x" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + +def test_renamed_duplicate_keeps_each_parents_children_warm(mock_drive): + left, right = folder("dup", "P"), folder("dup", "Q") + child = dict(folder("left", "L"), parents=["P"]) + sibling = dict(folder("right", "R"), parents=["Q"]) + drive, requests = mock_drive( + listing(left, right), + listing(child, sibling), + listing(dict(left, name="new"), right), + listing(), + ) + fs = filesystem(drive) + assert fs.find("root", maxdepth=2) == [] + assert fs.exists("root/dup/left") + fs.makedirs("root/dup/right", exist_ok=True) + assert len(requests) == 2 + fs.ls("root") + assert fs.exists("root/new/left") + assert fs.exists("root/dup/right") + assert len(requests) == 3 + assert not fs.exists("root/dup/left") + assert query(requests[-1])["q"] == [ + "('Q' in parents) and trashed=false and name='left'" + ] + + +@pytest.mark.parametrize("is_folder", [True, False], ids=["folder", "file"]) +def test_rename_rechecks_destination_after_parent_is_renamed( + mock_drive, is_folder +): + parent = folder("parent", "P") + renamed_parent = dict(parent, name="renamed") + source = folder("before", "A") + if not is_folder: + source["mimeType"] = "text/plain" + renamed = dict(source, name="after") + sibling = folder("after", "Z") + + def rename_parent(request): + if request[1] == "PATCH" and urlsplit(request[0]).path.endswith("/A"): + fs.mv("root/parent", "root/renamed") + fs.ls("root/renamed") + + drive, requests = mock_drive( + listing(parent), + listing(), + listing(source), + listing(), + response(renamed_parent), + listing(renamed_parent), + listing(source, sibling), + response(renamed), + listing(sibling, renamed), + response(renamed), + on_request=rename_parent, + ) + fs = filesystem(drive) + fs.mv("root/parent/before", "root/parent/after") + fs.info("root/renamed/after") + assert query(requests[-2])["q"] == [ + "('P' in parents) and trashed=false and name='after'" + ] + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + +def test_file_rename_rechecks_folder_discovered_during_the_move(mock_drive): + def list_destination(request): + if request[1] == "PATCH": + assert fs.ls("root") == ["root/new/"] + + old = {"id": "A", "name": "old", "mimeType": "text/plain"} + new = dict(old, name="new") + directory = folder("new", "Z") + drive, requests = mock_drive( + listing(), + listing(old), + listing(directory), + response(new), + listing(new, directory), + ({"status": "200", "content-length": "1"}, b"x"), + on_request=list_destination, + ) + fs = filesystem(drive) + fs.mv("root/old", "root/new") + with fs.open("root/new", "rb") as stream: + assert stream.read() == b"x" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + +@pytest.mark.parametrize("operation", ["exists", "ls", "find"]) +def test_failed_later_page_does_not_cache_partial_duplicate_matches( + mock_drive, operation +): + a, b = folder("dup", "A"), folder("dup", "B") + drive, requests = mock_drive( + response({"files": [a], "nextPageToken": "page2"}), + response({"files": [], "incompleteSearch": True}), + listing(a, b), + listing(), + ) + fs = filesystem(drive) + with pytest.raises(OSError, match="Incomplete Drive listing"): + if operation == "exists": + fs.exists("root/dup") + else: + getattr(fs, operation)("root") + assert fs.ls("root/dup") == [] + assert len(requests) == 4 + assert query(requests[1])["pageToken"] == ["page2"] + assert "'A' in parents or 'B' in parents" in query(requests[-1])["q"][0] + + +@pytest.mark.parametrize( + ("actual_parent", "max_probes"), [("P0", 1), ("P24", 8), ("P49", 7)] +) +def test_find_bounds_requests_to_locate_one_item_without_parents( + mock_drive, mocker, actual_parent, max_probes +): + folders = [folder(f"dir{i}", f"P{i}") for i in range(50)] + note = {"id": "N", "name": "note", "mimeType": "text/plain"} + drive, _ = mock_drive() + queries = [] + + def list_files(uri, method="GET", **kwargs): + assert method == "GET" + q = query((uri,))["q"][0] + parents = re.findall(r"'([^']+)' in parents", q) + queries.append(q) + if parents == ["root"]: + items = folders + else: + items = [note] if actual_parent in parents else [] + return Response({"status": "200"}), json.dumps( + {"files": items} + ).encode() + + mocker.patch.object( + drive.auth.thread_local.http, "request", side_effect=list_files + ) + assert filesystem(drive).find("root") == [ + f"root/dir{actual_parent[1:]}/note" + ] + assert 1 <= len(queries) - 2 <= max_probes + assert all("name='note'" in q for q in queries[2:]) + + +def test_find_places_items_without_parents_by_name_and_id(mock_drive): + a, b = folder("a", "A"), folder("b", "B") + one = {"id": "1", "name": "one", "mimeType": "text/plain"} + two = dict(one, id="2", name="two") + drive, requests = mock_drive( + listing(a, b), + listing(one, two), + listing(one, dict(two, id="unrelated")), + listing(two), + ) + assert filesystem(drive).find("root") == ["root/a/one", "root/b/two"] + assert [query(r)["q"][0] for r in requests[2:]] == [ + "('A' in parents) and trashed=false and (name='one' or name='two')", + "('B' in parents) and trashed=false and name='two'", + ] + + +def test_find_places_two_items_without_parents_in_different_folders( + mock_drive, +): + one = {"id": "1", "name": "one", "mimeType": "text/plain"} + two = dict(one, id="2", name="two") + drive, requests = mock_drive( + listing(*(folder(name, name.upper()) for name in "abcd")), + listing(one, two), + listing(), + listing(one), + listing(), + listing(two), + ) + assert filesystem(drive).find("root") == ["root/b/one", "root/d/two"] + assert len(requests) == 6 + + +def test_find_bounds_the_query_for_many_items_without_parents(mock_drive): + items = [ + {"id": str(i), "name": f"file-{i}", "mimeType": "text/plain"} + for i in range(51) + ] + drive, requests = mock_drive( + listing(folder("a", "A"), folder("b", "B")), + listing(*items), + listing(*items), + ) + assert filesystem(drive).find("root") == sorted( + f"root/a/{item['name']}" for item in items + ) + assert len(requests) == 3 + assert query(requests[-1])["q"] == ["('A' in parents) and trashed=false"] + + +def test_find_omits_a_file_that_disappears_between_pages(mock_drive): + note = {"id": "N", "name": "note", "mimeType": "text/plain"} + drive, requests = mock_drive( + listing(folder("a", "A"), folder("b", "B")), + response( + {"files": [dict(note, parents=["A"])], "nextPageToken": "next"} + ), + listing(note), + listing(), + listing(), + ) + assert filesystem(drive).find("root") == [] + assert [query(req)["q"][0] for req in requests[-2:]] == [ + "('A' in parents) and trashed=false and name='note'", + "('B' in parents) and trashed=false and name='note'", + ] + + +def test_find_keeps_cached_folders_when_items_without_parents_disappear( + mock_drive, +): + a, b = (dict(folder(n, n.upper()), parents=["root"]) for n in ("a", "b")) + item = folder("renamed", "C") + drive, requests = mock_drive( + listing(a, b), + listing(folder("old", "C")), + listing(a, b, item), + listing(), + listing(), + listing(), + ) + fs = filesystem(drive) + fs.ls("root") + assert fs.exists("root/a/old") + assert fs.find("root", maxdepth=2) == [] + before = len(requests) + assert fs.exists("root/a/old") + assert len(requests) == before + + def test_ls_started_before_invalidation_cannot_evict_a_new_lookup(mock_drive): def refresh_during_listing(request): if query(request)["q"] == ["('root' in parents) and trashed=false"]: @@ -637,6 +1427,47 @@ def test_find_matches_legacy_parent_before_assuming_root(mock_drive): assert fs.find("root") == ["root/sub/child"] +def test_ls_warms_folders_alongside_a_shared_file(mock_drive): + sibling = folder("item", "Z") + shared = dict(WRITTEN_FILE, parents=["root", "another-parent"]) + drive, requests = mock_drive( + listing(shared, sibling, folder("child", "C")), + listing(sibling, shared), + response(shared), + ) + fs = filesystem(drive) + assert fs.ls("root") == ["root/item", "root/item/", "root/child/"] + assert fs.exists("root/child") + assert len(requests) == 1 + assert fs.info("root/item")["type"] == "file" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + +def test_ambiguous_parent_row_cannot_hide_a_file_at_the_root_alias(mock_drive): + sub = dict(folder("sub", "P"), parents=["canonical-root"]) + directory = dict(folder("item", "Z"), parents=["canonical-root"]) + file = { + "name": "item", + "id": "A", + "mimeType": "text/plain", + "parents": ["canonical-root", "P"], + } + drive, requests = mock_drive( + listing(sub), + listing(sub, directory, file), + listing(), + listing(directory, file), + ({"status": "200", "content-length": "1"}, b"x"), + ) + fs = filesystem(drive) + assert fs.exists("root/sub") + assert fs.find("root", maxdepth=2) == ["root/sub/item"] + with fs.open("root/item", "rb") as stream: + assert stream.read() == b"x" + assert "name='item'" in query(requests[-2])["q"][0] + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + @pytest.mark.parametrize("operation", ["trash", "rename"]) def test_directory_mutation_evicts_descendants_only(mock_drive, operation): moved = folder("renamed", "dir-id") @@ -671,6 +1502,148 @@ def test_directory_mutation_evicts_descendants_only(mock_drive, operation): assert len(requests) == before +def test_move_rechecks_the_physical_destination_when_its_path_was_uncached( + mock_drive, +): + duplicate_parents = listing(folder("dup", "P"), folder("dup", "R")) + q, t = folder("q", "Q"), folder("t", "T") + cached, arriving = folder("x", "X"), folder("x", "N") + # Drive returns q below one of the two dup folders without exposing which + # one. The move can use Q and T even while q's path cannot be cached. + hidden_parent = listing(q) + move_t = [ + hidden_parent, + hidden_parent, + response({"parents": ["root"]}), + response(t), + ] + move_x = [ + hidden_parent, + listing(t), + hidden_parent, + listing(arriving), + hidden_parent, + listing(t), + response({"parents": ["Q"]}), + response(arriving), + ] + drive, requests = mock_drive( + listing(t), + listing(cached), + duplicate_parents, + *move_t, + *move_x, + listing(dict(q, parents=["P"])), + listing(t), + listing(cached, arriving), + response({}), + ) + fs = filesystem(drive) + assert fs.exists("root/t/x") + assert fs.exists("root/dup") + fs.mv("root/t", "root/dup/q") + fs.mv("root/dup/q/x", "root/dup/q/t") + fs.rm_file("root/dup/q/t/x") + assert urlsplit(requests[-1][0]).path.endswith("/files/N") + assert query(requests[-2])["q"] == [ + "('T' in parents) and trashed=false and name='x'" + ] + + +def test_invalidate_after_move_to_a_folder_with_hidden_parent(mock_drive): + parents = listing(folder("dup", "P"), folder("dup", "R")) + target = folder("q", "Q") + moved = folder("t", "T") + drive, requests = mock_drive( + listing(moved), + listing(folder("x", "X")), + parents, + listing(target), + listing(target), + response({"parents": ["root"]}), + response(moved), + parents, + listing(dict(target, parents=["P"])), + listing(moved), + listing(), + ) + fs = filesystem(drive) + assert fs.exists("root/t/x") + fs.mv("root/t", "root/dup/q") + # Another client deletes x before this branch is rediscovered. + fs.invalidate_cache("root/dup") + assert fs.exists("root/dup/q/t") + assert not fs.exists("root/dup/q/t/x") + assert query(requests[-1])["q"] == [ + "('T' in parents) and trashed=false and name='x'" + ] + + +def test_listing_after_parent_and_child_swap_places(mock_drive): + a, b = folder("a", "A"), folder("b", "B") + drive, requests = mock_drive( + listing(a), + listing(b, folder("gone", "X")), + listing(a), # Drive now has root/b/a and has removed gone. + listing(b), + listing(a), + listing(), + ) + fs = filesystem(drive) + fs.ls("root/a") + assert fs.ls("root/a/b") == ["root/a/b/a/"] + fs.invalidate_cache("root/a") + assert fs.ls("root/b") == ["root/b/a/"] + assert not fs.exists("root/b/a/gone") + assert query(requests[-1])["q"] == [ + "('A' in parents) and trashed=false and name='gone'" + ] + + +def test_find_keeps_folders_warm_after_observing_both_sides_of_a_move( + mock_drive, +): + a, b = folder("a", "A"), folder("b", "B") + drive, requests = mock_drive( + listing(a), + listing(b), + listing(dict(a, parents=["B"]), dict(b, parents=["root"])), + ) + fs = filesystem(drive) + assert fs.exists("root/a/b") + assert fs.find("root", withdirs=True) == ["root", "root/b", "root/b/a"] + assert fs.exists("root/b/a") + assert len(requests) == 3 + + +def test_move_into_a_folder_that_shares_its_name_with_a_file(mock_drive): + dest = folder("dest", "Z") + file = {"id": "A", "name": "dest", "mimeType": "text/plain"} + source = dict(file, id="source", name="source", parents=["root"]) + drive, requests = mock_drive( + listing(file, dest), + listing(source), + response({"parents": ["root"]}), + response(source), + ) + fs = filesystem(drive) + fs.ls("root") + fs.mv("root/source", "root/dest") + update = requests[-1] + assert update[1] == "PATCH" + assert query(update)["addParents"] == ["Z"] + assert len(requests) == 4 + + +def test_move_rejects_a_file_as_the_destination_parent(mock_drive): + file = {"id": "A", "name": "dest", "mimeType": "text/plain"} + source = dict(file, id="source", name="source") + drive, requests = mock_drive(listing(file), listing(source), listing(file)) + with pytest.raises(NotADirectoryError): + filesystem(drive).mv("root/source", "root/dest") + assert all(r[1] == "GET" for r in requests) + + def test_move_directory_to_implicit_root(mock_drive): moved = folder("dir", "dir-id") drive, requests = mock_drive( @@ -831,6 +1804,9 @@ def copy(fs, http, name): release.set() pending.result(timeout=5) + assert first.exists("root/one") + assert (other if other_instance else first).exists("root/two") + @pytest.mark.parametrize("trash_only", [True, False]) def test_rmdir_after_external_rename_forgets_the_old_path( @@ -1152,8 +2128,281 @@ def test_rmdir_checks_emptiness_again_after_transient_failure(mock_drive): assert [r[1] for r in requests] == ["GET", "GET", "DELETE", "GET"] -def test_concurrent_copies_share_a_folder_after_unrelated_invalidation( +def test_upload_while_mkdir_is_waiting_for_drive_keeps_both_matches( mock_drive, +): + started, release = Event(), Event() + + def pause_create(request): + if request[1] == "POST": + 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( + ({"status": "200", "location": "https://example.test/upload"}, ""), + response(file), + listing(file, directory), + ({"status": "200", "content-length": "1"}, b"x"), + ) + fs = filesystem(drive) + http = creator.auth.thread_local.http + + def create(): + drive.auth.thread_local.http = http + fs.mkdir("root/item") + + with ThreadPoolExecutor(max_workers=1) as pool: + pending = pool.submit(create) + try: + assert started.wait(5) + fs.touch("root/item") + finally: + release.set() + pending.result(timeout=5) + + with fs.open("root/item", "rb") as stream: + assert stream.read() == b"x" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + +def overlap_requests( + mock_drive, *, first, first_responses, pause_on, second, second_responses +): + """Finish the first operation while the second awaits its Drive response.""" + started, release = Event(), Event() + + def pause(request): + if pause_on(request): + started.set() + assert release.wait(5) + + def finish(request): + release.set() + pending.result(timeout=5) + + writer, _ = mock_drive(*first_responses, on_request=pause) + reader, requests = mock_drive(*second_responses, on_request=finish) + write_http = writer.auth.thread_local.http + + def run(): + fs.client.auth.thread_local.http = write_http + first(fs) + + fs = filesystem(reader) + with ThreadPoolExecutor(max_workers=1) as pool: + pending = pool.submit(run) + try: + assert started.wait(5) + second(fs) + finally: + release.set() + pending.result(timeout=5) + return fs, requests + + +def test_folder_retired_before_its_children_arrive_cannot_warm_the_new_path( + mock_drive, +): + def retire(fs): + assert fs.exists("root/old") + assert fs.ls("root") == [] + + def list_children(fs): + assert fs.ls("root/old") == ["root/old/child/"] + + fs, _ = overlap_requests( + mock_drive, + first=retire, + first_responses=[listing(folder("old", "D")), listing()], + pause_on=lambda req: ( + query(req).get("q") == ["('root' in parents) and trashed=false"] + ), + second=list_children, + second_responses=[ + listing(folder("child", "C")), + listing(folder("new", "D")), + listing(), + ], + ) + assert fs.exists("root/new") + assert not fs.exists("root/new/child") + + +def test_late_lookup_cannot_reattach_an_id_retired_under_another_parent( + mock_drive, +): + def retire(request): + if ( + "name='previous'" in query(request).get("q", [""])[0] + and len(requests) == 2 + ): + assert fs.ls("root/p") == [] + + drive, requests = mock_drive( + listing(folder("p", "P")), + listing(folder("current", "D")), + listing(), + listing(folder("previous", "D")), + listing(), + on_request=retire, + ) + fs = filesystem(drive) + assert fs.exists("root/p/current") + assert fs.exists("root/previous") + assert not fs.exists("root/previous") + + +def test_listing_started_during_create_cannot_evict_the_new_folder(mock_drive): + def read(fs): + assert fs.ls("root") == [] + + fs, requests = overlap_requests( + mock_drive, + first=lambda fs: fs.mkdir("root/item"), + first_responses=[listing(), response(folder("item", "A"))], + pause_on=lambda req: req[1] == "POST", + second=read, + second_responses=[listing(), listing(folder("item", "A"))], + ) + before = len(requests) + assert fs.exists("root/item") + assert len(requests) == before + + +def test_create_rechecks_a_sibling_discovered_during_the_folder_post( + mock_drive, +): + sibling, created = folder("item", "Z"), folder("item", "A") + + def see_sibling(request): + if request[1] == "POST": + assert fs.ls("root") == ["root/item/"] + + drive, requests = mock_drive( + listing(), + listing(sibling), + response(created), + listing(sibling, created), + response(created), + on_request=see_sibling, + ) + fs = filesystem(drive) + fs.mkdir("root/item") + assert fs.info("root/item")["type"] == "directory" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + +def test_listing_started_before_move_cannot_hide_the_arriving_folder( + mock_drive, +): + dest, moved, other = ( + folder("dest", "P"), + folder("item", "A"), + folder("item", "Z"), + ) + + def move(request): + if query(request).get("q") == ["('P' in parents) and trashed=false"]: + fs.mv("root/item", "root/dest") + + drive, requests = mock_drive( + listing(dest, moved), + response({"parents": ["root"]}), + response(moved), + listing(other), + listing(other, moved), + response(moved), + on_request=move, + ) + fs = filesystem(drive) + fs.ls("root") + assert fs.ls("root/dest") == ["root/dest/item/"] + assert fs.info("root/dest/item")["type"] == "directory" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + +def test_delayed_lookup_caches_neither_the_old_name_nor_its_children( + mock_drive, +): + def observe_new_name(request): + if "name='old'" in query(request)["q"][0] and not requests: + assert fs.exists("root/new") + + drive, requests = mock_drive( + listing(folder("new", "D")), + listing(folder("old", "D")), + listing(folder("child", "C")), + listing(), + listing(), + on_request=observe_new_name, + ) + fs = filesystem(drive) + assert fs.exists("root/old/child") + assert not fs.exists("root/old") + assert fs.exists("root/new") + assert not fs.exists("root/new/child") + assert len(requests) == 5 + + +@pytest.mark.parametrize("older_finishes_first", [True, False]) +def test_newer_listing_determines_which_id_a_warm_read_uses( + mock_drive, older_finishes_first +): + file = {"id": "A", "name": "item", "mimeType": "text/plain"} + current, stale = folder("item", "CURRENT"), folder("item", "STALE") + path = "root/item" + media = ({"status": "200", "content-length": "1"}, b"x") + drive, requests = mock_drive( + listing(current, file), listing(current, file), media + ) + fs = filesystem(drive) + fs.ls("root") + + def start(pool, items): + started, release = Event(), Event() + + def hold_lookup(request): + if "q" in query(request): + started.set() + assert release.wait(5) + + worker, _ = mock_drive(listing(*items), media, on_request=hold_lookup) + http = worker.auth.thread_local.http + + def read(): + drive.auth.thread_local.http = http + with fs.open(path, "rb") as stream: + return stream.read() + + result = pool.submit(read) + assert started.wait(5) + return release, result + + with ThreadPoolExecutor(max_workers=2) as pool: + older = start(pool, [stale]) + newer = start(pool, [file, current]) + first, second = ( + (older, newer) if older_finishes_first else (newer, older) + ) + try: + first[0].set() + assert first[1].result(timeout=5) == b"x" + finally: + second[0].set() + assert second[1].result(timeout=5) == b"x" + with fs.open(path, "rb") as stream: + assert stream.read() == b"x" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + +@pytest.mark.parametrize("invalidate", [False, True]) +def test_concurrent_copies_create_their_shared_folder_once( + mock_drive, invalidate ): creating, release = Event(), Event() second_started, second_lookup = Event(), Event() @@ -1180,7 +2429,7 @@ def observe_lookup(request): ) second, second_requests = mock_drive( listing(source), - listing(folder("ab", "AB")), + *([listing(folder("ab", "AB"))] if invalidate else []), response({"id": "second-copy"}), on_request=observe_lookup, ) @@ -1194,7 +2443,8 @@ def copy(http, name): one = pool.submit(copy, first.auth.thread_local.http, "one") try: assert creating.wait(5) - fs.invalidate_cache("root/ef") + if invalidate: + fs.invalidate_cache("root/ef") two = pool.submit(copy, second.auth.thread_local.http, "two") assert second_started.wait(5) # Drive cannot return the new folder until the first create finishes. @@ -1207,7 +2457,9 @@ def copy(http, name): for requests in (first_requests, second_requests): assert json.loads(requests[-1][2])["parents"] == ["AB"] assert [r[1] for r in first_requests] == ["GET", "GET", "POST", "POST"] - assert [r[1] for r in second_requests] == ["GET", "GET", "POST"] + assert [r[1] for r in second_requests] == ( + ["GET", "GET", "POST"] if invalidate else ["GET", "POST"] + ) def test_invalidating_an_unopened_mount_needs_no_drive_request(mock_drive): @@ -1819,6 +3071,22 @@ def test_missing_mount_discards_cached_children( assert all("q" not in query(req) for req in requests[2:]) +def test_exists_rechecks_a_removed_mount_before_using_a_cached_folder( + mock_drive, +): + drive, requests = mock_drive( + listing(folder("mount", "M")), + listing(folder("other", "O")), + response({"trashed": True}), + listing(), + ) + fs = filesystem(drive, "root/mount") + assert fs.exists("root/other") + fs.rm_file("root/mount") + assert not fs.exists("root/other") + assert "name='mount'" in query(requests[-1])["q"][0] + + def test_makedirs_after_trashing_and_restoring_the_mount(mock_drive): root = {"mimeType": FOLDER_MIME_TYPE} drive, _ = mock_drive(