Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions docs/fsspec.rst
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,29 @@ A filesystem instance is scoped to one root. Use URLs under the same folder
ID or root alias in a single ``fsspec.open_files`` call. Sibling URLs reuse
the filesystem and its directory ID cache. Reads by file ID skip name
lookups. Reads are sequential. To create a file, use a folder ID or root
alias followed by a filename. As with the direct PyDrive2 filesystem,
a write creates a Drive item even when a sibling has the same name. All
reads require credentials, including files shared by link.
alias followed by a filename. All reads require credentials, including
files shared by link.

.. _fsspec-writing-files:

Writing files
-------------

A write replaces the content of a file at that path that the filesystem
knows, and keeps the file, with its ID, type and sharing. The filesystem
knows the latest 10,000 files it wrote or copied, or found by their path,
for example with ``exists()``, ``info()`` or a read. Listings do not count.
Any other write creates a new file without asking Drive first, even if a
file with that name exists. To replace a file that another client or an
earlier process wrote, call ``fs.exists(path)`` before writing.

Writing to the path of a known folder raises ``IsADirectoryError``, and to
the path of a known Google Docs file or shortcut ``PermissionError``. If
another client has removed, trashed, moved or renamed the known file, the
write sends the new content to that file and then creates a new file at the
path. Threads that write one path through the same filesystem instance take
turns. Other instances and other clients do not wait, so two of them can
still create two files with the same name.

Listings
--------
Expand Down Expand Up @@ -95,7 +115,9 @@ client moves, trashes, or deletes a folder, call
The next lookup checks Drive for all folders with that name, including any
same-name folder that still exists.

Only folder IDs are cached between calls. Both ``ls()`` and ``find()``
Between calls the filesystem keeps folder IDs and the files that writes
can replace (see `Writing files`_), about 350 bytes for each file.
``invalidate_cache()`` forgets those files. Both ``ls()`` and ``find()``
build their results in memory, so larger listings use more memory during
the call.

Expand Down
9 changes: 9 additions & 0 deletions docs/upgrading.rst
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ Filesystem directories
Both raise ``FileExistsError`` if the folder already exists. Use
``fs.makedirs(path, exist_ok=True)`` when repeating a setup step.

Writing with ``pipe_file()``, ``put_file()`` or ``open(path, "wb")`` to
the path of a file that the filesystem wrote, copied or found by that path
now replaces that file's content. It used to add a second file with the
same name. Other writes still create a file without asking Drive first, so
call ``fs.exists(path)`` before writing to replace a file that another
client or an earlier process wrote. Writing to the path of a known folder
raises ``IsADirectoryError``, and to the path of a known Google Docs file
or shortcut ``PermissionError``. See :ref:`fsspec-writing-files`.

The :doc:`fsspec filesystem <fsspec>` 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
Expand Down
84 changes: 82 additions & 2 deletions pydrive2/fs/cache.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"""Directory edges learned from Drive queries, scoped to one filesystem."""

from collections import defaultdict
from collections import OrderedDict, defaultdict
from contextlib import contextmanager
from itertools import count
from threading import RLock
from threading import Lock, RLock
from typing import NamedTuple


Expand Down Expand Up @@ -208,6 +208,13 @@ def has_directory(self, path, mount):
for parent in parents
)

def has_child_folder(self, parents, name):
"""Whether a folder of this name is known under one of these parents."""
with self.lock:
return any(
self.children.get(parent, {}).get(name) for parent in parents
)

def _parents_of_path(self, path):
parent, _, name = path.rpartition("/")
return self._known_folder_ids(parent), name
Expand Down Expand Up @@ -432,3 +439,76 @@ def _relink(self, groups, revision):
for (parent, name), leaving in moved.items():
self._unlink(parent, name, leaving)
return True


class KnownFiles:
"""The latest files written or found by path, by parent ID and name."""

def __init__(self, limit: int):
self.limit = limit
self._lock = Lock()
# Counts changes, so a lookup can tell which ones came after it began.
self.revision = 0
self._files: OrderedDict[
tuple[str, str], tuple[str, str | None, int]
] = OrderedDict()
# The revision of the latest removal under each name.
self._removed: OrderedDict[tuple[str, str], int] = OrderedDict()

def add(self, parent, name, file_id, mime_type):
"""Remember a file; it does not displace a lower ID, as reads pick."""
with self._lock:
self._add((parent, name), file_id, mime_type)

def found(self, parents, name, files, revision):
"""Record a lookup's answer in one step, so readers see all or none.

It replaces what was known under each parent it read, except files
stored after the lookup started at this revision. A file removed
since then stays forgotten.
"""
with self._lock:
for parent in parents:
known = self._files.get((parent, name))
if known is not None and known[2] <= revision:
del self._files[parent, name]
for parent, file_id, mime_type in files:
if self._removed.get((parent, name), 0) <= revision:
self._add((parent, name), file_id, mime_type)

def _add(self, key, file_id, mime_type):
known = self._files.get(key)
if known is None or file_id < known[0]:
self.revision += 1
self._files[key] = (file_id, mime_type, self.revision)
self._files.move_to_end(key)
if len(self._files) > self.limit:
self._files.popitem(last=False)

def get(self, parents, name):
"""Return (ID, type, parent) of the lowest known ID, as reads pick."""
found: list[tuple[str, str | None, str]] = []
with self._lock:
for parent in parents:
key = (parent, name)
if key in self._files:
self._files.move_to_end(key)
file_id, mime_type, _ = self._files[key]
found.append((file_id, mime_type, parent))
return min(found, default=None)

def discard(self, parent, name):
"""Forget a file, and when, so an older lookup cannot bring it back."""
key = (parent, name)
with self._lock:
self._files.pop(key, None)
self.revision += 1
self._removed[key] = self.revision
self._removed.move_to_end(key)
if len(self._removed) > self.limit:
self._removed.popitem(last=False)

def clear(self):
with self._lock:
self._files.clear()
self._removed.clear()
Loading
Loading