asyncband/singleflight/mod.rs
1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Coalesce concurrent work that uses the same key.
19//!
20//! While work for a key is in flight, later callers wait and clone its successful value. A
21//! completed value is not cached: the entry is removed when the work succeeds, so a non-overlapping
22//! later call executes its own function.
23//!
24//! If the active call is cancelled or panics, a waiting caller may run its own function. `try_work`
25//! also lets a waiter retry after the active function returns an error. Use `OnceMap` instead when
26//! successful values should remain cached by key.
27
28use std::borrow::Borrow;
29use std::fmt;
30use std::hash::BuildHasher;
31use std::hash::Hash;
32use std::hash::RandomState;
33use std::sync::Arc;
34
35use hashbrown::HashTable;
36
37use crate::internal::mutex::Mutex;
38use crate::once::OnceCell;
39
40#[cfg(test)]
41mod tests;
42
43struct Entry<K, V> {
44 hash: u64,
45 key: K,
46 cell: OnceCell<V>,
47}
48
49/// A namespace that coalesces concurrent work by key.
50///
51/// Different keys run independently. A group neither caches completed results nor limits overall
52/// concurrency.
53pub struct Group<K, V, S = RandomState> {
54 // This lock protects only entry lookup, insertion, and removal.
55 // User work is always run after releasing it.
56 entries: Mutex<HashTable<Arc<Entry<K, V>>>>,
57 hasher: S,
58}
59
60impl<K, V, S> fmt::Debug for Group<K, V, S> {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 let in_flight = self.entries.lock().len();
63 f.debug_struct("Group")
64 .field("in_flight", &in_flight)
65 .finish()
66 }
67}
68
69impl<K, V, S> Group<K, V, S>
70where
71 K: Eq + Hash,
72 S: BuildHasher,
73{
74 fn get_or_insert(&self, key: K) -> WorkCleanupGuard<'_, K, V, S> {
75 let hash = self.hasher.hash_one(&key);
76 let mut entries = self.entries.lock();
77 if let Some(entry) = entries.find(hash, |entry| entry.key.eq(&key)) {
78 let entry = Arc::clone(entry);
79 drop(entries);
80 let guard = WorkCleanupGuard::new(self, entry);
81 // Establish cleanup before a duplicate key can unwind or reenter the group.
82 drop(key);
83 return guard;
84 }
85
86 let entry = Arc::new(Entry {
87 hash,
88 key,
89 cell: OnceCell::new(),
90 });
91 entries.insert_unique(hash, entry.clone(), |entry| entry.hash);
92 drop(entries);
93 WorkCleanupGuard::new(self, entry)
94 }
95
96 fn remove<Q>(&self, key: &Q)
97 where
98 K: Borrow<Q>,
99 Q: Eq + Hash + ?Sized,
100 {
101 let hash = self.hasher.hash_one(key);
102 let removed = {
103 let mut entries = self.entries.lock();
104 let Ok(occupied) = entries.find_entry(hash, |entry| entry.key.borrow() == key) else {
105 return;
106 };
107 occupied.remove().0
108 };
109 drop(removed);
110 }
111
112 fn remove_if_current(&self, entry: &Arc<Entry<K, V>>) {
113 let removed = {
114 let mut entries = self.entries.lock();
115 let Ok(occupied) = entries.find_entry(entry.hash, |stored| Arc::ptr_eq(stored, entry))
116 else {
117 return;
118 };
119 occupied.remove().0
120 };
121 drop(removed);
122 }
123
124 fn cleanup_abandoned_entry(&self, entry: Arc<Entry<K, V>>) {
125 let mut entries = self.entries.lock();
126 let Ok(occupied) = entries.find_entry(entry.hash, |stored| Arc::ptr_eq(stored, &entry))
127 else {
128 // `forget` detached the entry. It may be the final owner, so release it after
129 // unlocking rather than running user destructors under the table lock.
130 drop(entries);
131 drop(entry);
132 return;
133 };
134
135 // With group ownership confirmed and the table locked against new callers, two owners
136 // means the group and this cleanup guard are the only remaining references.
137 if Arc::strong_count(&entry) == 2 && !entry.cell.initialized() {
138 let (stored, _) = occupied.remove();
139 drop(entries);
140 drop(entry);
141 drop(stored);
142 } else {
143 // A waiting cleanup must observe this call's reference being released while no new
144 // caller can clone the group's reference.
145 drop(entry);
146 }
147 }
148}
149
150// Holds one call's entry so Drop can clean it up if the work is abandoned.
151struct WorkCleanupGuard<'a, K, V, S>
152where
153 K: Eq + Hash,
154 S: BuildHasher,
155{
156 group: &'a Group<K, V, S>,
157 entry: Option<Arc<Entry<K, V>>>,
158}
159
160impl<'a, K, V, S> WorkCleanupGuard<'a, K, V, S>
161where
162 K: Eq + Hash,
163 S: BuildHasher,
164{
165 fn new(group: &'a Group<K, V, S>, entry: Arc<Entry<K, V>>) -> Self {
166 Self {
167 group,
168 entry: Some(entry),
169 }
170 }
171
172 fn entry(&self) -> &Arc<Entry<K, V>> {
173 self.entry.as_ref().unwrap()
174 }
175
176 fn dismiss(mut self) {
177 drop(self.entry.take());
178 }
179}
180
181impl<K, V, S> Drop for WorkCleanupGuard<'_, K, V, S>
182where
183 K: Eq + Hash,
184 S: BuildHasher,
185{
186 fn drop(&mut self) {
187 let Some(entry) = self.entry.take() else {
188 return;
189 };
190
191 self.group.cleanup_abandoned_entry(entry);
192 }
193}
194
195impl<K, V, S> Default for Group<K, V, S>
196where
197 K: Eq + Hash,
198 V: Clone,
199 S: BuildHasher + Default,
200{
201 fn default() -> Self {
202 Self::with_hasher(S::default())
203 }
204}
205
206impl<K, V> Group<K, V, RandomState>
207where
208 K: Eq + Hash,
209 V: Clone,
210{
211 /// Creates a new Group with the default hasher.
212 pub fn new() -> Self {
213 Self::with_hasher(RandomState::new())
214 }
215}
216
217impl<K, V, S> Group<K, V, S>
218where
219 K: Eq + Hash,
220 V: Clone,
221 S: BuildHasher,
222{
223 /// Creates a new Group with the given hasher.
224 pub fn with_hasher(hasher: S) -> Self {
225 Self {
226 entries: Mutex::new(HashTable::new()),
227 hasher,
228 }
229 }
230
231 /// Executes and returns the results of the given function, making sure that only one execution
232 /// is in-flight for a given key at a time.
233 ///
234 /// If a duplicate comes in, the duplicate caller waits for the original to complete and
235 /// receives the same results.
236 ///
237 /// If the computation is cancelled or panics, another caller waiting for the same key may retry
238 /// it.
239 ///
240 /// Once the function completes, the key, if not [`forgotten`], is removed from the group,
241 /// allowing future calls with the same key to execute the function again.
242 ///
243 /// [`forgotten`]: Self::forget
244 ///
245 /// # Deadlocks
246 ///
247 /// The function must not recursively call `work` or `try_work` for the same current key because
248 /// it would wait for its own result. Work for other keys remains independent.
249 ///
250 /// # Examples
251 ///
252 /// ```
253 /// use std::sync::Arc;
254 /// use std::sync::atomic::AtomicUsize;
255 /// use std::sync::atomic::Ordering;
256 /// use std::time::Duration;
257 ///
258 /// use asyncband::singleflight::Group;
259 ///
260 /// # #[tokio::main]
261 /// # async fn main() {
262 /// let group = Group::new();
263 /// let counter = Arc::new(AtomicUsize::new(0));
264 ///
265 /// let c1 = counter.clone();
266 /// let fut1 = group.work("key", || async move {
267 /// c1.fetch_add(1, Ordering::SeqCst);
268 /// // simulate heavy work to avoid immediate completion
269 /// tokio::time::sleep(Duration::from_millis(100)).await;
270 /// "result"
271 /// });
272 ///
273 /// let c2 = counter.clone();
274 /// let fut2 = group.work("key", || async move {
275 /// c2.fetch_add(1, Ordering::SeqCst);
276 /// // simulate heavy work to avoid immediate completion
277 /// tokio::time::sleep(Duration::from_millis(100)).await;
278 /// "result"
279 /// });
280 ///
281 /// let (r1, r2) = tokio::join!(fut1, fut2);
282 ///
283 /// assert_eq!(r1, r2);
284 /// assert_eq!(counter.load(Ordering::SeqCst), 1);
285 /// # }
286 /// ```
287 pub async fn work<F>(&self, key: K, func: F) -> V
288 where
289 F: AsyncFnOnce() -> V,
290 {
291 let guard = self.get_or_insert(key);
292 let entry = guard.entry();
293 let result = entry
294 .cell
295 .get_or_init(async || {
296 let result = func().await;
297 self.remove_if_current(entry);
298 result
299 })
300 .await
301 .clone();
302 guard.dismiss();
303 result
304 }
305
306 /// Executes and returns the results of the given function, making sure that only one execution
307 /// is in-flight for a given key at a time.
308 ///
309 /// If a duplicate comes in, the duplicate caller waits for the original to complete and
310 /// receives the same results.
311 ///
312 /// If the computation returns an error, it is returned to that caller. After an error,
313 /// cancellation, or panic, another caller may retry the computation.
314 ///
315 /// Once the function completes successfully, the key, if not [`forgotten`], is removed from
316 /// the group, allowing future calls with the same key to execute the function again.
317 ///
318 /// [`forgotten`]: Self::forget
319 ///
320 /// # Deadlocks
321 ///
322 /// The function must not recursively call `work` or `try_work` for the same current key because
323 /// it would wait for its own result. Work for other keys remains independent.
324 ///
325 /// # Examples
326 ///
327 /// ```
328 /// use std::sync::Arc;
329 /// use std::sync::atomic::AtomicUsize;
330 /// use std::sync::atomic::Ordering;
331 /// use std::time::Duration;
332 ///
333 /// use asyncband::singleflight::Group;
334 ///
335 /// # #[tokio::main]
336 /// # async fn main() {
337 /// let group = Group::new();
338 ///
339 /// let fut1 = group.try_work("key", || async move {
340 /// // simulate heavy work to avoid immediate completion
341 /// tokio::time::sleep(Duration::from_millis(100)).await;
342 /// Err::<_, &'static str>("fut1")
343 /// });
344 ///
345 /// let fut2 = group.try_work("key", || async move {
346 /// // simulate heavy work to avoid immediate completion
347 /// tokio::time::sleep(Duration::from_millis(200)).await;
348 /// Ok::<_, &'static str>("fut2")
349 /// });
350 ///
351 /// let (r1, r2) = tokio::join!(fut1, fut2);
352 ///
353 /// assert_eq!(r1, Err("fut1"));
354 /// assert_eq!(r2, Ok("fut2"));
355 /// # }
356 /// ```
357 pub async fn try_work<E, F>(&self, key: K, func: F) -> Result<V, E>
358 where
359 F: AsyncFnOnce() -> Result<V, E>,
360 {
361 let guard = self.get_or_insert(key);
362 let entry = guard.entry();
363 let result = entry
364 .cell
365 .get_or_try_init(async || {
366 let result = func().await?;
367 self.remove_if_current(entry);
368 Ok(result)
369 })
370 .await?
371 .clone();
372 guard.dismiss();
373 Ok(result)
374 }
375
376 /// Forgets about the given key.
377 ///
378 /// Future calls to `work` for this key will call the function rather than waiting for an
379 /// earlier call to complete. Existing calls to `work` for this key are not affected.
380 pub fn forget<Q>(&self, key: &Q)
381 where
382 K: Borrow<Q>,
383 Q: Hash + Eq + ?Sized,
384 {
385 self.remove(key);
386 }
387}