1
1
import asyncio
2
+ from functools import _make_key as make_key
2
3
from typing import Awaitable , Callable , Hashable , Literal , TypeVar
3
4
4
5
from typing_extensions import ParamSpec
5
6
6
- from pgcachewatch import strategies , utils
7
+ from pgcachewatch import strategies
7
8
from pgcachewatch .logconfig import logger
8
9
9
10
P = ParamSpec ("P" )
12
13
13
14
def cache (
14
15
strategy : strategies .Strategy ,
15
- statistics_callback : Callable [[Literal ["hit" , "miss" ]], None ] | None = None ,
16
+ statistics_callback : Callable [[Literal ["hit" , "miss" ]], None ] = lambda _ : None ,
16
17
) -> Callable [[Callable [P , Awaitable [T ]]], Callable [P , Awaitable [T ]]]:
17
18
def outer (fn : Callable [P , Awaitable [T ]]) -> Callable [P , Awaitable [T ]]:
18
19
cached = dict [Hashable , asyncio .Future [T ]]()
@@ -29,24 +30,20 @@ async def inner(*args: P.args, **kwargs: P.kwargs) -> T:
29
30
logger .debug ("Cache clear" )
30
31
cached .clear ()
31
32
32
- key = utils . make_key (args , kwargs )
33
+ key = make_key (args , kwargs , typed = False )
33
34
34
35
try :
35
36
waiter = cached [key ]
36
37
except KeyError :
37
38
# Cache miss
38
- ...
39
+ logger .debug ("Cache miss" )
40
+ statistics_callback ("miss" )
39
41
else :
40
42
# Cache hit
41
43
logger .debug ("Cache hit" )
42
- if statistics_callback :
43
- statistics_callback ("hit" )
44
+ statistics_callback ("hit" )
44
45
return await waiter
45
46
46
- logger .debug ("Cache miss" )
47
- if statistics_callback :
48
- statistics_callback ("miss" )
49
-
50
47
# Initialize Future to prevent cache stampedes.
51
48
cached [key ] = waiter = asyncio .Future [T ]()
52
49
0 commit comments