-
-
Notifications
You must be signed in to change notification settings - Fork 34
use diskcache to memoize check results #1467
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
elfkuzco
wants to merge
5
commits into
main
Choose a base branch
from
healthcheck-diskcache
base: main
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
5 commits
Select commit
Hold shift + click to select a range
e4e4f86
use diskcache to memoize check results
elfkuzco f43b6f6
add stubs library ad fix ci
elfkuzco 84eb987
move stubs library to proper section
elfkuzco 4ad0868
add option to cache failed results
elfkuzco 1dbd002
add comment describing serialization protocol
elfkuzco 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
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,75 @@ | ||
| from collections.abc import Awaitable, Callable | ||
| from functools import wraps | ||
| from typing import ParamSpec, TypeVar | ||
|
|
||
| from diskcache import FanoutCache | ||
|
|
||
| from healthcheck.constants import ( | ||
| CACHE_KEY_PREFIX, | ||
| CACHE_LOCATION, | ||
| DEFAULT_CACHE_EXPIRATION, | ||
| ) | ||
|
|
||
| P = ParamSpec("P") | ||
| R = TypeVar("R") | ||
|
|
||
| # As per the docs, writers can block other writers to the cache. The FanoutCache as | ||
| # opposed to the simpler Cache uses sharding to decrease block writes. This makes | ||
| # it a good candidate for our usage because the functions we want to memoize are run | ||
| # "concurrently" using asyncio.gather. | ||
| _cache: FanoutCache | None = None | ||
|
|
||
|
|
||
| def init_cache() -> FanoutCache: | ||
| """Get or create the disk cache instance.""" | ||
| global _cache # noqa: PLW0603 | ||
| if _cache is None: | ||
| _cache = FanoutCache(CACHE_LOCATION) | ||
| return _cache | ||
|
|
||
|
|
||
| def close_cache() -> None: | ||
| """Close the disk cache instance.""" | ||
| global _cache # noqa: PLW0603 | ||
| if _cache is not None: | ||
| _cache.close() | ||
| _cache = None | ||
|
|
||
|
|
||
| def memoize( | ||
| key: str, | ||
| expire: float = DEFAULT_CACHE_EXPIRATION, | ||
| *, | ||
| cache_only_on_success: bool = True, | ||
| ) -> Callable[[Callable[P, Awaitable[R]]], Callable[P, Awaitable[R]]]: | ||
| """Memoize function calls with results at CACHE_KEY_PREFIX:key. | ||
|
|
||
| Results are considered successful if they have a success attribute and it is truthy. | ||
| """ | ||
|
|
||
| def decorator(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]: | ||
| @wraps(func) | ||
| async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: | ||
| cache = init_cache() | ||
| location = f"{CACHE_KEY_PREFIX}:{key}" | ||
| # Types other than the basic types like floats, ints, bytes, strings are | ||
| # are stored using pickle by default. Thus, we can save our results | ||
| # (pydantic models) directly to the cache and get it back as is. | ||
| if (result := cache.get(location)) is not None: | ||
| return result | ||
|
|
||
| result = await func(*args, **kwargs) | ||
|
|
||
| if cache_only_on_success: | ||
| if ( | ||
| hasattr(result, "success") | ||
| and result.success # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType] | ||
| ): | ||
| cache.set(location, result, expire=expire) | ||
| else: | ||
| cache.set(location, result, expire=expire) | ||
| return result | ||
|
|
||
| return wrapper | ||
|
|
||
| return decorator | ||
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 |
|---|---|---|
| @@ -1,28 +1,18 @@ | ||
| import os | ||
| from typing import Any | ||
| from pathlib import Path | ||
|
|
||
| from humanfriendly import parse_timespan | ||
|
|
||
|
|
||
| def getenv(key: str, *, mandatory: bool = False, default: Any = None) -> Any: | ||
| value = os.getenv(key) or default | ||
|
|
||
| if mandatory and not value: | ||
| raise OSError(f"Please set the {key} environment variable") | ||
|
|
||
| return value | ||
|
|
||
|
|
||
| def parse_bool(value: Any) -> bool: | ||
| """Parse value into boolean.""" | ||
| return str(value).lower() in ("true", "1", "yes", "y", "on") | ||
|
|
||
|
|
||
| DEBUG = parse_bool(getenv("DEBUG", default="false")) | ||
| from healthcheck import getenv | ||
|
|
||
| REQUESTS_TIMEOUT = parse_timespan(getenv("REQUESTS_TIMEOUT", default="1m")) | ||
|
|
||
| ZIMFARM_API_URL = getenv("ZIMFARM_API_URL", mandatory=True) | ||
| ZIMFARM_USERNAME = getenv("ZIMFARM_USERNAME", mandatory=True) | ||
| ZIMFARM_PASSWORD = getenv("ZIMFARM_PASSWORD", mandatory=True) | ||
| ZIMFARM_DATABASE_URL = getenv("ZIMFARM_DATABASE_URL", mandatory=True) | ||
|
|
||
| CACHE_LOCATION = Path(getenv("CACHE_LOCATION", default="/data/cache")) | ||
| CACHE_KEY_PREFIX = getenv("CACHE_KEY_PREFIX", default="healthcheck") | ||
| DEFAULT_CACHE_EXPIRATION = parse_timespan( | ||
| getenv("DEFAULT_CACHE_EXPIRATION", default="1m") | ||
| ) |
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
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
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,23 @@ | ||
| from pathlib import Path | ||
|
|
||
| import pytest | ||
|
|
||
| from healthcheck import cache as cache_module | ||
| from healthcheck.cache import close_cache, init_cache | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def cache_dir(tmp_path: Path) -> Path: | ||
| """Create a temporary directory for cache files.""" | ||
| cache_dir = tmp_path / "cache" | ||
| cache_dir.mkdir() | ||
| return cache_dir | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def cache(cache_dir: Path, monkeypatch: pytest.MonkeyPatch): | ||
| """Configure cache to use temporary directory and ensure it's closed after test.""" | ||
| monkeypatch.setattr(cache_module, "CACHE_LOCATION", cache_dir) | ||
| cache = init_cache() | ||
| yield cache | ||
| close_cache() |
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.
Uh oh!
There was an error while loading. Please reload this page.