-
Notifications
You must be signed in to change notification settings - Fork 33
Add persistent sqlite3-backed API metadata cache #1815
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
bendichter
wants to merge
2
commits into
master
Choose a base branch
from
enh/api-cache
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| """Persistent sqlite3-backed cache for DANDI API metadata responses. | ||
|
|
||
| The cache stores metadata keyed by ``(api_url, entity_type, entity_id)`` and | ||
| validates entries against a *modified* timestamp so that stale data is | ||
| automatically discarded without extra API calls. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import os | ||
| from pathlib import Path | ||
| import sqlite3 | ||
|
|
||
| from platformdirs import user_cache_dir | ||
|
|
||
| from . import get_logger | ||
|
|
||
| lgr = get_logger() | ||
|
|
||
| _SCHEMA = """\ | ||
| CREATE TABLE IF NOT EXISTS metadata_cache ( | ||
| api_url TEXT NOT NULL, | ||
| entity_type TEXT NOT NULL, | ||
| entity_id TEXT NOT NULL, | ||
| modified TEXT NOT NULL, | ||
| metadata TEXT NOT NULL, | ||
| PRIMARY KEY (api_url, entity_type, entity_id) | ||
| ); | ||
| """ | ||
|
|
||
|
|
||
| class APIMetadataCache: | ||
| """A lightweight, persistent metadata cache backed by sqlite3. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| db_path : Path or None | ||
| Explicit path for the sqlite database. When *None* (the default) the | ||
| database is placed under ``platformdirs.user_cache_dir("dandi")``. | ||
| """ | ||
|
|
||
| def __init__(self, db_path: Path | None = None) -> None: | ||
| if db_path is None: | ||
| db_path = Path(user_cache_dir("dandi")) / "api_metadata_cache.sqlite" | ||
| db_path.parent.mkdir(parents=True, exist_ok=True) | ||
| self._db_path = db_path | ||
|
|
||
| dandi_cache = os.environ.get("DANDI_CACHE", "").lower() | ||
| if dandi_cache == "ignore": | ||
| lgr.debug("DANDI_CACHE=ignore: API metadata cache disabled") | ||
| self._enabled = False | ||
| return | ||
|
|
||
| self._enabled = True | ||
| self._con = sqlite3.connect(str(db_path), check_same_thread=False) | ||
| self._con.execute("PRAGMA journal_mode=WAL;") | ||
| self._con.execute(_SCHEMA) | ||
| self._con.commit() | ||
|
|
||
| if dandi_cache == "clear": | ||
| lgr.debug("DANDI_CACHE=clear: clearing API metadata cache") | ||
| self.clear() | ||
|
|
||
| # ------------------------------------------------------------------ | ||
| # Public API | ||
| # ------------------------------------------------------------------ | ||
|
|
||
| def get( | ||
| self, | ||
| api_url: str, | ||
| entity_type: str, | ||
| entity_id: str, | ||
| modified: str, | ||
| ) -> dict | None: | ||
| """Return cached metadata if *modified* matches, else ``None``. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| api_url : str | ||
| Base URL of the DANDI API server. | ||
| entity_type : str | ||
| ``"dandiset"`` or ``"asset"``. | ||
| entity_id : str | ||
| Unique identifier for the entity (asset UUID, or | ||
| ``"<dandiset_id>/<version_id>"`` for Dandisets). | ||
| modified : str | ||
| ISO-8601 timestamp of the entity's last modification. A cache | ||
| hit is only returned when this value matches the stored entry. | ||
|
|
||
| Returns | ||
| ------- | ||
| dict or None | ||
| The cached metadata dict, or ``None`` on a cache miss. | ||
| """ | ||
| if not self._enabled: | ||
| return None | ||
| row = self._con.execute( | ||
| "SELECT metadata FROM metadata_cache " | ||
| "WHERE api_url = ? AND entity_type = ? AND entity_id = ? AND modified = ?", | ||
| (api_url, entity_type, entity_id, modified), | ||
| ).fetchone() | ||
| if row is not None: | ||
| lgr.debug("API cache hit: %s %s %s", entity_type, entity_id, modified) | ||
| return json.loads(row[0]) # type: ignore[no-any-return] | ||
| return None | ||
|
|
||
| def set( | ||
| self, | ||
| api_url: str, | ||
| entity_type: str, | ||
| entity_id: str, | ||
| modified: str, | ||
| metadata: dict, | ||
| ) -> None: | ||
| """Insert or replace a cache entry. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| api_url : str | ||
| Base URL of the DANDI API server. | ||
| entity_type : str | ||
| ``"dandiset"`` or ``"asset"``. | ||
| entity_id : str | ||
| Unique identifier for the entity. | ||
| modified : str | ||
| ISO-8601 timestamp of the entity's last modification. | ||
| metadata : dict | ||
| The raw metadata dict to cache. | ||
| """ | ||
| if not self._enabled: | ||
| return | ||
| self._con.execute( | ||
| "INSERT OR REPLACE INTO metadata_cache " | ||
| "(api_url, entity_type, entity_id, modified, metadata) " | ||
| "VALUES (?, ?, ?, ?, ?)", | ||
| (api_url, entity_type, entity_id, modified, json.dumps(metadata)), | ||
| ) | ||
| self._con.commit() | ||
| lgr.debug("API cache set: %s %s %s", entity_type, entity_id, modified) | ||
|
|
||
| def clear(self) -> None: | ||
| """Delete all cached entries from the database.""" | ||
| if not self._enabled: | ||
| return | ||
| self._con.execute("DELETE FROM metadata_cache") | ||
| self._con.commit() | ||
| lgr.debug("API metadata cache cleared") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| """Tests for the persistent API metadata cache.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from pathlib import Path | ||
|
|
||
| import pytest | ||
|
|
||
| from dandi.apicache import APIMetadataCache | ||
|
|
||
|
|
||
| @pytest.mark.ai_generated | ||
| class TestAPIMetadataCache: | ||
| API_URL = "https://api.dandiarchive.org/api" | ||
|
|
||
| def test_cache_miss(self, tmp_path: Path) -> None: | ||
| cache = APIMetadataCache(db_path=tmp_path / "cache.sqlite") | ||
| result = cache.get(self.API_URL, "asset", "abc-123", "2024-01-01T00:00:00Z") | ||
| assert result is None | ||
|
|
||
| def test_set_then_get(self, tmp_path: Path) -> None: | ||
| cache = APIMetadataCache(db_path=tmp_path / "cache.sqlite") | ||
| metadata = {"name": "test-asset", "size": 42} | ||
| cache.set(self.API_URL, "asset", "abc-123", "2024-01-01T00:00:00Z", metadata) | ||
| result = cache.get(self.API_URL, "asset", "abc-123", "2024-01-01T00:00:00Z") | ||
| assert result == metadata | ||
|
|
||
| def test_stale_modified_returns_none(self, tmp_path: Path) -> None: | ||
| cache = APIMetadataCache(db_path=tmp_path / "cache.sqlite") | ||
| metadata = {"name": "test-asset", "size": 42} | ||
| cache.set(self.API_URL, "asset", "abc-123", "2024-01-01T00:00:00Z", metadata) | ||
| # Different modified timestamp -> cache miss | ||
| result = cache.get(self.API_URL, "asset", "abc-123", "2024-06-15T12:00:00Z") | ||
| assert result is None | ||
|
|
||
| def test_update_replaces_entry(self, tmp_path: Path) -> None: | ||
| cache = APIMetadataCache(db_path=tmp_path / "cache.sqlite") | ||
| cache.set(self.API_URL, "asset", "abc-123", "2024-01-01T00:00:00Z", {"v": 1}) | ||
| cache.set(self.API_URL, "asset", "abc-123", "2024-06-15T12:00:00Z", {"v": 2}) | ||
| # Old modified no longer matches | ||
| assert ( | ||
| cache.get(self.API_URL, "asset", "abc-123", "2024-01-01T00:00:00Z") is None | ||
| ) | ||
| # New modified matches | ||
| assert cache.get(self.API_URL, "asset", "abc-123", "2024-06-15T12:00:00Z") == { | ||
| "v": 2 | ||
| } | ||
|
|
||
| def test_clear(self, tmp_path: Path) -> None: | ||
| cache = APIMetadataCache(db_path=tmp_path / "cache.sqlite") | ||
| cache.set(self.API_URL, "asset", "abc-123", "2024-01-01T00:00:00Z", {"a": 1}) | ||
| cache.clear() | ||
| assert ( | ||
| cache.get(self.API_URL, "asset", "abc-123", "2024-01-01T00:00:00Z") is None | ||
| ) | ||
|
|
||
| def test_different_entity_types(self, tmp_path: Path) -> None: | ||
| cache = APIMetadataCache(db_path=tmp_path / "cache.sqlite") | ||
| cache.set( | ||
| self.API_URL, "asset", "id1", "2024-01-01T00:00:00Z", {"type": "asset"} | ||
| ) | ||
| cache.set( | ||
| self.API_URL, | ||
| "dandiset", | ||
| "id1", | ||
| "2024-01-01T00:00:00Z", | ||
| {"type": "dandiset"}, | ||
| ) | ||
| assert cache.get(self.API_URL, "asset", "id1", "2024-01-01T00:00:00Z") == { | ||
| "type": "asset" | ||
| } | ||
| assert cache.get(self.API_URL, "dandiset", "id1", "2024-01-01T00:00:00Z") == { | ||
| "type": "dandiset" | ||
| } | ||
|
|
||
| def test_dandi_cache_ignore( | ||
| self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch | ||
| ) -> None: | ||
| monkeypatch.setenv("DANDI_CACHE", "ignore") | ||
| cache = APIMetadataCache(db_path=tmp_path / "cache.sqlite") | ||
| cache.set(self.API_URL, "asset", "abc-123", "2024-01-01T00:00:00Z", {"a": 1}) | ||
| # Even after set, get returns None because cache is disabled | ||
| assert ( | ||
| cache.get(self.API_URL, "asset", "abc-123", "2024-01-01T00:00:00Z") is None | ||
| ) | ||
|
|
||
| def test_dandi_cache_clear( | ||
| self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch | ||
| ) -> None: | ||
| # First, populate the cache normally | ||
| cache1 = APIMetadataCache(db_path=tmp_path / "cache.sqlite") | ||
| cache1.set(self.API_URL, "asset", "abc-123", "2024-01-01T00:00:00Z", {"a": 1}) | ||
| assert cache1.get(self.API_URL, "asset", "abc-123", "2024-01-01T00:00:00Z") == { | ||
| "a": 1 | ||
| } | ||
|
|
||
| # Now open with DANDI_CACHE=clear — old data should be gone | ||
| monkeypatch.setenv("DANDI_CACHE", "clear") | ||
| cache2 = APIMetadataCache(db_path=tmp_path / "cache.sqlite") | ||
| assert ( | ||
| cache2.get(self.API_URL, "asset", "abc-123", "2024-01-01T00:00:00Z") is None | ||
| ) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
frankly I am not sure yet if we can rely on modified on per asset, see e.g. a random first hit
but also can dig deeper to still open
etc :-/
and we had touched on those prior in