1
+ use http_cache:: { CacheManager , HttpResponse , Result } ;
2
+
3
+ use std:: { fmt, sync:: Arc } ;
4
+
5
+ use http_cache_semantics:: CachePolicy ;
6
+ use moka:: future:: Cache ;
7
+
8
+ #[ derive( Clone ) ]
9
+ pub struct MokaManager {
10
+ pub cache : Arc < Cache < String , Store > > ,
11
+ }
12
+
13
+ impl fmt:: Debug for MokaManager {
14
+ fn fmt ( & self , f : & mut fmt:: Formatter ) -> fmt:: Result {
15
+ f. debug_struct ( "MokaManager" ) . finish_non_exhaustive ( )
16
+ }
17
+ }
18
+
19
+ impl Default for MokaManager {
20
+ fn default ( ) -> Self {
21
+ Self :: new ( Cache :: new ( 42 ) )
22
+ }
23
+ }
24
+
25
+ #[ derive( Clone , Debug ) ]
26
+ pub struct Store {
27
+ response : HttpResponse ,
28
+ policy : CachePolicy ,
29
+ }
30
+
31
+ impl MokaManager {
32
+ pub fn new ( cache : Cache < String , Store > ) -> Self {
33
+ Self { cache : Arc :: new ( cache) }
34
+ }
35
+ pub async fn clear ( & self ) -> Result < ( ) > {
36
+ self . cache . invalidate_all ( ) ;
37
+ self . cache . run_pending_tasks ( ) . await ;
38
+ Ok ( ( ) )
39
+ }
40
+ }
41
+
42
+ #[ async_trait:: async_trait]
43
+ impl CacheManager for MokaManager {
44
+ async fn get (
45
+ & self ,
46
+ cache_key : & str ,
47
+ ) -> Result < Option < ( HttpResponse , CachePolicy ) > > {
48
+ let store: Store = match self . cache . get ( cache_key) . await {
49
+ Some ( d) => d,
50
+ None => return Ok ( None ) ,
51
+ } ;
52
+ Ok ( Some ( ( store. response , store. policy ) ) )
53
+ }
54
+
55
+ async fn put (
56
+ & self ,
57
+ cache_key : String ,
58
+ response : HttpResponse ,
59
+ policy : CachePolicy ,
60
+ ) -> Result < HttpResponse > {
61
+ let store = Store { response : response. clone ( ) , policy } ;
62
+ self . cache . insert ( cache_key, store) . await ;
63
+ self . cache . run_pending_tasks ( ) . await ;
64
+ Ok ( response)
65
+ }
66
+
67
+ async fn delete ( & self , cache_key : & str ) -> Result < ( ) > {
68
+ self . cache . invalidate ( cache_key) . await ;
69
+ self . cache . run_pending_tasks ( ) . await ;
70
+ Ok ( ( ) )
71
+ }
72
+ }
73
+
74
+ #[ cfg( test) ]
75
+ mod test;
0 commit comments