1use std::{
2 future::ready,
3 time::{Duration, Instant},
4};
5
6use async_trait::async_trait;
7use moka::{
8 Expiry,
9 future::Cache as MokaCache,
10 ops::compute::{CompResult, Op},
11};
12
13use super::{Error, Store};
14
15#[derive(Clone)]
17pub struct LocalStore {
18 values: MokaCache<String, StoredValue>,
19 locks: MokaCache<String, LockValue>,
20}
21
22impl LocalStore {
23 pub fn new(max_capacity: u64) -> Self {
25 Self {
26 values: MokaCache::builder().max_capacity(max_capacity).expire_after(ValueExpiry).build(),
27 locks: MokaCache::builder().max_capacity(max_capacity).expire_after(LockExpiry).build(),
28 }
29 }
30}
31
32#[async_trait]
33impl Store for LocalStore {
34 async fn get(&self, key: &str) -> Result<Option<Vec<u8>>, Error> {
35 Ok(self.values.get(key).await.map(|value| value.data))
36 }
37
38 async fn put(&self, key: &str, value: Vec<u8>, ttl: Option<Duration>) -> Result<(), Error> {
39 self.values.insert(key.to_owned(), StoredValue { data: value, expiry: EntryExpiry::Reset(ttl) }).await;
40 Ok(())
41 }
42
43 async fn add(&self, key: &str, value: Vec<u8>, ttl: Option<Duration>) -> Result<bool, Error> {
44 let entry = self
45 .values
46 .entry(key.to_owned())
47 .or_insert(StoredValue { data: value, expiry: EntryExpiry::Reset(ttl) })
48 .await;
49 Ok(entry.is_fresh())
50 }
51
52 async fn pull(&self, key: &str) -> Result<Option<Vec<u8>>, Error> {
53 let result = self
54 .values
55 .entry(key.to_owned())
56 .and_compute_with(|entry| ready(if entry.is_some() { Op::Remove } else { Op::Nop }))
57 .await;
58 Ok(match result {
59 CompResult::Removed(entry) => Some(entry.into_value().data),
60 _ => None,
61 })
62 }
63
64 async fn increment(&self, key: &str, amount: i64) -> Result<i64, Error> {
65 let logical_key = key.to_owned();
66 let result = self
67 .values
68 .entry(logical_key.clone())
69 .and_try_compute_with(|entry| {
70 let result = match entry {
71 Some(entry) => decode_integer(&logical_key, &entry.into_value().data)
72 .and_then(|current| checked_add(&logical_key, current, amount))
73 .and_then(|value| integer_value(&logical_key, value, EntryExpiry::Keep)),
74 None => integer_value(&logical_key, amount, EntryExpiry::Reset(None)),
75 }
76 .map(Op::Put);
77 ready(result)
78 })
79 .await?;
80
81 let entry = result.into_entry().ok_or_else(|| Error::NotInteger { key: logical_key.clone() })?;
82 decode_integer(&logical_key, &entry.into_value().data)
83 }
84
85 async fn touch(&self, key: &str, ttl: Duration) -> Result<bool, Error> {
86 let result = self
87 .values
88 .entry(key.to_owned())
89 .and_compute_with(|entry| {
90 ready(match entry {
91 Some(entry) => {
92 Op::Put(StoredValue { data: entry.into_value().data, expiry: EntryExpiry::Reset(Some(ttl)) })
93 }
94 None => Op::Nop,
95 })
96 })
97 .await;
98 Ok(matches!(result, CompResult::ReplacedWith(_)))
99 }
100
101 async fn forget(&self, key: &str) -> Result<bool, Error> {
102 Ok(self.values.remove(key).await.is_some())
103 }
104
105 async fn flush(&self) -> Result<(), Error> {
106 self.values.invalidate_all();
107 self.values.run_pending_tasks().await;
108 Ok(())
109 }
110
111 async fn acquire_lock(&self, key: &str, owner: &str, ttl: Option<Duration>) -> Result<bool, Error> {
112 let entry = self.locks.entry(key.to_owned()).or_insert(LockValue { owner: owner.to_owned(), ttl }).await;
113 Ok(entry.is_fresh())
114 }
115
116 async fn release_lock(&self, key: &str, owner: &str) -> Result<bool, Error> {
117 let owner = owner.to_owned();
118 let result = self
119 .locks
120 .entry(key.to_owned())
121 .and_compute_with(|entry| {
122 ready(match entry {
123 Some(entry) if entry.value().owner == owner => Op::Remove,
124 _ => Op::Nop,
125 })
126 })
127 .await;
128 Ok(matches!(result, CompResult::Removed(_)))
129 }
130
131 async fn force_release_lock(&self, key: &str) -> Result<(), Error> {
132 self.locks.invalidate(key).await;
133 Ok(())
134 }
135
136 async fn refresh_lock(&self, key: &str, owner: &str, ttl: Option<Duration>) -> Result<bool, Error> {
137 let owner = owner.to_owned();
138 let result = self
139 .locks
140 .entry(key.to_owned())
141 .and_compute_with(|entry| {
142 ready(match entry {
143 Some(entry) if entry.value().owner == owner => Op::Put(LockValue { owner, ttl }),
144 _ => Op::Nop,
145 })
146 })
147 .await;
148 Ok(matches!(result, CompResult::ReplacedWith(_)))
149 }
150
151 async fn lock_owner(&self, key: &str) -> Result<Option<String>, Error> {
152 Ok(self.locks.get(key).await.map(|lock| lock.owner))
153 }
154}
155
156#[derive(Clone)]
157struct StoredValue {
158 data: Vec<u8>,
159 expiry: EntryExpiry,
160}
161
162#[derive(Clone, Copy)]
163enum EntryExpiry {
164 Reset(Option<Duration>),
165 Keep,
166}
167
168struct ValueExpiry;
169
170impl Expiry<String, StoredValue> for ValueExpiry {
171 fn expire_after_create(&self, _key: &String, value: &StoredValue, _created_at: Instant) -> Option<Duration> {
172 match value.expiry {
173 EntryExpiry::Reset(ttl) => ttl,
174 EntryExpiry::Keep => None,
175 }
176 }
177
178 fn expire_after_update(
179 &self,
180 _key: &String,
181 value: &StoredValue,
182 _updated_at: Instant,
183 current: Option<Duration>,
184 ) -> Option<Duration> {
185 match value.expiry {
186 EntryExpiry::Reset(ttl) => ttl,
187 EntryExpiry::Keep => current,
188 }
189 }
190}
191
192#[derive(Clone)]
193struct LockValue {
194 owner: String,
195 ttl: Option<Duration>,
196}
197
198struct LockExpiry;
199
200impl Expiry<String, LockValue> for LockExpiry {
201 fn expire_after_create(&self, _key: &String, value: &LockValue, _created_at: Instant) -> Option<Duration> {
202 value.ttl
203 }
204
205 fn expire_after_update(
206 &self,
207 _key: &String,
208 value: &LockValue,
209 _updated_at: Instant,
210 _current: Option<Duration>,
211 ) -> Option<Duration> {
212 value.ttl
213 }
214}
215
216fn decode_integer(key: &str, value: &[u8]) -> Result<i64, Error> {
217 serde_json::from_slice(value).map_err(|_| Error::NotInteger { key: key.to_owned() })
218}
219
220fn checked_add(key: &str, current: i64, amount: i64) -> Result<i64, Error> {
221 current.checked_add(amount).ok_or_else(|| Error::IntegerOverflow(key.to_owned()))
222}
223
224fn integer_value(key: &str, value: i64, expiry: EntryExpiry) -> Result<StoredValue, Error> {
225 Ok(StoredValue {
226 data: serde_json::to_vec(&value).map_err(|source| Error::Encode { key: key.to_owned(), source })?,
227 expiry,
228 })
229}