|
18 | 18 | TYPE_CHECKING,
|
19 | 19 | Any,
|
20 | 20 | Callable,
|
| 21 | + Collection, |
21 | 22 | Dict,
|
22 | 23 | Generator,
|
23 | 24 | Iterable,
|
|
126 | 127 | from synapse.types.state import StateFilter
|
127 | 128 | from synapse.util import Clock
|
128 | 129 | from synapse.util.async_helpers import maybe_awaitable
|
129 |
| -from synapse.util.caches.descriptors import CachedFunction, cached |
| 130 | +from synapse.util.caches.descriptors import CachedFunction, cached as _cached |
130 | 131 | from synapse.util.frozenutils import freeze
|
131 | 132 |
|
132 | 133 | if TYPE_CHECKING:
|
|
136 | 137 |
|
137 | 138 | T = TypeVar("T")
|
138 | 139 | P = ParamSpec("P")
|
| 140 | +F = TypeVar("F", bound=Callable[..., Any]) |
139 | 141 |
|
140 | 142 | """
|
141 | 143 | This package defines the 'stable' API which can be used by extension modules which
|
@@ -185,6 +187,42 @@ class UserIpAndAgent:
|
185 | 187 | last_seen: int
|
186 | 188 |
|
187 | 189 |
|
| 190 | +def cached( |
| 191 | + *, |
| 192 | + max_entries: int = 1000, |
| 193 | + num_args: Optional[int] = None, |
| 194 | + uncached_args: Optional[Collection[str]] = None, |
| 195 | +) -> Callable[[F], CachedFunction[F]]: |
| 196 | + """Returns a decorator that applies a memoizing cache around the function. This |
| 197 | + decorator behaves similarly to functools.lru_cache. |
| 198 | +
|
| 199 | + Example: |
| 200 | +
|
| 201 | + @cached() |
| 202 | + def foo('a', 'b'): |
| 203 | + ... |
| 204 | +
|
| 205 | + Added in Synapse v1.74.0. |
| 206 | +
|
| 207 | + Args: |
| 208 | + max_entries: The maximum number of entries in the cache. If the cache is full |
| 209 | + and a new entry is added, the least recently accessed entry will be evicted |
| 210 | + from the cache. |
| 211 | + num_args: The number of positional arguments (excluding `self`) to use as cache |
| 212 | + keys. Defaults to all named args of the function. |
| 213 | + uncached_args: A list of argument names to not use as the cache key. (`self` is |
| 214 | + always ignored.) Cannot be used with num_args. |
| 215 | +
|
| 216 | + Returns: |
| 217 | + A decorator that applies a memoizing cache around the function. |
| 218 | + """ |
| 219 | + return _cached( |
| 220 | + max_entries=max_entries, |
| 221 | + num_args=num_args, |
| 222 | + uncached_args=uncached_args, |
| 223 | + ) |
| 224 | + |
| 225 | + |
188 | 226 | class ModuleApi:
|
189 | 227 | """A proxy object that gets passed to various plugin modules so they
|
190 | 228 | can register new users etc if necessary.
|
|
0 commit comments