Skip to main content

Backend-neutral cache contracts and in-memory backend for Spakky Framework

Project description

Spakky Cache

Backend-neutral application data cache contracts for Spakky Framework.

Installation

pip install spakky-cache

Features

  • Typed cache results: CacheHit[T] and CacheMiss represent hit and miss outcomes without backend-specific exceptions.
  • Sync and async contracts: ICache[T] defines get, set, delete, clear and async equivalents.
  • TTL semantics: Positive TTL values expire entries deterministically; missing and expired entries are misses.
  • In-memory backend: InMemoryCache[T] is suitable for local development, tests, and single-process usage.
  • AOP method caching: @cacheable() and @cache_evict() apply cache hit/miss and eviction behavior without manual plumbing.
  • Application data scope: This package does not expose or mutate ApplicationContext internal caches.

Quick Start

from datetime import timedelta

from spakky.cache import CacheHit, InMemoryCache

cache = InMemoryCache[str]()
cache.set("profile:42", "Ada", ttl=timedelta(minutes=5))

result = cache.get("profile:42")
if isinstance(result, CacheHit):
    print(result.value)

Annotation Usage

Load the spakky-cache plugin, then annotate service methods. The plugin registers InMemoryCache, CacheAspect, and AsyncCacheAspect so sync and async methods are handled through Spakky AOP.

from datetime import timedelta

from spakky.cache import cache_evict, cacheable
from spakky.core.stereotype.usecase import UseCase


@UseCase()
class ProfileService:
    def __init__(self) -> None:
        self.calls = 0

    @cacheable(key="profile:{0}", ttl=timedelta(minutes=5))
    def load_profile(self, user_id: str) -> str:
        self.calls += 1
        return f"profile:{user_id}"

    @cache_evict(key="profile:{0}")
    def refresh_profile(self, user_id: str) -> None:
        ...

The default key is derived from the method module, qualified name, positional arguments, and sorted keyword arguments. Explicit key values are Python format strings evaluated against method call arguments. Invalid key formatting raises CacheKeyGenerationError. Backend failures are not swallowed; cache errors propagate loudly.

@cache_evict() deletes the matching entry only after the annotated method succeeds. Failed method calls leave existing entries untouched so a failed refresh does not erase the last known cached value.

Async Usage

from spakky.cache import CacheHit, InMemoryCache

cache = InMemoryCache[int]()
await cache.set_async("answer", 42)

result = await cache.get_async("answer")
if isinstance(result, CacheHit):
    assert result.value == 42

TTL Rules

ttl=None stores an entry until explicit deletion or clear. Positive float, int, or datetime.timedelta values expire entries after that duration. Zero or negative TTL values raise InvalidCacheTTLError.

The in-memory backend deletes expired entries when they are observed. It is deterministic for one process and does not provide distributed invalidation, stampede protection, or tag-based eviction.

Cache eviction annotations remove a single matching entry only after the annotated method succeeds.

Scope

spakky-cache is an application data cache abstraction. It is separate from ApplicationContext internal type, singleton, and context caches. Distributed locks, cache stampede protection, tag invalidation, write-through/write-behind policies, and metrics exporters are outside the current contract.

License

MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

spakky_cache-6.3.1.tar.gz (5.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

spakky_cache-6.3.1-py3-none-any.whl (9.6 kB view details)

Uploaded Python 3

File details

Details for the file spakky_cache-6.3.1.tar.gz.

File metadata

  • Download URL: spakky_cache-6.3.1.tar.gz
  • Upload date:
  • Size: 5.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for spakky_cache-6.3.1.tar.gz
Algorithm Hash digest
SHA256 7acbe21b5fd8e4e19e57b20e1617c8a93781ef8c252cb73efcbdd0abcf9c56b6
MD5 dbd0aab2087da0892c3b87adde39c83d
BLAKE2b-256 1ee2ba2c81a6923d524a34101f8e3cfae7c97bcbf37c6a583c4f38a649915b56

See more details on using hashes here.

Provenance

The following attestation bundles were made for spakky_cache-6.3.1.tar.gz:

Publisher: publish-package.yml on E5presso/spakky-framework

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file spakky_cache-6.3.1-py3-none-any.whl.

File metadata

  • Download URL: spakky_cache-6.3.1-py3-none-any.whl
  • Upload date:
  • Size: 9.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for spakky_cache-6.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 5d7e7aed00a2fbf6ade949d2d9eee70bb74fee4504c3886af129ea7742536a52
MD5 f4ee3e3b3f81d3be7418634fca226fc3
BLAKE2b-256 a3c2cdb5b0b7d1a33f9d0e71209fd06e4dfddb9b24abe7aa53f39854c48279e4

See more details on using hashes here.

Provenance

The following attestation bundles were made for spakky_cache-6.3.1-py3-none-any.whl:

Publisher: publish-package.yml on E5presso/spakky-framework

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page