Debian Codegraph @

lib/ansible/_internal/_plugins/_cache.py

raw
1 from __future__ import annotations
2
3 import functools
4 import json
5 import json.encoder
6 import json.decoder
7 import typing as t
8
9 from .._wrapt import ObjectProxy
10 from .._json._profiles import _cache_persistence
11
12
13 class PluginInterposer(ObjectProxy):
14 """Proxies a Cache plugin instance to implement transparent encapsulation of serialized Ansible internal data types."""
15
16 _PAYLOAD_KEY = '__payload__'
17 """The key used to store the serialized payload."""
18
19 def get(self, key: str) -> dict[str, object]:
20 return self._decode(self.__wrapped__.get(self._get_key(key)))
21
22 def set(self, key: str, value: dict[str, object]) -> None:
23 self.__wrapped__.set(self._get_key(key), self._encode(value))
24
25 def keys(self) -> t.Sequence[str]:
26 return [k for k in (self._restore_key(k) for k in self.__wrapped__.keys()) if k is not None]
27
28 def contains(self, key: t.Any) -> bool:
29 return self.__wrapped__.contains(self._get_key(key))
30
31 def delete(self, key: str) -> None:
32 self.__wrapped__.delete(self._get_key(key))
33
34 @classmethod
35 def _restore_key(cls, wrapped_key: str) -> str | None:
36 prefix = cls._get_wrapped_key_prefix()
37
38 if not wrapped_key.startswith(prefix):
39 return None
40
41 return wrapped_key[len(prefix) :]
42
43 @classmethod
44 @functools.cache
45 def _get_wrapped_key_prefix(cls) -> str:
46 return f's{_cache_persistence._Profile.schema_id}_'
47
48 @classmethod
49 def _get_key(cls, key: str) -> str:
50 """Augment the supplied key with a schema identifier to allow for side-by-side caching across incompatible schemas."""
51 return f'{cls._get_wrapped_key_prefix()}{key}'
52
53 def _encode(self, value: dict[str, object]) -> dict[str, object]:
54 return {self._PAYLOAD_KEY: json.dumps(value, cls=_cache_persistence.Encoder)}
55
56 def _decode(self, value: dict[str, t.Any]) -> dict[str, object]:
57 return json.loads(value[self._PAYLOAD_KEY], cls=_cache_persistence.Decoder)