forked from moka-rs/moka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalue_initializer.rs
208 lines (187 loc) · 7.78 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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
use parking_lot::RwLock;
use std::{
any::{Any, TypeId},
hash::{BuildHasher, Hash},
sync::Arc,
};
use triomphe::Arc as TrioArc;
use super::OptionallyNone;
const WAITER_MAP_NUM_SEGMENTS: usize = 64;
type ErrorObject = Arc<dyn Any + Send + Sync + 'static>;
type WaiterValue<V> = Option<Result<V, ErrorObject>>;
type Waiter<V> = TrioArc<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 the
// try_get_with method. 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: crate::cht::SegmentedHashMap<(Arc<K>, TypeId), Waiter<V>, S>,
}
impl<K, V, S> ValueInitializer<K, V, S>
where
K: Eq + Hash,
V: Clone,
S: BuildHasher,
{
pub(crate) fn with_hasher(hasher: S) -> Self {
Self {
waiters: crate::cht::SegmentedHashMap::with_num_segments_and_hasher(
WAITER_MAP_NUM_SEGMENTS,
hasher,
),
}
}
/// # Panics
/// Panics if the `init` closure has been panicked.
pub(crate) fn try_init_or_read<O, E>(
&self,
key: &Arc<K>,
type_id: TypeId,
// Closure to get an existing value from cache.
mut get: impl FnMut() -> Option<V>,
// Closure to initialize a new value.
init: impl FnOnce() -> O,
// Closure to insert a new value into cache.
mut insert: impl FnMut(V),
// Function to convert a value O, returned from the init future, into
// Result<V, E>.
post_init: fn(O) -> Result<V, E>,
) -> InitResult<V, E>
where
E: Send + Sync + 'static,
{
use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
use InitResult::*;
const MAX_RETRIES: usize = 200;
let mut retries = 0;
let (cht_key, hash) = self.cht_key_hash(key, type_id);
loop {
let waiter = TrioArc::new(RwLock::new(None));
let mut lock = waiter.write();
match self.try_insert_waiter(cht_key.clone(), hash, &waiter) {
None => {
// Our waiter was inserted.
// Check if the value has already been inserted by other thread.
if let Some(value) = get() {
// Yes. Set the waiter value, remove our waiter, and return
// the existing value.
*lock = Some(Ok(value.clone()));
self.remove_waiter(cht_key, hash);
return InitResult::ReadExisting(value);
}
// The value still does note exist. Let's evaluate the init
// closure. Catching panic is safe here as we do not try to
// evaluate the closure again.
match catch_unwind(AssertUnwindSafe(init)) {
// Evaluated.
Ok(value) => {
let (waiter_val, init_res) = match post_init(value) {
Ok(value) => {
insert(value.clone());
(Some(Ok(value.clone())), InitResult::Initialized(value))
}
Err(e) => {
let err: ErrorObject = Arc::new(e);
(
Some(Err(Arc::clone(&err))),
InitResult::InitErr(err.downcast().unwrap()),
)
}
};
*lock = waiter_val;
self.remove_waiter(cht_key, hash);
return init_res;
}
// Panicked.
Err(payload) => {
*lock = None;
// Remove the waiter so that others can retry.
self.remove_waiter(cht_key, hash);
resume_unwind(payload);
}
} // The write lock will be unlocked here.
}
Some(res) => {
// Somebody else's waiter already exists. Drop our write lock and
// wait for the read lock to become available.
std::mem::drop(lock);
match &*res.read() {
Some(Ok(value)) => return ReadExisting(value.clone()),
Some(Err(e)) => return InitErr(Arc::clone(e).downcast().unwrap()),
// None means somebody else's init closure has been panicked.
None => {
retries += 1;
if retries < MAX_RETRIES {
// Retry from the beginning.
continue;
} else {
panic!(
"Too many retries. Tried to read the return value from the `init` \
closure but failed {} times. Maybe the `init` kept panicking?",
retries
);
}
}
}
}
}
}
}
/// The `post_init` function for the `get_with` method of cache.
pub(crate) fn post_init_for_get_with(value: V) -> Result<V, ()> {
Ok(value)
}
/// The `post_init` function for the `optionally_get_with` method of cache.
pub(crate) fn post_init_for_optionally_get_with(
value: Option<V>,
) -> Result<V, Arc<OptionallyNone>> {
// `value` can be either `Some` or `None`. For `None` case, without change
// the existing API too much, we will need to convert `None` to Arc<E> here.
// `Infallible` could not be instantiated. So it might be good to use an
// empty struct to indicate the error type.
value.ok_or(Arc::new(OptionallyNone))
}
/// The `post_init` function for `try_get_with` method of cache.
pub(crate) fn post_init_for_try_get_with<E>(result: Result<V, E>) -> Result<V, E> {
result
}
/// Returns the `type_id` for `get_with` method of cache.
pub(crate) fn type_id_for_get_with() -> TypeId {
// NOTE: We use a regular function here instead of a const fn because TypeId
// is not stable as a const fn. (as of our MSRV)
TypeId::of::<()>()
}
/// Returns the `type_id` for `optionally_get_with` method of cache.
pub(crate) fn type_id_for_optionally_get_with() -> TypeId {
TypeId::of::<OptionallyNone>()
}
/// Returns the `type_id` for `try_get_with` method of cache.
pub(crate) fn type_id_for_try_get_with<E: 'static>() -> TypeId {
TypeId::of::<E>()
}
#[inline]
fn remove_waiter(&self, cht_key: (Arc<K>, TypeId), hash: u64) {
self.waiters.remove(hash, |k| k == &cht_key);
}
#[inline]
fn try_insert_waiter(
&self,
cht_key: (Arc<K>, TypeId),
hash: u64,
waiter: &Waiter<V>,
) -> Option<Waiter<V>> {
let waiter = TrioArc::clone(waiter);
self.waiters.insert_if_not_present(cht_key, hash, waiter)
}
#[inline]
fn cht_key_hash(&self, key: &Arc<K>, type_id: TypeId) -> ((Arc<K>, TypeId), u64) {
let cht_key = (Arc::clone(key), type_id);
let hash = self.waiters.hash(&cht_key);
(cht_key, hash)
}
}