Repository navigation
Expand file tree
/
Copy pathcorofunc_cache.py
More file actions
239 lines (184 loc) · 7.97 KB
/
Copy pathcorofunc_cache.py
File metadata and controls
239 lines (184 loc) · 7.97 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# Copyright 2020-present Michael Hall
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
__lazy_modules__: list[str] = ["asyncio"]
import asyncio
import concurrent.futures as cf
from functools import partial, wraps
from . import _typings as t
from ._paramkey import make_key
from .lru import LRU
__all__ = ("corocache", "lrucorocache")
type CoroFunc[**P, R] = t.Callable[P, t.Coroutine[t.Any, t.Any, R]]
type CoroLike[**P, R] = t.Callable[P, t.Awaitable[R]]
#: Note CacheTransformers recieve a tuple (args) and dict(kwargs)
#: rather than a ParamSpec of the decorated function.
#: Warning: Mutations will impact callsite, return new objects as needed.
type CacheTransformer = t.Callable[
[tuple[t.Any, ...], t.Mapping[str, t.Any]],
tuple[tuple[t.Any, ...], t.Mapping[str, t.Any]],
]
TYPE_CHECKING = False
if TYPE_CHECKING:
import typing
class CoroCacheDeco(typing.Protocol):
def __call__[**P, R](self, c: CoroLike[P, R], /) -> CoroFunc[P, R]: ...
else:
class ExprWrapper:
"""Wrapper since call expressions aren't allowed in type statements."""
def __class_getitem__(cls, key: None) -> t.Any:
import typing
class CoroCacheDeco(typing.Protocol):
def __call__[**P, R](self, c: CoroLike[P, R], /) -> CoroFunc[P, R]: ...
return CoroCacheDeco
type CoroCacheDeco = ExprWrapper[None]
def _chain_fut[R](c_fut: cf.Future[R], a_fut: asyncio.Future[R]) -> None:
if a_fut.cancelled():
c_fut.cancel()
elif exc := a_fut.exception():
c_fut.set_exception(exc)
else:
c_fut.set_result(a_fut.result())
def corocache(
ttl: float | None = None,
*,
cache_transform: CacheTransformer | None = None,
evict_on_exception: bool = False,
) -> CoroCacheDeco:
"""Cache the results of the decorated coroutine.
This is less powerful than the version in task_cache.py but may work better
for some cases where typing of libraries this interacts with is too
restrictive.
Note: This by default uses the args and kwargs of the original coroutine
function as a cache key.
This includes instances (self) when wrapping methods.
Consider not wrapping instance methods, but what those methods call when
feasible in cases where this may matter, or using a cache transform.
The ordering of args and kwargs matters.
Parameters
----------
ttl: float | None
The time to live in seconds for cached results.
Defaults to None (forever)
cache_transform: CacheTransformer | None
An optional callable that transforms args and kwargs used
as a cache key.
evict_on_exception: bool
When True, exceptions are not cached *after being raised*.
multiple callers prior to the completion will still recieve the
same exception.
Returns
-------
A decorator which wraps coroutine-like functions with preemptive caching.
"""
if cache_transform is None:
key_func = make_key
else:
def key_func(args: tuple[t.Any, ...], kwds: t.Mapping[t.Any, t.Any], /) -> t.Hashable:
return make_key(*cache_transform(args, kwds))
def wrapper[**P, R](coro: CoroLike[P, R], /) -> CoroFunc[P, R]:
internal_cache: dict[t.Hashable, cf.Future[R]] = {}
internal_taskset: set[asyncio.Task[R]] = set()
def _internal_cache_evict(key: t.Hashable, task: cf.Future[R]) -> None:
if evict_on_exception and (task.cancelled() or task.exception() is not None):
internal_cache.pop(key)
elif ttl is not None:
loop = asyncio.get_running_loop()
loop.call_later(ttl, internal_cache.pop, key)
@wraps(coro)
async def wrapped(*args: P.args, **kwargs: P.kwargs) -> R:
key = key_func(args, kwargs)
ours: cf.Future[R] = cf.Future()
cached = internal_cache.setdefault(key, ours)
if cached is not ours:
return await asyncio.wrap_future(cached)
cb = partial(_internal_cache_evict, key)
ours.add_done_callback(cb)
c = coro(*args, **kwargs)
a_fut = asyncio.ensure_future(c)
internal_taskset.add(a_fut)
a_fut.add_done_callback(internal_taskset.discard)
a_fut.add_done_callback(partial(_chain_fut, ours))
return await a_fut
return wrapped
return wrapper
def lrucorocache(
ttl: float | None = None,
maxsize: int = 1024,
*,
cache_transform: CacheTransformer | None = None,
evict_on_exception: bool = False,
) -> CoroCacheDeco:
"""Cache the results of the decorated coroutine.
This is less powerful than the version in task_cache.py but may work better
for some cases where typing of libraries this interacts with is too
restrictive.
Note: This by default uses the args and kwargs of the original coroutine
function as a cache key.
This includes instances (self) when wrapping methods.
Consider not wrapping instance methods, but what those methods call when
feasible in cases where this may matter, or using a cache transform.
The ordering of args and kwargs matters.
Cached results are evicted by LRU and ttl.
Parameters
----------
ttl: float | None
The time to live in seconds for cached results.
Defaults to None (forever)
maxsize: int
The maximum number of items to retain no matter if they have reached
expiration by ttl or not.
Items evicted by this policy are evicted by least recent use.
cache_transform: CacheTransformer | None
An optional callable that transforms args and kwargs used
as a cache key.
evict_on_exception: bool
When True, exceptions are not cached *after being raised*.
multiple callers prior to the completion will still recieve the
same exception.
Returns
-------
A decorator which wraps coroutine-like functions with preemptive caching.
"""
if cache_transform is None:
key_func = make_key
else:
def key_func(args: tuple[t.Any, ...], kwds: t.Mapping[t.Any, t.Any], /) -> t.Hashable:
return make_key(*cache_transform(args, kwds))
def wrapper[**P, R](coro: CoroLike[P, R], /) -> CoroFunc[P, R]:
internal_cache: LRU[t.Hashable, cf.Future[R]] = LRU(maxsize)
internal_taskset: set[asyncio.Task[R]] = set()
def _internal_cache_evict(key: t.Hashable, task: cf.Future[R]) -> None:
if evict_on_exception and (task.cancelled() or task.exception() is not None):
internal_cache.remove(key)
elif ttl is not None:
loop = asyncio.get_running_loop()
loop.call_later(ttl, internal_cache.remove, key)
@wraps(coro)
async def wrapped(*args: P.args, **kwargs: P.kwargs) -> R:
key = key_func(args, kwargs)
ours: cf.Future[R] = cf.Future()
cached = internal_cache.setdefault(key, ours)
if cached is not ours:
return await asyncio.wrap_future(cached)
cb = partial(_internal_cache_evict, key)
ours.add_done_callback(cb)
c = coro(*args, **kwargs)
a_fut = asyncio.ensure_future(c)
internal_taskset.add(a_fut)
a_fut.add_done_callback(internal_taskset.discard)
a_fut.add_done_callback(partial(_chain_fut, ours))
return await a_fut
return wrapped
return wrapper