rs-singleflight 0.1.2

Cancellation-safe asynchronous request coalescing
Documentation
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
//! Asynchronous request coalescing with cancellation-safe recovery.
//!
//! [`Group`] executes at most one operation for a key at a time. Concurrent
//! callers wait for the same result, while operations for different keys can
//! run independently. [`CachedGroup`] adds a success-only TTL cache.

use std::{
    collections::HashMap,
    future::Future,
    hash::Hash,
    sync::{Arc, Weak},
    time::{Duration, Instant},
};

use parking_lot::{Mutex, RwLock};
use tokio::sync::Notify;

/// A result shared without requiring either its value or error to implement
/// [`Clone`].
pub type SharedResult<V, E> = Arc<Result<V, E>>;

enum FlightState<V, E> {
    Running,
    Complete(SharedResult<V, E>),
    Aborted,
}

struct Flight<V, E> {
    state: Mutex<FlightState<V, E>>,
    changed: Notify,
}

impl<V, E> Flight<V, E> {
    fn new() -> Self {
        Self {
            state: Mutex::new(FlightState::Running),
            changed: Notify::new(),
        }
    }

    async fn wait(&self) -> Option<SharedResult<V, E>> {
        loop {
            // Register before reading the state so a publication between the
            // state check and await cannot be lost.
            let changed = self.changed.notified();
            tokio::pin!(changed);
            changed.as_mut().enable();

            {
                let state = self.state.lock();
                match &*state {
                    FlightState::Running => {}
                    FlightState::Complete(result) => return Some(Arc::clone(result)),
                    FlightState::Aborted => return None,
                }
            }

            changed.await;
        }
    }

    fn publish(&self, result: SharedResult<V, E>) {
        let mut state = self.state.lock();
        debug_assert!(matches!(*state, FlightState::Running));
        *state = FlightState::Complete(result);
    }

    fn abort(&self) -> bool {
        let mut state = self.state.lock();
        if matches!(*state, FlightState::Running) {
            *state = FlightState::Aborted;
            true
        } else {
            false
        }
    }

    fn wake_waiters(&self) {
        self.changed.notify_waiters();
    }
}

/// Coalesces concurrent asynchronous operations by key.
///
/// The registry stores weak references, so dropping or aborting the caller
/// executing an operation cannot leave a permanently live entry behind.
/// Internal locks are synchronous and are never held across an `.await`.
pub struct Group<K, V, E> {
    flights: Mutex<HashMap<K, Weak<Flight<V, E>>>>,
}

impl<K, V, E> Group<K, V, E> {
    /// Creates an empty group.
    #[must_use]
    pub fn new() -> Self {
        Self {
            flights: Mutex::new(HashMap::new()),
        }
    }
}

impl<K, V, E> Group<K, V, E>
where
    K: Eq + Hash + Clone,
{
    /// Runs `operation` or waits for the operation already running for `key`.
    ///
    /// This variant returns an [`Arc`] and therefore supports non-[`Clone`]
    /// values and errors. If the current leader is cancelled or panics, one
    /// waiting caller retries the acquisition and becomes the new leader,
    /// re-executing its own operation.
    pub async fn do_call_shared<F, Fut>(&self, key: K, operation: F) -> SharedResult<V, E>
    where
        F: FnOnce() -> Fut,
        Fut: Future<Output = Result<V, E>>,
    {
        let mut operation = Some(operation);

        loop {
            let (flight, is_leader) = self.acquire(&key);
            if !is_leader {
                if let Some(result) = flight.wait().await {
                    return result;
                }
                self.remove_if_current(&key, &flight);
                continue;
            }

            let guard = LeaderGuard::new(self, &key, flight);
            let operation = operation
                .take()
                .expect("singleflight operation can only be executed once");
            let result = operation().await;
            return guard.complete(result);
        }
    }

    /// Runs `operation` or waits for the operation already running for `key`.
    ///
    /// Prefer [`Group::do_call_shared`] when cloning a large value is
    /// undesirable or the value/error is not [`Clone`].
    pub async fn do_call<F, Fut>(&self, key: K, operation: F) -> Result<V, E>
    where
        V: Clone,
        E: Clone,
        F: FnOnce() -> Fut,
        Fut: Future<Output = Result<V, E>>,
    {
        let result = self.do_call_shared(key, operation).await;
        match result.as_ref() {
            Ok(value) => Ok(value.clone()),
            Err(error) => Err(error.clone()),
        }
    }

    fn acquire(&self, key: &K) -> (Arc<Flight<V, E>>, bool) {
        let mut flights = self.flights.lock();

        if let Some(flight) = flights.get(key).and_then(Weak::upgrade) {
            return (flight, false);
        }

        let flight = Arc::new(Flight::new());
        flights.insert(key.clone(), Arc::downgrade(&flight));
        (flight, true)
    }

    fn remove_if_current(&self, key: &K, flight: &Arc<Flight<V, E>>) {
        let mut flights = self.flights.lock();
        let is_current = flights
            .get(key)
            .is_some_and(|current| std::ptr::eq(current.as_ptr(), Arc::as_ptr(flight)));

        if is_current {
            flights.remove(key);
        }
    }

    fn has_active(&self, key: &K) -> bool {
        self.flights
            .lock()
            .get(key)
            .and_then(Weak::upgrade)
            .is_some()
    }

    #[cfg(test)]
    fn in_flight_len(&self) -> usize {
        self.flights.lock().len()
    }
}

impl<K, V, E> Default for Group<K, V, E> {
    fn default() -> Self {
        Self::new()
    }
}

struct LeaderGuard<'a, K, V, E>
where
    K: Eq + Hash + Clone,
{
    group: &'a Group<K, V, E>,
    key: &'a K,
    flight: Arc<Flight<V, E>>,
    armed: bool,
}

impl<'a, K, V, E> LeaderGuard<'a, K, V, E>
where
    K: Eq + Hash + Clone,
{
    fn new(group: &'a Group<K, V, E>, key: &'a K, flight: Arc<Flight<V, E>>) -> Self {
        Self {
            group,
            key,
            flight,
            armed: true,
        }
    }

    fn complete(mut self, result: Result<V, E>) -> SharedResult<V, E> {
        let result = Arc::new(result);
        self.flight.publish(Arc::clone(&result));
        self.group.remove_if_current(self.key, &self.flight);
        self.flight.wake_waiters();
        self.armed = false;
        result
    }
}

impl<K, V, E> Drop for LeaderGuard<'_, K, V, E>
where
    K: Eq + Hash + Clone,
{
    fn drop(&mut self) {
        if self.armed && self.flight.abort() {
            self.group.remove_if_current(self.key, &self.flight);
            self.flight.wake_waiters();
        }
    }
}

struct CacheEntry<V> {
    inserted_at: Instant,
    value: Arc<V>,
}

struct CacheSlot<V> {
    // Non-zero only while invalidation must prevent the sole per-key leader
    // that observed an older revision from populating this slot.
    revision: u64,
    entry: Option<CacheEntry<V>>,
}

struct CacheState<K, V> {
    clear_revision: u64,
    slots: HashMap<K, CacheSlot<V>>,
}

impl<K, V> CacheState<K, V> {
    fn new() -> Self {
        Self {
            clear_revision: 0,
            slots: HashMap::new(),
        }
    }
}

#[derive(Clone, Copy)]
struct CacheVersion {
    clear_revision: u64,
    key_revision: u64,
}

fn next_revision(revision: u64) -> u64 {
    let revision = revision.wrapping_add(1);
    if revision == 0 { 1 } else { revision }
}

struct CacheAttempt<'a, K, V>
where
    K: Eq + Hash + Clone,
{
    cache: &'a RwLock<CacheState<K, V>>,
    key: &'a K,
    version: CacheVersion,
    armed: bool,
}

impl<'a, K, V> CacheAttempt<'a, K, V>
where
    K: Eq + Hash + Clone,
{
    fn new(cache: &'a RwLock<CacheState<K, V>>, key: &'a K) -> Self {
        let version = {
            let cache = cache.read();
            CacheVersion {
                clear_revision: cache.clear_revision,
                key_revision: cache.slots.get(key).map_or(0, |slot| slot.revision),
            }
        };

        Self {
            cache,
            key,
            version,
            armed: true,
        }
    }

    fn cache(mut self, value: Arc<V>) {
        let mut cache = self.cache.write();
        if cache.clear_revision == self.version.clear_revision {
            match cache.slots.get_mut(self.key) {
                Some(slot) if slot.revision == self.version.key_revision => {
                    slot.revision = 0;
                    slot.entry = Some(CacheEntry {
                        inserted_at: Instant::now(),
                        value,
                    });
                }
                None if self.version.key_revision == 0 => {
                    cache.slots.insert(
                        self.key.clone(),
                        CacheSlot {
                            revision: 0,
                            entry: Some(CacheEntry {
                                inserted_at: Instant::now(),
                                value,
                            }),
                        },
                    );
                }
                Some(_) | None => {
                    Self::remove_marker(&mut cache, self.key);
                }
            }
        } else {
            Self::remove_marker(&mut cache, self.key);
        }
        self.armed = false;
    }

    fn remove_marker(cache: &mut CacheState<K, V>, key: &K) {
        if cache
            .slots
            .get(key)
            .is_some_and(|slot| slot.revision != 0 && slot.entry.is_none())
        {
            cache.slots.remove(key);
        }
    }
}

impl<K, V> Drop for CacheAttempt<'_, K, V>
where
    K: Eq + Hash + Clone,
{
    fn drop(&mut self) {
        if self.armed {
            Self::remove_marker(&mut self.cache.write(), self.key);
        }
    }
}

/// A [`Group`] layered with a success-only, in-memory TTL cache.
///
/// Cache hits use a read lock, allowing unrelated keys to be read
/// concurrently. Failed operations are not cached. Call
/// [`CachedGroup::purge_expired`] periodically if the key space is unbounded.
pub struct CachedGroup<K, V, E> {
    flight: Group<K, Arc<V>, Arc<E>>,
    cache: RwLock<CacheState<K, V>>,
    ttl: Duration,
}

impl<K, V, E> CachedGroup<K, V, E> {
    /// Creates an empty cached group.
    #[must_use]
    pub fn new(ttl: Duration) -> Self {
        Self {
            flight: Group::new(),
            cache: RwLock::new(CacheState::new()),
            ttl,
        }
    }

    /// Returns the configured time to live.
    #[must_use]
    pub const fn ttl(&self) -> Duration {
        self.ttl
    }
}

impl<K, V, E> CachedGroup<K, V, E>
where
    K: Eq + Hash + Clone,
{
    /// Returns a shared fresh value or coalesces a call to `operation`.
    ///
    /// The cache is checked again by the winning caller, and a successful
    /// result is cached before waiting callers are released. This closes the
    /// miss window between flight completion and cache population.
    ///
    /// Invalidating the key while the operation is running prevents that
    /// operation from repopulating the cache.
    pub async fn get_shared<F, Fut>(&self, key: K, operation: F) -> Result<Arc<V>, Arc<E>>
    where
        F: FnOnce() -> Fut,
        Fut: Future<Output = Result<V, E>>,
    {
        if let Some(value) = self.cached(&key) {
            return Ok(value);
        }

        let cache_key = key.clone();
        let result = self
            .flight
            .do_call_shared(key, move || async move {
                if let Some(value) = self.cached(&cache_key) {
                    return Ok(value);
                }

                let cache_attempt = CacheAttempt::new(&self.cache, &cache_key);
                match operation().await {
                    Ok(value) => {
                        let value = Arc::new(value);
                        cache_attempt.cache(Arc::clone(&value));
                        Ok(value)
                    }
                    Err(error) => Err(Arc::new(error)),
                }
            })
            .await;

        match result.as_ref() {
            Ok(value) => Ok(Arc::clone(value)),
            Err(error) => Err(Arc::clone(error)),
        }
    }

    /// Returns a fresh cached value or coalesces a call to `operation`.
    ///
    /// Prefer [`CachedGroup::get_shared`] for large or non-[`Clone`] results.
    pub async fn get<F, Fut>(&self, key: K, operation: F) -> Result<V, E>
    where
        V: Clone,
        E: Clone,
        F: FnOnce() -> Fut,
        Fut: Future<Output = Result<V, E>>,
    {
        match self.get_shared(key, operation).await {
            Ok(value) => Ok(value.as_ref().clone()),
            Err(error) => Err(error.as_ref().clone()),
        }
    }

    /// Invalidates `key` and prevents an in-flight operation from caching its
    /// result.
    ///
    /// Returns whether a cached value was present. Callers already joined to
    /// the current flight still receive that flight's result; the next flight
    /// executes the new operation.
    pub fn invalidate(&self, key: &K) -> bool {
        let has_active = self.flight.has_active(key);
        let mut cache = self.cache.write();

        if !has_active {
            return cache
                .slots
                .remove(key)
                .and_then(|slot| slot.entry)
                .is_some();
        }

        let slot = cache.slots.entry(key.clone()).or_insert(CacheSlot {
            revision: 0,
            entry: None,
        });
        slot.revision = next_revision(slot.revision);
        let was_cached = slot.entry.take().is_some();
        drop(cache);

        if !self.flight.has_active(key) {
            CacheAttempt::remove_marker(&mut self.cache.write(), key);
        }
        was_cached
    }

    /// Removes all cached values and prevents currently in-flight operations
    /// from repopulating the cache.
    pub fn clear(&self) {
        let mut cache = self.cache.write();
        cache.clear_revision = next_revision(cache.clear_revision);
        cache.slots.clear();
    }

    /// Removes expired cached values and returns the number removed.
    ///
    /// Abandoned invalidation markers are also reclaimed but are not included
    /// in the returned count.
    pub fn purge_expired(&self) -> usize {
        let (expired, markers) = {
            let mut cache = self.cache.write();
            let mut expired = 0;
            let mut markers = Vec::new();
            cache.slots.retain(|key, slot| {
                if slot.revision != 0 {
                    markers.push(key.clone());
                    return true;
                }

                let fresh = slot
                    .entry
                    .as_ref()
                    .is_some_and(|entry| entry.inserted_at.elapsed() < self.ttl);
                expired += usize::from(!fresh);
                fresh
            });
            (expired, markers)
        };

        for key in markers {
            if !self.flight.has_active(&key) {
                CacheAttempt::remove_marker(&mut self.cache.write(), &key);
            }
        }
        expired
    }

    fn cached(&self, key: &K) -> Option<Arc<V>> {
        let cache = self.cache.read();
        cache
            .slots
            .get(key)
            .and_then(|slot| slot.entry.as_ref())
            .filter(|entry| entry.inserted_at.elapsed() < self.ttl)
            .map(|entry| Arc::clone(&entry.value))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{
        convert::Infallible,
        future::pending,
        sync::atomic::{AtomicUsize, Ordering},
    };
    use tokio::{
        sync::{Barrier, Notify},
        task::JoinSet,
        time::{sleep, timeout},
    };

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn coalesces_concurrent_calls_for_the_same_key() {
        const CALLERS: usize = 64;

        let group = Arc::new(Group::<&str, usize, Infallible>::new());
        let barrier = Arc::new(Barrier::new(CALLERS));
        let executions = Arc::new(AtomicUsize::new(0));
        let mut calls = JoinSet::new();

        for _ in 0..CALLERS {
            let group = Arc::clone(&group);
            let barrier = Arc::clone(&barrier);
            let executions = Arc::clone(&executions);
            calls.spawn(async move {
                barrier.wait().await;
                group
                    .do_call("channel", || async move {
                        executions.fetch_add(1, Ordering::SeqCst);
                        sleep(Duration::from_millis(25)).await;
                        Ok(42)
                    })
                    .await
            });
        }

        while let Some(result) = calls.join_next().await {
            assert_eq!(result.unwrap(), Ok(42));
        }
        assert_eq!(executions.load(Ordering::SeqCst), 1);
        assert_eq!(group.in_flight_len(), 0);
    }

    #[tokio::test]
    async fn operations_for_different_keys_are_independent() {
        let group = Arc::new(Group::<&str, usize, Infallible>::new());
        let first_started = Arc::new(Notify::new());
        let release_first = Arc::new(Notify::new());

        let first = {
            let group = Arc::clone(&group);
            let first_started = Arc::clone(&first_started);
            let release_first = Arc::clone(&release_first);
            tokio::spawn(async move {
                group
                    .do_call("first", || async move {
                        first_started.notify_one();
                        release_first.notified().await;
                        Ok(1)
                    })
                    .await
            })
        };

        first_started.notified().await;
        let second = timeout(
            Duration::from_millis(100),
            group.do_call("second", || async { Ok(2) }),
        )
        .await
        .unwrap();
        assert_eq!(second, Ok(2));

        release_first.notify_one();
        assert_eq!(first.await.unwrap(), Ok(1));
    }

    #[tokio::test]
    async fn shares_errors() {
        let group = Arc::new(Group::<&str, (), &'static str>::new());
        let started = Arc::new(Barrier::new(2));

        let leader = {
            let group = Arc::clone(&group);
            let started = Arc::clone(&started);
            tokio::spawn(async move {
                group
                    .do_call("key", || async move {
                        started.wait().await;
                        sleep(Duration::from_millis(10)).await;
                        Err("failed")
                    })
                    .await
            })
        };

        started.wait().await;
        let follower = group.do_call("key", || async { Ok(()) });
        assert_eq!(follower.await, Err("failed"));
        assert_eq!(leader.await.unwrap(), Err("failed"));
    }

    #[tokio::test]
    async fn shared_api_supports_non_clone_results() {
        #[derive(Debug, PartialEq)]
        struct NonClone(usize);

        let group = Arc::new(Group::<&str, NonClone, NonClone>::new());
        let release = Arc::new(Notify::new());
        let started = Arc::new(Notify::new());

        let leader = {
            let group = Arc::clone(&group);
            let release = Arc::clone(&release);
            let started = Arc::clone(&started);
            tokio::spawn(async move {
                group
                    .do_call_shared("key", || async move {
                        started.notify_one();
                        release.notified().await;
                        Ok(NonClone(7))
                    })
                    .await
            })
        };

        started.notified().await;
        let follower = {
            let group = Arc::clone(&group);
            tokio::spawn(async move {
                group
                    .do_call_shared("key", || async { Err(NonClone(9)) })
                    .await
            })
        };
        tokio::task::yield_now().await;
        release.notify_one();

        let leader_result = leader.await.unwrap();
        let follower_result = follower.await.unwrap();
        assert!(Arc::ptr_eq(&leader_result, &follower_result));
        assert_eq!(leader_result.as_ref(), &Ok(NonClone(7)));
    }

    #[tokio::test]
    async fn recovers_when_the_leader_is_cancelled() {
        let group = Arc::new(Group::<&str, usize, Infallible>::new());
        let started = Arc::new(Notify::new());
        let recovery_executions = Arc::new(AtomicUsize::new(0));

        let leader = {
            let group = Arc::clone(&group);
            let started = Arc::clone(&started);
            tokio::spawn(async move {
                group
                    .do_call("key", || async move {
                        started.notify_one();
                        pending::<Result<usize, Infallible>>().await
                    })
                    .await
            })
        };

        started.notified().await;
        let follower = {
            let group = Arc::clone(&group);
            let recovery_executions = Arc::clone(&recovery_executions);
            tokio::spawn(async move {
                group
                    .do_call("key", || async move {
                        recovery_executions.fetch_add(1, Ordering::SeqCst);
                        Ok(11)
                    })
                    .await
            })
        };

        tokio::task::yield_now().await;
        leader.abort();
        assert!(leader.await.unwrap_err().is_cancelled());
        assert_eq!(
            timeout(Duration::from_secs(1), follower)
                .await
                .unwrap()
                .unwrap(),
            Ok(11)
        );
        assert_eq!(recovery_executions.load(Ordering::SeqCst), 1);
        assert_eq!(group.in_flight_len(), 0);
    }

    #[tokio::test]
    async fn cancellation_without_waiters_removes_the_flight() {
        let group = Arc::new(Group::<&str, usize, Infallible>::new());
        let started = Arc::new(Notify::new());

        let leader = {
            let group = Arc::clone(&group);
            let started = Arc::clone(&started);
            tokio::spawn(async move {
                group
                    .do_call("key", || async move {
                        started.notify_one();
                        pending::<Result<usize, Infallible>>().await
                    })
                    .await
            })
        };

        started.notified().await;
        leader.abort();
        assert!(leader.await.unwrap_err().is_cancelled());
        assert_eq!(group.in_flight_len(), 0);
        assert_eq!(group.do_call("key", || async { Ok(12) }).await, Ok(12));
    }

    #[tokio::test]
    async fn recovers_when_the_leader_panics() {
        let group = Arc::new(Group::<&str, usize, Infallible>::new());
        let started = Arc::new(Notify::new());

        let leader = {
            let group = Arc::clone(&group);
            let started = Arc::clone(&started);
            tokio::spawn(async move {
                group
                    .do_call("key", || async move {
                        started.notify_one();
                        sleep(Duration::from_millis(10)).await;
                        panic!("leader failed");
                    })
                    .await
            })
        };

        started.notified().await;
        let follower = {
            let group = Arc::clone(&group);
            tokio::spawn(async move { group.do_call("key", || async { Ok(13) }).await })
        };

        assert!(leader.await.unwrap_err().is_panic());
        assert_eq!(follower.await.unwrap(), Ok(13));
        assert_eq!(group.in_flight_len(), 0);
    }

    #[tokio::test]
    async fn cached_group_coalesces_and_honors_ttl() {
        let group = Arc::new(CachedGroup::<&str, usize, Infallible>::new(
            Duration::from_millis(250),
        ));
        let executions = Arc::new(AtomicUsize::new(0));
        let barrier = Arc::new(Barrier::new(8));
        let mut calls = JoinSet::new();

        for _ in 0..8 {
            let group = Arc::clone(&group);
            let executions = Arc::clone(&executions);
            let barrier = Arc::clone(&barrier);
            calls.spawn(async move {
                barrier.wait().await;
                group
                    .get("key", || async move {
                        executions.fetch_add(1, Ordering::SeqCst);
                        sleep(Duration::from_millis(5)).await;
                        Ok(17)
                    })
                    .await
            });
        }

        while let Some(result) = calls.join_next().await {
            assert_eq!(result.unwrap(), Ok(17));
        }
        assert_eq!(executions.load(Ordering::SeqCst), 1);

        assert_eq!(group.get("key", || async { Ok(99) }).await, Ok(17));
        assert_eq!(executions.load(Ordering::SeqCst), 1);

        sleep(Duration::from_millis(275)).await;
        assert_eq!(group.purge_expired(), 1);
        let executions_for_refresh = Arc::clone(&executions);
        assert_eq!(
            group
                .get("key", || async move {
                    executions_for_refresh.fetch_add(1, Ordering::SeqCst);
                    Ok(23)
                })
                .await,
            Ok(23)
        );
        assert_eq!(executions.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn cached_shared_api_avoids_cloning_values() {
        #[derive(Debug, PartialEq)]
        struct NonClone(usize);

        let group = CachedGroup::<&str, NonClone, NonClone>::new(Duration::from_secs(60));
        let fetched = group
            .get_shared("key", || async { Ok(NonClone(31)) })
            .await
            .unwrap();
        let cached = group
            .get_shared("key", || async { Err(NonClone(32)) })
            .await
            .unwrap();

        assert!(Arc::ptr_eq(&fetched, &cached));
        assert_eq!(fetched.as_ref(), &NonClone(31));
    }

    #[tokio::test]
    async fn invalidation_wins_against_an_in_flight_result() {
        let group = Arc::new(CachedGroup::<&str, usize, Infallible>::new(
            Duration::from_secs(60),
        ));
        let started = Arc::new(Notify::new());
        let release = Arc::new(Notify::new());

        let first = {
            let group = Arc::clone(&group);
            let started = Arc::clone(&started);
            let release = Arc::clone(&release);
            tokio::spawn(async move {
                group
                    .get("key", || async move {
                        started.notify_one();
                        release.notified().await;
                        Ok(37)
                    })
                    .await
            })
        };

        started.notified().await;
        assert!(!group.invalidate(&"key"));
        release.notify_one();
        assert_eq!(first.await.unwrap(), Ok(37));

        assert_eq!(group.get("key", || async { Ok(41) }).await, Ok(41));
        assert_eq!(group.get("key", || async { Ok(43) }).await, Ok(41));
    }

    #[tokio::test]
    async fn clear_wins_against_in_flight_results() {
        let group = Arc::new(CachedGroup::<&str, usize, Infallible>::new(
            Duration::from_secs(60),
        ));
        let started = Arc::new(Notify::new());
        let release = Arc::new(Notify::new());

        let first = {
            let group = Arc::clone(&group);
            let started = Arc::clone(&started);
            let release = Arc::clone(&release);
            tokio::spawn(async move {
                group
                    .get("key", || async move {
                        started.notify_one();
                        release.notified().await;
                        Ok(47)
                    })
                    .await
            })
        };

        started.notified().await;
        group.clear();
        release.notify_one();
        assert_eq!(first.await.unwrap(), Ok(47));

        assert_eq!(group.get("key", || async { Ok(53) }).await, Ok(53));
        assert_eq!(group.get("key", || async { Ok(59) }).await, Ok(53));
    }

    #[tokio::test]
    async fn cached_group_does_not_cache_errors() {
        let group = CachedGroup::<&str, usize, &'static str>::new(Duration::from_secs(60));
        assert_eq!(
            group.get("key", || async { Err("temporary") }).await,
            Err("temporary")
        );
        assert_eq!(group.get("key", || async { Ok(29) }).await, Ok(29));
    }
}