-
-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathvalue_initializer.rs
170 lines (154 loc) · 5.94 KB
/
value_initializer.rs
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
use async_lock::RwLock;
use std::{
any::{Any, TypeId},
future::Future,
hash::{BuildHasher, Hash},
sync::Arc,
};
type ErrorObject = Arc<dyn Any + Send + Sync + 'static>;
type WaiterValue<V> = Option<Result<V, ErrorObject>>;
type Waiter<V> = Arc<RwLock<WaiterValue<V>>>;
pub(crate) enum InitResult<V, E> {
Initialized(V),
ReadExisting(V),
InitErr(Arc<E>),
}
pub(crate) struct ValueInitializer<K, V, S> {
// TypeId is the type ID of the concrete error type of generic type E in
// try_init_or_read(). We use the type ID as a part of the key to ensure that
// we can always downcast the trait object ErrorObject (in Waiter<V>) into
// its concrete type.
waiters: moka_cht::SegmentedHashMap<(Arc<K>, TypeId), Waiter<V>, S>,
}
impl<K, V, S> ValueInitializer<K, V, S>
where
Arc<K>: Eq + Hash,
V: Clone,
S: BuildHasher,
{
pub(crate) fn with_hasher(hasher: S) -> Self {
Self {
waiters: moka_cht::SegmentedHashMap::with_num_segments_and_hasher(16, hasher),
}
}
/// # Panics
/// Panics if the `init` future has been panicked.
pub(crate) async fn init_or_read<F>(&self, key: Arc<K>, init: F) -> InitResult<V, ()>
where
F: Future<Output = V>,
{
// This closure will be called after the init closure has returned a value.
// It will convert the returned value (from init) into an InitResult.
let post_init = |_key, value: V, lock: &mut WaiterValue<V>| {
*lock = Some(Ok(value.clone()));
InitResult::Initialized(value)
};
let type_id = TypeId::of::<()>();
self.do_try_init(&key, type_id, init, post_init).await
}
/// # Panics
/// Panics if the `init` future has been panicked.
pub(crate) async fn try_init_or_read<F, E>(&self, key: Arc<K>, init: F) -> InitResult<V, E>
where
F: Future<Output = Result<V, E>>,
E: Send + Sync + 'static,
{
let type_id = TypeId::of::<E>();
// This closure will be called after the init closure has returned a value.
// It will convert the returned value (from init) into an InitResult.
let post_init = |key, value: Result<V, E>, lock: &mut WaiterValue<V>| match value {
Ok(value) => {
*lock = Some(Ok(value.clone()));
InitResult::Initialized(value)
}
Err(e) => {
let err: ErrorObject = Arc::new(e);
*lock = Some(Err(Arc::clone(&err)));
self.remove_waiter(key, type_id);
InitResult::InitErr(err.downcast().unwrap())
}
};
self.do_try_init(&key, type_id, init, post_init).await
}
/// # Panics
/// Panics if the `init` future has been panicked.
async fn do_try_init<'a, F, O, C, E>(
&self,
key: &'a Arc<K>,
type_id: TypeId,
init: F,
mut post_init: C,
) -> InitResult<V, E>
where
F: Future<Output = O>,
C: FnMut(&'a Arc<K>, O, &mut WaiterValue<V>) -> InitResult<V, E>,
E: Send + Sync + 'static,
{
use futures::future::FutureExt;
use std::panic::{resume_unwind, AssertUnwindSafe};
use InitResult::*;
const MAX_RETRIES: usize = 200;
let mut retries = 0;
loop {
let waiter = Arc::new(RwLock::new(None));
let mut lock = waiter.write().await;
match self.try_insert_waiter(key, type_id, &waiter) {
None => {
// Our waiter was inserted. Let's resolve the init future.
// Catching panic is safe here as we do not try to resolve the future again.
match AssertUnwindSafe(init).catch_unwind().await {
// Resolved.
Ok(value) => return post_init(key, value, &mut lock),
// Panicked.
Err(payload) => {
*lock = None;
// Remove the waiter so that others can retry.
self.remove_waiter(key, type_id);
resume_unwind(payload);
} // The lock will be unlocked here.
}
}
Some(res) => {
// Somebody else's waiter already exists. Drop our write lock and wait
// for a read lock to become available.
std::mem::drop(lock);
match &*res.read().await {
Some(Ok(value)) => return ReadExisting(value.clone()),
Some(Err(e)) => return InitErr(Arc::clone(e).downcast().unwrap()),
// None means somebody else's init future has been panicked.
None => {
retries += 1;
if retries < MAX_RETRIES {
// Retry from the beginning.
continue;
} else {
panic!(
r#"Too many retries. Tried to read the return value from the `init` \
future but failed {} times. Maybe the `init` kept panicking?"#,
retries
);
}
}
}
}
}
}
}
#[inline]
pub(crate) fn remove_waiter(&self, key: &Arc<K>, type_id: TypeId) {
let key = Arc::clone(key);
self.waiters.remove(&(key, type_id));
}
#[inline]
fn try_insert_waiter(
&self,
key: &Arc<K>,
type_id: TypeId,
waiter: &Waiter<V>,
) -> Option<Waiter<V>> {
let key = Arc::clone(key);
let waiter = Arc::clone(waiter);
self.waiters
.insert_with_or_modify((key, type_id), || waiter, |_, w| Arc::clone(w))
}
}