1use std::future::Future;
11use std::pin::Pin;
12use std::sync::{Arc, Mutex};
13use std::time::{Duration, Instant};
14
15pub trait SecondaryStorage: Send + Sync + 'static {
21 fn get(&self, key: &str) -> impl Future<Output = Result<Option<String>, StorageError>> + Send;
23
24 fn set(
27 &self,
28 key: &str,
29 value: &str,
30 ttl: Option<Duration>,
31 ) -> impl Future<Output = Result<(), StorageError>> + Send;
32
33 fn delete(&self, key: &str) -> impl Future<Output = Result<(), StorageError>> + Send;
35
36 fn increment(
41 &self,
42 key: &str,
43 ttl: Duration,
44 ) -> impl Future<Output = Result<u64, StorageError>> + Send;
45}
46
47#[derive(Debug, thiserror::Error)]
49#[error("secondary storage: {0}")]
50pub struct StorageError(#[source] Box<dyn std::error::Error + Send + Sync>);
51
52impl StorageError {
53 pub fn new(err: impl std::error::Error + Send + Sync + 'static) -> Self {
54 Self(Box::new(err))
55 }
56}
57
58type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
59
60pub(crate) trait DynStorage: Send + Sync {
62 fn increment<'a>(
63 &'a self,
64 key: &'a str,
65 ttl: Duration,
66 ) -> BoxFuture<'a, Result<u64, StorageError>>;
67}
68
69impl<S: SecondaryStorage> DynStorage for S {
70 fn increment<'a>(
71 &'a self,
72 key: &'a str,
73 ttl: Duration,
74 ) -> BoxFuture<'a, Result<u64, StorageError>> {
75 Box::pin(SecondaryStorage::increment(self, key, ttl))
76 }
77}
78
79pub const DEFAULT_STORAGE_TIMEOUT: Duration = Duration::from_millis(100);
84
85const BREAKER_THRESHOLD: u32 = 5;
87
88const BREAKER_COOL_DOWN: Duration = Duration::from_secs(5);
90
91pub(crate) struct GuardedStorage {
96 inner: Arc<dyn DynStorage>,
97 timeout: Duration,
98 threshold: u32,
99 cool_down: Duration,
100 breaker: Mutex<Breaker>,
101}
102
103#[derive(Default)]
104struct Breaker {
105 failures: u32,
106 open_until: Option<Instant>,
107}
108
109impl GuardedStorage {
110 pub(crate) fn new(inner: Arc<dyn DynStorage>, timeout: Duration) -> Self {
111 Self {
112 inner,
113 timeout,
114 threshold: BREAKER_THRESHOLD,
115 cool_down: BREAKER_COOL_DOWN,
116 breaker: Mutex::default(),
117 }
118 }
119
120 #[cfg(test)]
121 pub(crate) fn with_breaker(mut self, threshold: u32, cool_down: Duration) -> Self {
122 self.threshold = threshold;
123 self.cool_down = cool_down;
124 self
125 }
126
127 pub(crate) async fn increment(&self, key: &str, ttl: Duration) -> Result<u64, StorageError> {
128 if !self.admit() {
129 return Err(StorageError::new(std::io::Error::other(format!(
130 "skipped after {} failures in a row; probing again every {:?}",
131 self.threshold, self.cool_down
132 ))));
133 }
134 let result = tokio::time::timeout(self.timeout, self.inner.increment(key, ttl))
135 .await
136 .unwrap_or_else(|_| {
137 Err(StorageError::new(std::io::Error::new(
138 std::io::ErrorKind::TimedOut,
139 format!("no answer within {:?}", self.timeout),
140 )))
141 });
142 self.record(result.is_ok());
143 result
144 }
145
146 fn admit(&self) -> bool {
149 let mut breaker = self.breaker.lock().unwrap();
150 let now = Instant::now();
151 match breaker.open_until {
152 Some(until) if now < until => false,
153 Some(_) => {
154 breaker.open_until = Some(now + self.cool_down);
155 true
156 }
157 None => true,
158 }
159 }
160
161 fn record(&self, ok: bool) {
162 let mut breaker = self.breaker.lock().unwrap();
163 if ok {
164 *breaker = Breaker::default();
165 return;
166 }
167 breaker.failures = breaker.failures.saturating_add(1);
168 if breaker.failures >= self.threshold {
169 breaker.open_until = Some(Instant::now() + self.cool_down);
170 }
171 }
172}
173
174#[cfg(test)]
176pub(crate) mod fake {
177 use std::collections::HashMap;
178 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
179 use std::sync::{Arc, Mutex, MutexGuard};
180 use std::time::{Duration, Instant};
181
182 use super::{SecondaryStorage, StorageError};
183
184 type Entries = HashMap<String, (String, Option<Instant>)>;
185
186 #[derive(Clone, Default)]
187 pub(crate) struct FakeStorage {
188 entries: Arc<Mutex<Entries>>,
189 down: Arc<AtomicBool>,
190 hanging: Arc<AtomicBool>,
191 increments: Arc<AtomicUsize>,
192 }
193
194 impl FakeStorage {
195 pub(crate) fn set_down(&self, down: bool) {
197 self.down.store(down, Ordering::SeqCst);
198 }
199
200 pub(crate) fn set_hanging(&self, hanging: bool) {
202 self.hanging.store(hanging, Ordering::SeqCst);
203 }
204
205 pub(crate) fn increments(&self) -> usize {
207 self.increments.load(Ordering::SeqCst)
208 }
209
210 pub(crate) fn keys(&self) -> Vec<String> {
211 self.entries.lock().unwrap().keys().cloned().collect()
212 }
213
214 fn live(&self) -> Result<MutexGuard<'_, Entries>, StorageError> {
215 if self.down.load(Ordering::SeqCst) {
216 return Err(StorageError::new(std::io::Error::other(
217 "connection refused",
218 )));
219 }
220 let mut entries = self.entries.lock().unwrap();
221 let now = Instant::now();
222 entries.retain(|_, (_, expires)| expires.is_none_or(|at| at > now));
223 Ok(entries)
224 }
225 }
226
227 fn expiry(ttl: Duration) -> Instant {
228 Instant::now() + ttl.max(Duration::from_millis(1))
229 }
230
231 impl SecondaryStorage for FakeStorage {
232 async fn get(&self, key: &str) -> Result<Option<String>, StorageError> {
233 Ok(self.live()?.get(key).map(|(value, _)| value.clone()))
234 }
235
236 async fn set(
237 &self,
238 key: &str,
239 value: &str,
240 ttl: Option<Duration>,
241 ) -> Result<(), StorageError> {
242 self.live()?
243 .insert(key.to_owned(), (value.to_owned(), ttl.map(expiry)));
244 Ok(())
245 }
246
247 async fn delete(&self, key: &str) -> Result<(), StorageError> {
248 self.live()?.remove(key);
249 Ok(())
250 }
251
252 async fn increment(&self, key: &str, ttl: Duration) -> Result<u64, StorageError> {
253 self.increments.fetch_add(1, Ordering::SeqCst);
254 if self.hanging.load(Ordering::SeqCst) {
255 std::future::pending::<()>().await;
256 }
257 let mut entries = self.live()?;
258 let (value, _) = entries
259 .entry(key.to_owned())
260 .or_insert_with(|| ("0".into(), Some(expiry(ttl))));
261 let next = value
262 .parse::<u64>()
263 .map_err(|_| StorageError::new(std::io::Error::other("not a counter")))?
264 + 1;
265 *value = next.to_string();
266 Ok(next)
267 }
268 }
269
270 #[tokio::test]
271 async fn fake_storage_passes_the_conformance_suite() {
272 crate::testing::run_storage_conformance(FakeStorage::default()).await;
273 }
274}