-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcache.py
More file actions
81 lines (67 loc) · 2.61 KB
/
cache.py
File metadata and controls
81 lines (67 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
from abc import ABC
from collections import defaultdict
from typing import Any
class BaseEnvironmentsCache(ABC):
def __init__(self, *args, **kwargs):
self.last_updated_at = None
def put_environment(
self,
environment_api_key: str,
environment_document: dict[str, Any],
) -> bool:
"""
Update the environment cache for the given key with the given environment document.
Returns a boolean confirming if the cache was updated or not (i.e. if the environment document
was different from the one already in the cache).
"""
# TODO: can we use the environment header here instead of comparing the document?
if environment_document != self.get_environment(environment_api_key):
self._put_environment(environment_api_key, environment_document)
return True
return False
def _put_environment(
self,
environment_api_key: str,
environment_document: dict[str, Any],
) -> None:
raise NotImplementedError()
def get_environment(self, environment_api_key: str) -> dict[str, Any] | None:
raise NotImplementedError()
def get_identity(
self,
environment_api_key: str,
identifier: str,
) -> dict[str, Any]:
raise NotImplementedError()
_LocalCacheDict = dict[str, dict[str, Any]]
class LocalMemEnvironmentsCache(BaseEnvironmentsCache):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._environment_cache: _LocalCacheDict = {}
self._identity_override_cache = defaultdict[str, _LocalCacheDict](dict)
def _put_environment(
self,
environment_api_key: str,
environment_document: dict[str, Any],
) -> None:
self._environment_cache[environment_api_key] = environment_document
new_overrides = environment_document.get("identity_overrides") or []
self._identity_override_cache[environment_api_key] = {
identifier: identity_document
for identity_document in new_overrides
if (identifier := identity_document.get("identifier"))
}
def get_environment(
self,
environment_api_key: str,
) -> dict[str, Any] | None:
return self._environment_cache.get(environment_api_key)
def get_identity(
self,
environment_api_key: str,
identifier: str,
) -> dict[str, Any]:
return self._identity_override_cache[environment_api_key].get(identifier) or {
"environment_api_key": environment_api_key,
"identifier": identifier,
}