Debian Codegraph @

gavo/base/caches.py

raw
1 """
2 Accessor functions for the various immutables we have.
3
4 The main purpose of this module is to keep caches of resource descriptors,
5 and other items the parsing of which may take some time.
6
7 All you need to do is provide a function taking a "key" (a string, most
8 likely) and returning the object. Then call
9
10 base.caches.makeCache(<accessorName>, <function>)
11
12 After that, clients can call
13
14 base.caches.<accessorName>(key)
15
16 You can additionally provide an isDirty(res) function when calling makeCache.
17 This can return True if the resource is out of date and should be reloaded.
18
19 An alternative interface to registering caches is the registerCache function
20 (see there).
21 """
22
23 from gavo.utils.dachstypes import (Any, Callable, Dict, Optional)
24
25 #c Copyright 2008-2025, the GAVO project <[email protected]>
26 #c
27 #c This program is free software, covered by the GNU GPL. See the
28 #c COPYING file in the source distribution.
29
30
31 class CacheRegistry:
32 """is a registry for caches kept to be able to clear them.
33
34 A cache is assumed to be a dictionary here.
35 """
36 def __init__(self):
37 self.knownCaches = []
38
39 def clearall(self):
40 """drops all caches managed by this registry.
41
42 This would be an appropriate action on a server reload, for instance.
43 """
44 for cache in self.knownCaches:
45 for key in list(cache.keys()):
46 del cache[key]
47
48 def clearForName(self, key: str) -> None:
49 """removes cached items for key from all known caches.
50
51 This is the appropriate action when an RD is reloaded, for instance.
52 """
53 for cache in self.knownCaches:
54 if key in cache:
55 del cache[key]
56
57 def register(self, cache: Dict) -> None:
58 self.knownCaches.append(cache)
59
60
61 _cacheRegistry = CacheRegistry()
62 clearCaches = _cacheRegistry.clearall
63 clearForName = _cacheRegistry.clearForName
64
65
66 def _makeCache(
67 creator: Callable[[Any], Any],
68 isDirty: Optional[Callable[[Any], bool]]) -> Callable:
69 """returns a callable that memoizes the results of creator.
70
71 The creator has to be a function taking an id and returning the
72 designated object.
73
74 The whole thing is thread-safe only when the creators are. It is
75 possible that arbitrarily many creators for the same id run. Only one
76 will win in the end.
77
78 Race conditions are possible when exceptions occur, but then creators
79 behaviour should only depend on id, and so it shouldn't matter.
80
81 isDirty can be a function returning true when the cache should be
82 cleared. The function is passed the current resource. If isDirty
83 is None, no such check is performed.
84 """
85 cache: Dict[str, Any] = {}
86 _cacheRegistry.register(cache)
87
88 def func(id: str) -> Any:
89 if isDirty is not None and id in cache and isDirty(cache[id]):
90 clearForName(id)
91
92 if not id in cache:
93 try:
94 cache[id] = creator(id)
95 except Exception as exc:
96 cache[id] = exc
97 raise
98 if isinstance(cache[id], Exception):
99 raise cache[id]
100 else:
101 return cache[id]
102
103 return func
104
105
106 def registerCache(
107 name: str,
108 cacheDict: Dict[str, Any],
109 creationFunction: Callable[[str], Any]) -> None:
110 """registers a custom cache.
111
112 This function makes creationFunction available as base.caches.name,
113 and it registers cacheDict with the cache manager such that cacheDict
114 is cleared as necessary.
115
116 creationFunction must manage cacheDict itself, and of course it
117 must always use the instance passed to registerCache.
118
119 This is for "magic" things like getRD that has to deal with aliases
120 and such. For normal use, use makeCache.
121 """
122 globals()[name] = creationFunction
123 _cacheRegistry.register(cacheDict)
124
125
126 def makeCache(
127 name: str,
128 callable: Callable[[str], Any],
129 isDirty: Optional[Callable[[Any], bool]] = None) -> None:
130 """creates a new function name to cache results to calls to callable.
131
132 isDirty can be a function returning true when the cache should be
133 cleared. The function is passed the current resource.
134 """
135 globals()[name] = _makeCache(callable, isDirty)