pico-caching 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,19 @@
1
+ """pico-caching: declarative caching for the Pico ecosystem.
2
+
3
+ ``@cacheable`` over pico-ioc method interception, with a pluggable
4
+ ``CacheBackend`` protocol and a built-in thread-safe in-memory LRU with TTL.
5
+ Auto-discovered by pico-boot; zero-config (no ``cache:`` block required).
6
+
7
+ Public API:
8
+ Decorator: cacheable
9
+ Protocol: CacheBackend
10
+ Backend: InMemoryCacheBackend
11
+ Settings: CacheSettings
12
+ """
13
+
14
+ from .backend import CacheBackend, InMemoryCacheBackend
15
+ from .config import CacheSettings
16
+ from .decorators import cacheable
17
+ from .interceptor import CacheInterceptor
18
+
19
+ __all__ = ["cacheable", "CacheBackend", "InMemoryCacheBackend", "CacheSettings", "CacheInterceptor"]
@@ -0,0 +1 @@
1
+ __version__ = '0.1.0'
@@ -0,0 +1,59 @@
1
+ """Cache backend protocol and the built-in in-memory LRU backend."""
2
+
3
+ import threading
4
+ import time
5
+ from collections import OrderedDict
6
+ from typing import Any, Protocol, Tuple, runtime_checkable
7
+
8
+ from pico_ioc import component
9
+
10
+ from .config import CacheSettings
11
+
12
+ _MISS = object()
13
+
14
+
15
+ @runtime_checkable
16
+ class CacheBackend(Protocol):
17
+ """Implement as a ``@component`` to replace the in-memory backend."""
18
+
19
+ def get(self, key: str) -> Tuple[bool, Any]: ...
20
+ def set(self, key: str, value: Any, ttl_seconds: float) -> None: ...
21
+ def delete(self, key: str) -> None: ...
22
+ def clear(self) -> None: ...
23
+
24
+
25
+ @component
26
+ class InMemoryCacheBackend:
27
+ """Thread-safe LRU with per-entry TTL (``time.monotonic`` based)."""
28
+
29
+ def __init__(self, settings: CacheSettings):
30
+ self._max = settings.max_entries
31
+ self._data: OrderedDict[str, Tuple[float, Any]] = OrderedDict()
32
+ self._lock = threading.Lock()
33
+
34
+ def get(self, key: str) -> Tuple[bool, Any]:
35
+ with self._lock:
36
+ item = self._data.get(key, _MISS)
37
+ if item is _MISS:
38
+ return False, None
39
+ expires_at, value = item
40
+ if time.monotonic() >= expires_at:
41
+ del self._data[key]
42
+ return False, None
43
+ self._data.move_to_end(key)
44
+ return True, value
45
+
46
+ def set(self, key: str, value: Any, ttl_seconds: float) -> None:
47
+ with self._lock:
48
+ self._data[key] = (time.monotonic() + ttl_seconds, value)
49
+ self._data.move_to_end(key)
50
+ while len(self._data) > self._max:
51
+ self._data.popitem(last=False)
52
+
53
+ def delete(self, key: str) -> None:
54
+ with self._lock:
55
+ self._data.pop(key, None)
56
+
57
+ def clear(self) -> None:
58
+ with self._lock:
59
+ self._data.clear()
pico_caching/config.py ADDED
@@ -0,0 +1,15 @@
1
+ """Settings for pico-caching (prefix ``cache``, zero-config)."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from pico_ioc import configured
6
+
7
+
8
+ @configured(target="self", prefix="cache", mapping="tree")
9
+ @dataclass
10
+ class CacheSettings:
11
+ """``enabled: false`` makes ``@cacheable`` a pass-through."""
12
+
13
+ enabled: bool = True
14
+ default_ttl_seconds: float = 300.0
15
+ max_entries: int = 1024
@@ -0,0 +1,32 @@
1
+ """``@cacheable`` marker: stores the policy and attaches the interceptor."""
2
+
3
+ from typing import Any, Callable
4
+
5
+ CACHE_META = "_pico_caching_meta"
6
+
7
+
8
+ def cacheable(
9
+ _func: Callable | None = None,
10
+ *,
11
+ ttl_seconds: float | None = None,
12
+ key: Callable[..., str] | None = None,
13
+ ):
14
+ """Cache the method's return value. Sync or async; async methods cache
15
+ the awaited result, never the coroutine. ``key(*args, **kwargs)``
16
+ overrides the default repr-based key; ``ttl_seconds`` overrides
17
+ ``cache.default_ttl_seconds``."""
18
+
19
+ def dec(fn):
20
+ setattr(fn, CACHE_META, {"ttl_seconds": ttl_seconds, "key": key})
21
+ from pico_ioc import intercepted_by
22
+
23
+ from .interceptor import CacheInterceptor
24
+
25
+ return intercepted_by(CacheInterceptor)(fn)
26
+
27
+ return dec(_func) if callable(_func) else dec
28
+
29
+
30
+ def _meta(ctx: Any) -> dict:
31
+ fn = getattr(ctx.cls, ctx.name, None)
32
+ return getattr(fn, CACHE_META, {})
@@ -0,0 +1,51 @@
1
+ """Cache interceptor: get-or-compute through the selected backend."""
2
+
3
+ import inspect
4
+ from typing import Any, Callable, List
5
+
6
+ from pico_ioc import MethodCtx, component
7
+
8
+ from .backend import CacheBackend, InMemoryCacheBackend
9
+ from .config import CacheSettings
10
+ from .decorators import _meta
11
+
12
+
13
+ def _default_key(ctx: MethodCtx) -> str:
14
+ kw = ",".join(f"{k}={v!r}" for k, v in sorted(ctx.kwargs.items()))
15
+ return f"{ctx.cls.__module__}.{ctx.cls.__qualname__}.{ctx.name}({','.join(map(repr, ctx.args))};{kw})"
16
+
17
+
18
+ @component(scope="singleton")
19
+ class CacheInterceptor:
20
+ """Uses the first user-provided ``CacheBackend``; falls back to the
21
+ built-in in-memory LRU."""
22
+
23
+ def __init__(self, settings: CacheSettings, backends: List[CacheBackend]):
24
+ self.settings = settings
25
+ custom = [b for b in backends if not isinstance(b, InMemoryCacheBackend)]
26
+ fallback = [b for b in backends if isinstance(b, InMemoryCacheBackend)]
27
+ self.backend = (custom or fallback)[0]
28
+
29
+ def invoke(self, ctx: MethodCtx, call_next: Callable[[MethodCtx], Any]) -> Any:
30
+ meta = _meta(ctx)
31
+ if not self.settings.enabled or not meta:
32
+ return call_next(ctx)
33
+ key_fn = meta["key"]
34
+ key = key_fn(*ctx.args, **ctx.kwargs) if key_fn else _default_key(ctx)
35
+ ttl = meta["ttl_seconds"] if meta["ttl_seconds"] is not None else self.settings.default_ttl_seconds
36
+ if inspect.iscoroutinefunction(ctx.method):
37
+ return self._get_or_compute_async(ctx, call_next, key, ttl)
38
+ hit, value = self.backend.get(key)
39
+ if hit:
40
+ return value
41
+ value = call_next(ctx)
42
+ self.backend.set(key, value, ttl)
43
+ return value
44
+
45
+ async def _get_or_compute_async(self, ctx, call_next, key: str, ttl: float):
46
+ hit, value = self.backend.get(key)
47
+ if hit:
48
+ return value
49
+ value = await call_next(ctx)
50
+ self.backend.set(key, value, ttl)
51
+ return value
pico_caching/py.typed ADDED
File without changes
@@ -0,0 +1,110 @@
1
+ Metadata-Version: 2.4
2
+ Name: pico-caching
3
+ Version: 0.1.0
4
+ Summary: Declarative caching for the Pico ecosystem: @cacheable AOP with pluggable backends.
5
+ Author-email: David Perez Cabrera <dperezcabrera@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 David Pérez Cabrera
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/dperezcabrera/pico-caching
29
+ Project-URL: Documentation, https://dperezcabrera.github.io/pico-caching/
30
+ Project-URL: Repository, https://github.com/dperezcabrera/pico-caching
31
+ Project-URL: Changelog, https://github.com/dperezcabrera/pico-caching/blob/main/CHANGELOG.md
32
+ Project-URL: Issue Tracker, https://github.com/dperezcabrera/pico-caching/issues
33
+ Keywords: cache,cacheable,lru,ttl,aop,ioc,spring boot
34
+ Classifier: Development Status :: 4 - Beta
35
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
36
+ Classifier: Programming Language :: Python :: 3
37
+ Classifier: Programming Language :: Python :: 3 :: Only
38
+ Classifier: Programming Language :: Python :: 3.11
39
+ Classifier: Programming Language :: Python :: 3.12
40
+ Classifier: Programming Language :: Python :: 3.13
41
+ Classifier: Intended Audience :: Developers
42
+ Classifier: License :: OSI Approved :: MIT License
43
+ Classifier: Operating System :: OS Independent
44
+ Classifier: Typing :: Typed
45
+ Requires-Python: >=3.11
46
+ Description-Content-Type: text/markdown
47
+ License-File: LICENSE
48
+ Requires-Dist: pico-ioc>=2.2.0
49
+ Provides-Extra: dev
50
+ Requires-Dist: pytest>=8; extra == "dev"
51
+ Requires-Dist: pytest-asyncio; extra == "dev"
52
+ Requires-Dist: pytest-cov>=5; extra == "dev"
53
+ Requires-Dist: ruff; extra == "dev"
54
+ Dynamic: license-file
55
+
56
+ # 📦 pico-caching
57
+
58
+ [![PyPI](https://img.shields.io/pypi/v/pico-caching.svg)](https://pypi.org/project/pico-caching/)
59
+ [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/dperezcabrera/pico-caching)
60
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
61
+ ![CI (tox matrix)](https://github.com/dperezcabrera/pico-caching/actions/workflows/ci.yml/badge.svg)
62
+ [![codecov](https://codecov.io/gh/dperezcabrera/pico-caching/branch/main/graph/badge.svg)](https://codecov.io/gh/dperezcabrera/pico-caching)
63
+ [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=dperezcabrera_pico-caching&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=dperezcabrera_pico-caching)
64
+ [![Duplicated Lines (%)](https://sonarcloud.io/api/project_badges/measure?project=dperezcabrera_pico-caching&metric=duplicated_lines_density)](https://sonarcloud.io/summary/new_code?id=dperezcabrera_pico-caching)
65
+ [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=dperezcabrera_pico-caching&metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=dperezcabrera_pico-caching)
66
+ [![PyPI Downloads](https://img.shields.io/pypi/dm/pico-caching)](https://pypi.org/project/pico-caching/)
67
+ [![Docs](https://img.shields.io/badge/Docs-pico--caching-blue?style=flat&logo=readthedocs&logoColor=white)](https://dperezcabrera.github.io/pico-caching/)
68
+ [![Interactive Lab](https://img.shields.io/badge/Learn-online-green?style=flat&logo=python&logoColor=white)](https://dperezcabrera.github.io/pico-learn/)
69
+
70
+ Declarative **method caching** for the [Pico](https://github.com/dperezcabrera/pico-ioc) ecosystem: `@cacheable` over pico-ioc method interception, pluggable backends, auto-discovered by [pico-boot](https://github.com/dperezcabrera/pico-boot). Zero-config.
71
+
72
+ ## Install
73
+
74
+ ```bash
75
+ pip install pico-caching
76
+ ```
77
+
78
+ ## Use
79
+
80
+ ```python
81
+ from pico_ioc import component
82
+ from pico_caching import cacheable
83
+
84
+ @component
85
+ class UserRepo:
86
+ @cacheable(ttl_seconds=60)
87
+ async def find(self, user_id: int): ...
88
+
89
+ @cacheable(key=lambda q: f"search:{q}")
90
+ def search(self, q: str): ...
91
+ ```
92
+
93
+ Sync and async (the awaited **result** is cached, never the coroutine). Default backend: thread-safe in-memory LRU with per-entry TTL (`cache.max_entries`, `cache.default_ttl_seconds`). Bring your own backend by implementing the `CacheBackend` protocol as a `@component` — it replaces the built-in automatically.
94
+
95
+ ```yaml
96
+ # application.yaml (optional)
97
+ cache:
98
+ default_ttl_seconds: 300
99
+ max_entries: 1024
100
+ ```
101
+
102
+ Skipped for now: `@cache_evict` and a Redis backend — planned once real usage asks for them.
103
+
104
+ ## Documentation
105
+
106
+ Full docs at **[dperezcabrera.github.io/pico-caching](https://dperezcabrera.github.io/pico-caching/)**.
107
+
108
+ ## License
109
+
110
+ MIT
@@ -0,0 +1,15 @@
1
+ pico_caching/__init__.py,sha256=pylGqOfjMh-yU1d2ECsKwSOaFM9rwKONFn_vWCtKUhc,680
2
+ pico_caching/_version.py,sha256=IMjkMO3twhQzluVTo8Z6rE7Eg-9U79_LGKMcsWLKBkY,22
3
+ pico_caching/backend.py,sha256=46nATdKrJH2bfOMPElvvdmfa2rH2-gTcHUVXBtKu9sA,1824
4
+ pico_caching/config.py,sha256=GoCmJhrTGPT51U-FvS_JnUY8pfl-DX3inkNtLuWi_8k,385
5
+ pico_caching/decorators.py,sha256=2F0t-D76_6PYafgopiCtTM8TUiKKmfMhUZH07DmdUR0,943
6
+ pico_caching/interceptor.py,sha256=zpYavThTukbTXk0-FfnCz_d1kOvM0BFq1m1Dk6kZDCc,1970
7
+ pico_caching/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ pico_caching-0.1.0.dist-info/licenses/LICENSE,sha256=N1_nOvHTM6BobYnOTNXiQkroDqCEi6EzfGBv8lWtyZ0,1077
9
+ pico_caching-0.1.0.dist-info/METADATA,sha256=1BkZd8DYNervaVzGR75ztxTyGNdo9oKz833sS7Xw3k4,5601
10
+ pico_caching-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
11
+ pico_caching-0.1.0.dist-info/entry_points.txt,sha256=3R_ryGuGL5r2wdkRS1EQh5WyJSEkIWGyICxMS8AxPrM,48
12
+ pico_caching-0.1.0.dist-info/scm_file_list.json,sha256=GaoZRveD_DMMpuE-cLdGbm_Fp2NhoIfArxSjHpXsWF0,1303
13
+ pico_caching-0.1.0.dist-info/scm_version.json,sha256=wEnomyEM9-j3rRRc8h5W7_YItJn4L6nA36ZlEDcuigI,160
14
+ pico_caching-0.1.0.dist-info/top_level.txt,sha256=M1jez3sLSGVJ5r_G3HfafvcQ_3wKJj2YRSk-ver4iLg,13
15
+ pico_caching-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [pico_boot.modules]
2
+ pico_caching = pico_caching
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 David Pérez Cabrera
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,51 @@
1
+ {
2
+ "files": [
3
+ ".coveragerc",
4
+ "README.md",
5
+ "Makefile",
6
+ "tox.ini",
7
+ "LICENSE",
8
+ "pyproject.toml",
9
+ "SECURITY.md",
10
+ "mkdocs.yml",
11
+ "CHANGELOG.md",
12
+ "CONTRIBUTING.md",
13
+ "AGENTS.md",
14
+ "CLAUDE.md",
15
+ "MANIFEST.in",
16
+ "Dockerfile.test",
17
+ ".gitignore",
18
+ "CODE_OF_CONDUCT.md",
19
+ "docs/getting-started.md",
20
+ "docs/requirements.txt",
21
+ "docs/LEARN.md",
22
+ "docs/CHANGELOG.md",
23
+ "docs/faq.md",
24
+ "docs/troubleshooting.md",
25
+ "docs/skills.md",
26
+ "docs/index.md",
27
+ "docs/hooks.py",
28
+ "docs/architecture.md",
29
+ "docs/stylesheets/extra.css",
30
+ "docs/javascripts/extra.js",
31
+ "docs/reference/api.md",
32
+ "docs/reference/index.md",
33
+ "src/pico_caching/interceptor.py",
34
+ "src/pico_caching/py.typed",
35
+ "src/pico_caching/__init__.py",
36
+ "src/pico_caching/config.py",
37
+ "src/pico_caching/decorators.py",
38
+ "src/pico_caching/backend.py",
39
+ "tests/__init__.py",
40
+ "tests/conftest.py",
41
+ "tests/test_cache.py",
42
+ ".github/PULL_REQUEST_TEMPLATE.md",
43
+ ".github/dependabot.yml",
44
+ ".github/ISSUE_TEMPLATE/bug_report.yml",
45
+ ".github/ISSUE_TEMPLATE/feature_request.yml",
46
+ ".github/workflows/docs.yml",
47
+ ".github/workflows/codeql.yml",
48
+ ".github/workflows/ci.yml",
49
+ ".github/workflows/publish-to-pypi.yml"
50
+ ]
51
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "tag": "0.1.0",
3
+ "distance": 0,
4
+ "node": "g0371d292c577375653beb97ef06543a62be28345",
5
+ "dirty": false,
6
+ "branch": "HEAD",
7
+ "node_date": "2026-07-04"
8
+ }
@@ -0,0 +1 @@
1
+ pico_caching