authentik.root.cache
1from collections.abc import Callable, Hashable 2from concurrent.futures import ThreadPoolExecutor 3from functools import wraps 4from threading import Lock 5from time import monotonic 6from typing import Any, Protocol, cast 7 8from django.db import connection 9 10 11def make_key(key: str, key_prefix: str, version: int) -> str: 12 return f"{connection.schema_name}:{key_prefix}:{version}:{key}" 13 14 15def reverse_key(key: str) -> str: 16 return key.split(":", 3)[3] 17 18 19class CachedFunction[**P, R](Protocol): 20 def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ... 21 22 def cache_clear(self) -> None: ... 23 24 25class in_memory_cache: 26 """Cache a function's result in process memory, keyed by `key(*args, **kwargs)`. 27 28 Within `timeout` seconds the cached value is returned as-is. Once stale, the stale 29 value is still returned while a single background worker refreshes it. 30 The cache is per-process; call `.cache_clear()` on the wrapped function to invalidate.""" 31 32 def __init__(self, key: Callable[..., Hashable], timeout: float = 30, maxsize: int = 1024): 33 self.key = key 34 self.timeout = timeout 35 self.maxsize = maxsize 36 self._values: dict[Hashable, tuple[float, Any]] = {} 37 self._lock = Lock() 38 self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="in_memory_cache") 39 40 def _store(self, key: Hashable, value: Any) -> None: 41 # drop everything when full instead of LRU; keys can come from 42 # client input (e.g. Host header), so this only needs to bound memory 43 if key not in self._values and len(self._values) >= self.maxsize: 44 self._values.clear() 45 self._values[key] = (monotonic(), value) 46 47 def __call__[**P, R](self, func: Callable[P, R]) -> CachedFunction[P, R]: 48 def refresh(key: Hashable, args: tuple[Any, ...], kwargs: dict[str, Any]) -> None: 49 # Another thread is already refreshing; the next stale read will retry 50 if not self._lock.acquire(blocking=False): 51 return 52 try: 53 # Skip if a refresh finished between the stale read and acquiring the lock 54 cached = self._values.get(key) 55 if cached is None or monotonic() - cached[0] > self.timeout: 56 self._store(key, func(*args, **kwargs)) 57 finally: 58 self._lock.release() 59 # The worker thread has its own DB connection, which Django won't close 60 connection.close() 61 62 @wraps(func) 63 def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: 64 key = self.key(*args, **kwargs) 65 cached = self._values.get(key) 66 if cached is None: 67 value = func(*args, **kwargs) 68 self._store(key, value) 69 return value 70 stored_at, value = cached 71 if monotonic() - stored_at > self.timeout and not self._lock.locked(): 72 self._executor.submit(refresh, key, args, kwargs) 73 return cast(R, value) 74 75 wrapper.cache_clear = self._values.clear # type: ignore[attr-defined] 76 return cast(CachedFunction[P, R], wrapper)
20class CachedFunction[**P, R](Protocol): 21 def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ... 22 23 def cache_clear(self) -> None: ...
Base class for protocol classes.
Protocol classes are defined as::
class Proto(Protocol):
def meth(self) -> int:
...
Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing).
For example::
class C:
def meth(self) -> int:
return 0
def func(x: Proto) -> int:
return x.meth()
func(C()) # Passes static type check
See PEP 544 for details. Protocol classes decorated with @typing.runtime_checkable act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes can be generic, they are defined as::
class GenProto[T](Protocol):
def meth(self) -> T:
...
1903def _no_init_or_replace_init(self, *args, **kwargs): 1904 cls = type(self) 1905 1906 if cls._is_protocol: 1907 raise TypeError('Protocols cannot be instantiated') 1908 1909 # Already using a custom `__init__`. No need to calculate correct 1910 # `__init__` to call. This can lead to RecursionError. See bpo-45121. 1911 if cls.__init__ is not _no_init_or_replace_init: 1912 return 1913 1914 # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`. 1915 # The first instantiation of the subclass will call `_no_init_or_replace_init` which 1916 # searches for a proper new `__init__` in the MRO. The new `__init__` 1917 # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent 1918 # instantiation of the protocol subclass will thus use the new 1919 # `__init__` and no longer call `_no_init_or_replace_init`. 1920 for base in cls.__mro__: 1921 init = base.__dict__.get('__init__', _no_init_or_replace_init) 1922 if init is not _no_init_or_replace_init: 1923 cls.__init__ = init 1924 break 1925 else: 1926 # should not happen 1927 cls.__init__ = object.__init__ 1928 1929 cls.__init__(self, *args, **kwargs)
26class in_memory_cache: 27 """Cache a function's result in process memory, keyed by `key(*args, **kwargs)`. 28 29 Within `timeout` seconds the cached value is returned as-is. Once stale, the stale 30 value is still returned while a single background worker refreshes it. 31 The cache is per-process; call `.cache_clear()` on the wrapped function to invalidate.""" 32 33 def __init__(self, key: Callable[..., Hashable], timeout: float = 30, maxsize: int = 1024): 34 self.key = key 35 self.timeout = timeout 36 self.maxsize = maxsize 37 self._values: dict[Hashable, tuple[float, Any]] = {} 38 self._lock = Lock() 39 self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="in_memory_cache") 40 41 def _store(self, key: Hashable, value: Any) -> None: 42 # drop everything when full instead of LRU; keys can come from 43 # client input (e.g. Host header), so this only needs to bound memory 44 if key not in self._values and len(self._values) >= self.maxsize: 45 self._values.clear() 46 self._values[key] = (monotonic(), value) 47 48 def __call__[**P, R](self, func: Callable[P, R]) -> CachedFunction[P, R]: 49 def refresh(key: Hashable, args: tuple[Any, ...], kwargs: dict[str, Any]) -> None: 50 # Another thread is already refreshing; the next stale read will retry 51 if not self._lock.acquire(blocking=False): 52 return 53 try: 54 # Skip if a refresh finished between the stale read and acquiring the lock 55 cached = self._values.get(key) 56 if cached is None or monotonic() - cached[0] > self.timeout: 57 self._store(key, func(*args, **kwargs)) 58 finally: 59 self._lock.release() 60 # The worker thread has its own DB connection, which Django won't close 61 connection.close() 62 63 @wraps(func) 64 def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: 65 key = self.key(*args, **kwargs) 66 cached = self._values.get(key) 67 if cached is None: 68 value = func(*args, **kwargs) 69 self._store(key, value) 70 return value 71 stored_at, value = cached 72 if monotonic() - stored_at > self.timeout and not self._lock.locked(): 73 self._executor.submit(refresh, key, args, kwargs) 74 return cast(R, value) 75 76 wrapper.cache_clear = self._values.clear # type: ignore[attr-defined] 77 return cast(CachedFunction[P, R], wrapper)
Cache a function's result in process memory, keyed by key(*args, **kwargs).
Within timeout seconds the cached value is returned as-is. Once stale, the stale
value is still returned while a single background worker refreshes it.
The cache is per-process; call .cache_clear() on the wrapped function to invalidate.
33 def __init__(self, key: Callable[..., Hashable], timeout: float = 30, maxsize: int = 1024): 34 self.key = key 35 self.timeout = timeout 36 self.maxsize = maxsize 37 self._values: dict[Hashable, tuple[float, Any]] = {} 38 self._lock = Lock() 39 self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="in_memory_cache")