Coverage for jinja2_async_environment/compiler_modules/cache.py: 100%

1"""Compilation cache for template code optimization."""

2

3 import hashlib

4

5

6 class CompilationCache:

7 """Cache for compiled template code to avoid recompilation."""

8

9 def __init__(self, max_size: int = 1000):

10 self.max_size = max_size

11 self._cache: dict[str, str] = {}

12

13 def get_cache_key(self, source: str, environment_id: str) -> str:

14 """Generate a cache key for template source and environment."""

15 content = f"{source}:{environment_id}"

16 return hashlib.sha256(content.encode()).hexdigest()[:16]

17

18 def get(self, cache_key: str) -> str | None:

19 """Get compiled code from cache."""

20 return self._cache.get(cache_key)

21

22 def set(self, cache_key: str, compiled_code: str) -> None:

23 """Store compiled code in cache with size limit."""

24 if len(self._cache) >= self.max_size:

25 # Remove oldest entries (simple FIFO)

26 oldest_keys = list(self._cache.keys())[: self.max_size // 4]

27 for key in oldest_keys:

28 del self._cache[key]

29

30 self._cache[cache_key] = compiled_code

31

32 def clear(self) -> None:

33 """Clear the cache."""

34 self._cache.clear()