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.4.0.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.4.0-py3-none-any.whl (9.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: spakky_cache-6.4.0.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.4.0.tar.gz
Algorithm Hash digest
SHA256 317f0387ca3474ff6444158ae1b9302193a2c99d05fdcfaed074edfc2959e435
MD5 3458317050af064bfae38d48dfe7c626
BLAKE2b-256 0188e8b830fe47ca42825785e7d2d55c3fa1a25255ee81180d287a236639c652

See more details on using hashes here.

Provenance

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

Publisher: release.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.4.0-py3-none-any.whl.

File metadata

  • Download URL: spakky_cache-6.4.0-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.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c0bb55ca0536a4b10d8b1caf1f92b1cbb8db4a33e69639f089196373b7a0d5d5
MD5 b273c416bb2e5d550501f574eb4e8146
BLAKE2b-256 b995469cac15ab67bf74378bd570221beabc6672b9cb83d498bc60d1f7066266

See more details on using hashes here.

Provenance

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

Publisher: release.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